如何修改pytest参数?

5

我发现我可以使用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。

我做错了什么?请帮我运行它。

conftest.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

test_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)

这不就是 -n auto 的作用吗? - JoseKilo
无论如何,在 sys.modules 中出现之前,您可能需要导入 xdist。您可以使用 try: import xdist except ImportError: pass,以便在未安装时不会因导入而停止执行。 - JoseKilo
2个回答

3

7
那么,鉴于此,pytest_load_initial_conftests 函数应放置在哪里才能被调用? - MauroNeira
@Antidemiurge 请查看我下面的回答。花了几乎整个一天来阅读文档。 - Karishma Sukhwani

2

添加额外插件以使pytest参数动态化

根据API文档pytest_load_initial_conftests钩子将不会在conftest.py文件中调用,只能在插件中使用。

此外,pytest文档提到了如何编写用于pytest的自定义插件并使其可安装。

按照以下步骤:

在根目录下创建以下文件

- ./setup.py
- ./plugin.py
- ./tests/conftest.py
- ./pyproject.toml

# contents of ./setup.py
from setuptools import setup

setup(
    name='my_project',
    version='0.0.1',
    entry_points={
        'console_scripts': [
        ], # feel free to add if you have any
        "pytest11": ["custom_args = plugin"]
    },
    classifiers=["Framework :: Pytest"],
)

注意,这里保留了python11,根据我的阅读,它是为添加pytest插件而保留的。

# contents of ./plugin.py

import sys

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


# contents of ./tests/conftest.py

pytest_plugins = ["custom_args"] # allows to load plugin while running tests

# ... other fixtures and hooks

最终,该项目的pyproject.toml文件。
# contents of ./pyproject.toml

[tool.setuptools]
py-modules = []

[tool.setuptools]
py-modules = []

[build-system]
requires = [
  "setuptools",
]
build-backend = "setuptools.build_meta"

[project]
name = "my_package"
description = "My package description"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
    "Framework :: Flask",
    "Programming Language :: Python :: 3",
]
dynamic = ["version"]


这将动态添加-n参数及其值,根据您的系统具有的CPU数量启用并行运行。
希望这可以帮到您,欢迎留言评论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接