我发现为了这个目的,我可以使用PyTest函数PyTest_load_initial_contests((
https://docs.pytest.org/en/latest/example/simple.html#dynamically-添加命令行选项
但是我不能正确地实现这个例子(见链接(。
pytest_load_initial_contests((甚至没有启动(通过调试查看(。测试在没有任何params(一个线程(的情况下正常运行,但我需要"-n"param。
我安装了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)
根据pytest_load_initial_conftests
:上的文档
注意:这个钩子不会为conftest.py文件调用,只为setuptools插件。
https://docs.pytest.org/en/latest/reference/reference.html#pytest.hookspec.pytest_load_initial_conftests
也许你发现的那一页上不应该提到它。
编辑:更新文档url
添加额外的插件以使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数量启用并行运行。
希望这能有所帮助,欢迎发表评论。