【问题标题】:How can I enable parallelism via pytest -nauto if pytest-xdist is installed?如果安装了 pytest-xdist,如何通过 pytest -nauto 启用并行性?
【发布时间】:2019-01-04 15:57:40
【问题描述】:

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

[pytest]
addopts = -nauto

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

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

【问题讨论】:

    标签: python pytest xdist


    【解决方案1】:

    您可以检查xdist 选项组是否定义了numprocesses arg。这表明pytest-xdist 已安装并且将处理该选项。如果不是这种情况,您自己的虚拟 arg 将确保 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;但是,您需要使用 long 选项:

    [pytest]
    addopts=--numprocesses=auto
    

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

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

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

    [pytest]
    addopts=-nauto
    

    【讨论】:

    • options 属性没有公开记录,可以依赖它吗?
    • 不幸的是,OptionGroupArgument 对象都没有记录在 API reference 中,所以这里不能保证。总的来说,我不喜欢这个解决方案,因为添加无用的参数感觉就像是 hack。我会想一个更好的解决方案,但是现在,重新配置 xdist 看起来比在 cli 解析器周围进行黑客攻击还要糟糕。
    • 这确实有点hacky,并且不允许区分pytest -nauto(由用户给出)和默认配置所暗示的(在前一种情况下,可能想直接出错)。现在我决定在使用 pytest 时要求安装 xdist,这样更简单。
    猜你喜欢
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2021-06-22
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多