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

2024-09-27 19:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

要启用并行测试,必须安装pytest-xdist,并使用将-nauto选项传递给pytest以使用所有可用的cpu。我希望在默认情况下启用-nauto,但仍将pytest-xdist设为可选。所以这行不通:

[pytest]
addopts = -nauto

如果安装了pytest-xdist,是否有一种方法可以在默认情况下启用pytest并行性?(如果需要,还可以使用pytest -n0再次禁用它。)

我想一定要写某种conftest.py钩子?{{a2插件可能安装得太晚了,但是^安装插件后}可能太晚了。此外,我不确定在那个时候如何添加选项(或者如何配置直接操纵xdist)。在


Tags: 方法py插件a2pytest选项情况cpu
1条回答
网友
1楼 · 发布于 2024-09-27 19:30:39

您可以检查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.ini中保留该选项,即使没有安装pytest-xdist;但是,您需要使用long选项:

^{pr2}$

原因是短选项是为pytest本身保留的,所以上面的代码没有定义或使用它。如果你真的需要做空期权,你必须求助于私人方法:

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

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

[pytest]
addopts=-nauto

相关问题 更多 >

    热门问题