关于python:我可以让pytest doctest模块忽略文件吗?

Can I make the pytest doctest module ignore a file?

我们使用pytest来测试我们的项目,并且默认情况下启用了--doctest-modules来收集整个项目中的所有doctest。

但是,有一个wsgi.py可能不会在测试收集期间导入,但是我无法让pytest忽略它。

我尝试将其放在conftest.pycollect_ignore列表中,但显然doctest模块不使用此列表。

唯一有效的方法是将wsgi.py的整个目录放入pytest配置文件中的norecursedirs中,但这显然隐藏了整个目录,我不想这样做。

有没有一种方法可以使doctest模块仅忽略某个文件?


您可以使用挂钩有条件地从测试发现中排除某些文件夹。
https://docs.pytest.org/en/latest/writing_plugins.html

1
2
3
4
5
def pytest_ignore_collect(path, config):
   """ return True to prevent considering this path for collection.
    This hook is consulted for all files and directories prior to calling
    more specific hooks.
   """

正如MasterAndrey所提到的,pytest_ignore_collect应该可以解决问题。 重要的是要注意,应该将conftest.py放到根文件夹(运行测试的文件夹)中。
例:

1
2
3
4
5
6
7
8
9
import sys

def pytest_ignore_collect(path):
    if sys.version_info[0] > 2:
        if str(path).endswith("__py2.py"):
            return True
    else:
        if str(path).endswith("__py3.py"):
            return True

从pytest v4.3.0开始,还有--ignore-glob标志,允许按模式忽略。 例:
pytest --doctest-modules --ignore-glob="*__py3.py" dir/