我们使用pytest测试我们的项目,并默认启用--doctest-modules
来收集整个项目的所有doctests。
然而,有一个wsgi.py
在测试收集期间可能无法导入,但我无法让pytest忽略它。
我尝试将它放在collect_ignore
的conftest.py
列表中,但显然doctest模块不使用此列表。
唯一可行的是将wsgi.py
的整个目录放入pytest配置文件中的norecursedirs
,但这显然隐藏了整个目录,这是我不想要的。
有没有办法让doctest模块只忽略某个文件?
您可以使用hook有条件地从测试发现中排除某些文件夹。 https://docs.pytest.org/en/latest/writing_plugins.html
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
放到根文件夹(您运行测试的文件夹)。
例:
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/