【问题标题】:Doctest fails when normal output and exception mixed together?当正常输出和异常混合在一起时,Doctest 失败?
【发布时间】:2016-12-16 20:59:51
【问题描述】:

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.

【问题讨论】:

    标签: python testing doctest


    【解决方案1】:

    docs 说你不能这样做:

    不支持同时包含预期输出和异常的示例。试图猜测一个结束和另一个开始的地方太容易出错,这也会使测试变得混乱。

    【讨论】:

      【解决方案2】:

      常规输出和回溯不能混合,因为它们只是无法区分的文本。但是,您可以包装块,捕获您期望的异常:

      >>> try:
      ...     foo_bar()
      ... except TheSpecificExceptionYouWant:
      ...     pass
      ... else:
      ...     raise AssertionError('Should have raised an exception')
      hello world!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 1970-01-01
        • 2018-12-29
        • 2019-05-12
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多