如何在方法docString /评论中从特殊语法中自动生成单元测试例程?
这是我要寻找的内容的模型:
def is_even(a, b):
"""Returns True if both numbers are even.
@AutoUnitTestTag:
- (0,2) -> True
- (2,1) -> False
- (3,5) -> False
"""
return (a % 2 == 0 and b % 2 == 0)
是否有一个工具可以允许一个工具在函数的DocString中插入紧凑型语法定义的单元测试,然后自动生成unittest_foobar.py
unit测试例程?
我几乎确定我已经看过这件事了,但是找不到。
编辑: @mkrieger1建议doctest 在下面的评论中,在使用它之后,我说这是一个非常适合的解决方案。 但是,我想让这个问题持续更长的时间,以收集更多建议,尤其是关于更复杂的工具。
如果有人有兴趣,以下是在我的示例情况下使用医生的方式:
- so中的格式函数。
def is_even(a,b):
"""Returns True if both numbers are even.
>>> is_even(0,2)
True
>>> is_even(2,1)
False
>>> is_even(3,5)
False
"""
return (a % 2 == 0 and b % 2 == 0)
- file
is_even.py
。 输出看起来像:
Trying:
is_even(0,2)
Expecting:
True
ok
Trying:
is_even(2,1)
Expecting:
False
ok
Trying:
is_even(3,5)
Expecting:
False
ok
1 items had no tests:
foo2
1 items passed all tests:
3 tests in foo2.is_even
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
This is a mock-up of what I'm looking for:
def is_even(a, b):
"""Returns True if both numbers are even.
@AutoUnitTestTag:
- (0,2) -> True
- (2,1) -> False
- (3,5) -> False
"""
return (a % 2 == 0 and b % 2 == 0)
Is there a tool that could allow one to insert compact syntax-defined unit tests within a function's docstring and then automatically generate a unittest_foobar.py
unit testing routine?
I'm almost sure I've seen this a while ago, but cannot find it.
EDIT: @mkrieger1 suggested doctest
in the comments below and after playing a bit with it, I'd say it's a pretty apt solution.
However, I'd like to let this question linger a bit longer in order to collect more suggestions, especially about more sophisticated tools.
If someone's interested, here's how one would use doctest in my example case:
- Format function in file
is_even.py
like so:
def is_even(a,b):
"""Returns True if both numbers are even.
>>> is_even(0,2)
True
>>> is_even(2,1)
False
>>> is_even(3,5)
False
"""
return (a % 2 == 0 and b % 2 == 0)
- Then run the command
python3 -m doctest is_even.py
.
The output will look like so:
Trying:
is_even(0,2)
Expecting:
True
ok
Trying:
is_even(2,1)
Expecting:
False
ok
Trying:
is_even(3,5)
Expecting:
False
ok
1 items had no tests:
foo2
1 items passed all tests:
3 tests in foo2.is_even
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它称为 doctect ,这是标准库的一部分。但是您必须对语法进行一些更改:
您可以使用它来运行:
该语法已设计为设计,以便您可以从交互式(C)Python解释器会话中复制和粘贴测试,因此有充分的理由不去尝试更改它。此外,其他Python开发人员将已经熟悉此语法,而不是您可能想出的任何自定义。
It's called doctest and it's part of the standard library. But you'll have to change your syntax a bit:
You can run it with:
The syntax has been designed so that you can mostly copy and paste your tests from an interactive (C)Python interpreter session, so there is good reason not to try and change it. Moreover, other Python developers will already be familiar with this syntax, and not with anything custom you might come up with.