5

有时只运行大型 doctests 文件的第一部分会很有用。

在代码更改后第一部分中断的情况有很多,我想只运行第一部分,直到它通过,然后再次运行整个文件。

我还没有找到一个简单的方法来做到这一点。

假设我用这个文件开始我的文档测试:

#!/usr/bin/env python
import doctest
doctest.testfile("scenario.rst")

而scenario.rst 看起来像这样:

>>> 'hello world'
'hello world'

>>> exit()

>>> 'this should not be processed anymore'

... lots of lines

>>> 'this should also not be processed'

在这个例子中,我使用 exit() 函数来演示我的意思,当然它不起作用,因为它被视为异常,doctest 很高兴地将其视为可以测试的东西的一部分:

**********************************************************************
File "_scenario.rst", line 10, in _scenario.rst
Failed example:
    exit()
Exception raised:
    Traceback (most recent call last):
      File "c:\Python27\lib\doctest.py", line 1254, in __run
        compileflags, 1) in test.globs
      File "<doctest _scenario.rst[1]>", line 1, in <module>
        exit()
      File "c:\Python27\lib\site.py", line 372, in __call__
        raise SystemExit(code)
    SystemExit: None
**********************************************************************
File "_scenario.rst", line 12, in _scenario.rst
Failed example:
    'this should not be processed anymore'
Expected nothing
Got:
    'this should not be processed anymore'
**********************************************************************
1 items had failures:
   2 of   3 in _scenario.rst
***Test Failed*** 2 failures.

那么这样一个doctest文件怎么会在中间被终止呢?

编辑:有 +SKIP 指令,但它只跳过一行。我需要一些跳过文件其余部分的东西。

4

3 回答 3

4

这就是我所做的:我插入

>>> 'ERROR'

在我想停止 doctest 文件的地方,然后我要求我的测试运行程序启用 doctest.REPORT_ONLY_FIRST_FAILURE 标志(使用 zope.testrunner 它是bin/test -1)。

也许这样做就足够了

>>> 'ERROR'  # doctest: +REPORT_ONLY_FIRST_FAILURE

在您的 doctest 文件中。

就个人而言,我不喜欢doctest.testfile. 我更喜欢创建一个doctest.DocFileSuite(),将一堆这些组合成一个unittest.TestSuite(),然后用unittest.TextTestRunner()类似的东西运行它们。我通常optionflags=doctest.REPORT_ONLY_FIRST_FAILURE在创建 DocFileSuite 对象时添加,因为我真的很喜欢这个选项。

于 2012-03-19T17:19:52.077 回答
3
>>> raise KeyboardInterrupt

与所有其他例外情况不同,这将在任何时候停止Doctest

就个人而言,我认为 KeyboardInterrupt 异常是针对 doctest 的,因为 SystemExit 异常是针对 Python 的其余部分。

于 2013-08-22T15:36:45.250 回答
0

根据此错误报告,目前有两种解决方法:

  • 将 >>> 替换为 >>
  • 拆分文档字符串,并在第二部分前面添加类似“ dont_test =”的内容;字符串成为语句的一部分,不会被解析。
于 2012-03-19T13:50:26.080 回答