仅当使用过滤器调用pytest时如何禁用pytest xdist?

How to disable pytest xdist only when pytest is called with filters?

当我 运行 所有 pytests 时,我确实希望从所有 m 核 (xdist) 上分散负载中充分受益,但是当我 运行 它们的一个子集几乎总是用于 development/debugging 目的,在这种情况下我确实想避免 xdist 的缺点:

例如:调用 pytest -k foo 应该有效地 运行 pytest -n0 -k foo。请记住,调用不带参数的 pytest 不应影响 -n 值。

您可以dynamically add the option,例如:

conftest.py

import sys

def pytest_cmdline_preparse(args):
    if "xdist" in sys.modules and "-k" in args:
        for i, arg in enumerate(args):
            # remove -n # option
            if arg == "-n":
                del args[i]
                del args[i]
                break
            # remove -n# option
            if re.match(r"-n\d+", arg):
                del args[i]
                break

        args[:] = ["-n0"] + args

这将删除现有的“-n”选项(-n #-n# 形式 - 您可能不需要两者,具体取决于命令行的外观),并添加“ -n0" 选项。

更新:
pytest_cmdline_preparse 在当前 (6.x) pytest 版本中已弃用,可以以相同的方式使用 pytest_load_initial_conftests