python - 当正常输出和异常混合在一起时 Doctest 失败?

标签 python testing doctest

doctest 是否支持输出和异常混合在一起?

一个例子是:

>>> def foo():
...    print 'hello world!'
>>> foo()
hello world!
>>> def bar():
...     raise Exception()
>>> bar()
Traceback (most recent call last):
    ...
Exception

>>> def foo_bar():
...     foo()
...     bar()
>>> foo_bar()
hello world!
Traceback (most recent call last):
    ...
Exception

我希望所有三个案例都应该成功,但只有两个成功,请参阅

$ python -m doctest -v /tmp/1.py
Trying:
    def foo():
       print 'hello world!'
Expecting nothing
ok
Trying:
    foo()
Expecting:
    hello world!
ok
Trying:
    def bar():
        raise Exception()
Expecting nothing
ok
Trying:
    bar()
Expecting:
    Traceback (most recent call last):
        ...
    Exception
ok
Trying:
    def foo_bar():
        foo()
        bar()
Expecting nothing
ok
Trying:
    foo_bar()
Expecting:
    hello world!
    Traceback (most recent call last):
        ...
    Exception
**********************************************************************
File "/tmp/1.py", line 16, in 1
Failed example:
    foo_bar()
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python2.7/doctest.py", line 1315, in __run
        compileflags, 1) in test.globs
      File "<doctest 1[5]>", line 1, in <module>
        foo_bar()
      File "<doctest 1[4]>", line 3, in foo_bar
        bar()
      File "<doctest 1[2]>", line 2, in bar
        raise Exception()
    Exception
**********************************************************************
1 items had failures:
   1 of   6 in 1
6 tests in 1 items.
5 passed and 1 failed.
***Test Failed*** 1 failures.

最佳答案

docs说你不能那样做:

Examples containing both expected output and an exception are not supported. Trying to guess where one ends and the other begins is too error-prone, and that also makes for a confusing test.

关于python - 当正常输出和异常混合在一起时 Doctest 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192354/

相关文章:

c# - 测试 : How to verify that a method is called?

python - 使用 doctest 测试警告

python - 将存储为 numpy 数组的图像转换为 hsv 的有效方法

python - 我可以使用 pathlib.Path 解析环境变量而不使用 os.path.expandvars 吗?

mysql - Junit:测试查询类

python-2.6 - 如何编写关于路径分隔符的独立于操作系统的 Python doctest

unit-testing - 有没有办法使用 Elixir 中的 Doctest 测试 IO 输出?

Pythonic 相当于 unshift 或 redo?

python - Pandas:查找由开始列和停止列定义的多个范围内的值

unit-testing - 严格捕获用于单元测试的测试用例