要启用并行测试,必须安装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/