为什么 py.test 向后运行模块 doctests?

Why does py.test runs modules doctests backwards?

如果我有这两个文件:

first_module.py

def add(a, b):
    """
    >>> add(1, 2) # should this not fail first?
    3
    """
    return a - b # (because here's the mistake)

second_module.py

from first_module import *

def anti_add(a, b):
    """
    >>> anti_add(1, 2) # why does this fail first?
    -3
    """
    return -add(a, b)

而我运行:

py.test --doctest-modules -x second_module.py

我得到:

========================================== FAILURES ===========================================
__________________________________ [doctest] second_module.anti_add __________________________________
005 
006     >>> anti_add(1, 2) # why does this fail first?
Expected:
    -3
Got:
    1

.../second_module.py:6: DocTestFailure

但我实际上希望第一个测试首先失败,因为 add 需要 anti_add 才能正常工作。
我有时会感到困惑,因为 anti_add 测试因 add 中的错误而失败,但我在 add 中没有看到失败,所以我认为它工作正常。

如何在模块中以相反的方式进行 py.test 运行 测试?

遗憾的是pytest没有这样的功能。它只能 运行 测试选定的文件或文件夹。

这个命令:

pytest --doctest-modules -x second_module.py

意味着 pytest 将扫描文件 second_module.py 中的文档字符串并为它们进行 运行 测试(-x 表示第一次失败时停止)。它不会在所需模块中查找文档字符串。

如果你想测试所有模块,你可以简单地使用:

pytest --doctest-modules 

或尝试选项--doctest-glob。