我可以让pytest doctest模块忽略一个文件吗?

问题描述 投票:10回答:2

我们使用pytest测试我们的项目,并默认启用--doctest-modules来收集整个项目的所有doctests。

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

我尝试将它放在collect_ignoreconftest.py列表中,但显然doctest模块不使用此列表。

唯一可行的是将wsgi.py的整个目录放入pytest配置文件中的norecursedirs,但这显然隐藏了整个目录,这是我不想要的。

有没有办法让doctest模块只忽略某个文件?

python pytest doctest
2个回答
4
投票

您可以使用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.
    """

1
投票

正如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/

© www.soinside.com 2019 - 2024. All rights reserved.