如何修改 pytest 参数?

lun*_*nin 5 python automated-tests pytest xdist

我发现为此目的我可以使用 PyTest 函数 pytest_load_initial_conftests()

https://docs.pytest.org/en/latest/example/simple.html#dynamically-adding-command-line-options

但我无法正确实现这个示例(请参阅链接)。

pytest_load_initial_conftests()甚至没有启动(通过调试查看)。测试在没有任何参数(一个线程)的情况下正常运行,但我期望“-n”参数。

我安装了 pytest 和 xdist。项目中只有两个文件。没有 pytest.ini。

我究竟做错了什么?请帮忙运行一下。

测试.py

import pytest
import os
import sys


def pytest_addoption(parser):
    parser.addoption('--some_param', action='store', help='some_param', default='')


def pytest_configure(config):
    some_param = config.getoption('--some_param')


def pytest_load_initial_conftests(args):
    if "xdist" in sys.modules:
        import multiprocessing
        num = max(multiprocessing.cpu_count() / 2, 1)
        args[:] = ["-n", str(num)] + args
Run Code Online (Sandbox Code Playgroud)

测试_t1.py

import inspect
from time import sleep
import os
import pytest


class Test_Run:

    def test_1(self):
        body()

    def test_2(self):
        body()

    def test_3(self):
        body()

    def test_4(self):
        body()

    def setup(self):
        pass

    def teardown(self):
        pass


def body():
    sleep(5)
Run Code Online (Sandbox Code Playgroud)

Jos*_*ilo 3

根据文档pytest_load_initial_conftests

注意:conftest.py 文件不会调用此挂钩,仅适用于 setuptools 插件。

https://docs.pytest.org/en/latest/reference/reference.html#pytest.hookspec.pytest_load_initial_conftests

可能不应该在您找到的页面上提及它。

编辑:更新文档网址

  • 那么考虑到这一点,“pytest_load_initial_conftests”函数应该放在哪里才能被调用呢? (7认同)