python - 如果安装了 pytest-xdist,如何通过 pytest -nauto 启用并行性?

标签 python pytest xdist

要启用并行测试,必须安装pytest-xdist并使用将-nauto选项传递给pytest以使用所有可用的CPU 。我想默认启用 -nauto,但仍然使 pytest-xdist 可选。所以这行不通:

[pytest]
addopts = -nauto

如果安装了pytest-xdist,有没有办法默认启用pytest并行性? (如果需要的话,也可以使用 pytest -n0 再次禁用它。)

我想必须编写某种conftest.py钩子(Hook)?是possible检测已安装的插件,但是 pytest_configure在加载插件后运行,这可能为时已晚。此外,我不确定此时如何添加选项(或如何配置直接操作 xdist)。

最佳答案

您可以检查xdist选项组是否定义了numprocesses参数。这表明 pytest-xdist 已安装并且该选项将被处理。如果情况并非如此,您自己的虚拟参数将确保 pytest 知道该选项(并安全地忽略):

# conftest.py

def pytest_addoption(parser):
    argdests = {arg.dest for arg in parser.getgroup('xdist').options}
    if 'numprocesses' not in argdests:
        parser.getgroup('xdist').addoption(
            '--numprocesses', dest='numprocesses', metavar='numprocesses', action='store',
            help="placeholder for xdist's numprocesses arg; passed value is ignored if xdist is not installed"
    )

现在,即使未安装 pytest-xdist,您也可以将该选项保留在 pytest.ini 中;但是,您需要使用长选项:

[pytest]
addopts=--numprocesses=auto

原因是短选项是为 pytest 本身保留的,因此上面的代码没有定义或使用它。如果您确实需要短选项,则必须诉诸私有(private)方法:

parser.getgroup('xdist')._addoption('-n', '--numprocesses', dest='numprocesses', ...)

现在您可以在配置中使用短选项:

[pytest]
addopts=-nauto

关于python - 如果安装了 pytest-xdist,如何通过 pytest -nauto 启用并行性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042282/

相关文章:

python - 我什么时候可以安全地使用 float 来做数学?

python - Tensorflow Dataset API 读取 csv 转换 tfrecords

初始化派生类和抽象类时出现python错误

python - pytest 使用变量自省(introspection)断言消息自定义

selenium - 使用 Docker、Selenium 和 Pytest 运行并行测试

python - 为什么 cross_val_score 和我手动计算的不一样?

python - 使用 python 3.3 运行 pytest

python - 如何在 Azure DevOps(服务器)管道中测试 dockerized 应用程序?

python - 有没有办法控制 pytest-xdist 如何并行运行测试?

python - 使用 pytest-xdist 跨主节点和工作节点访问共享资源