pytest.ini中testpaths动态设置失效问题求助
解决pytest动态设置testpaths不生效的问题
我看到你尝试通过conftest.py的钩子动态调整testpaths,但使用--suite a时依然会运行所有测试,这个问题的核心是**addinivalue_line的作用时机不对**——它仅用于向配置文件追加内容,而此时pytest已经完成了初始配置解析,不会再重新读取testpaths来调整测试收集范围。
问题原因
pytest_configure钩子执行时,pytest已经完成了配置初始化(包括读取pytest.ini里的testpaths)。调用config.addinivalue_line("testpaths", "...")只是把内容添加到配置的“待写入”缓存里,并不会触发重新解析测试路径的逻辑,所以实际测试收集还是沿用了初始的testpaths(如果没设置就是当前目录,自然会跑所有测试)。
修正后的代码
我们需要直接修改pytest用来决定测试路径的config.option.testpaths属性,这样就能实时调整测试收集的范围:
# conftest.py @pytest.hookimpl() def pytest_addoption(parser): """Creates a parser option""" # Allows the user to select the test suite they want to run parser.addoption("--suite", action="store", default="None", choices=['a', 'b'], help="Choose which test suite to run.") @pytest.hookimpl() def pytest_configure(config): print("Determining test directory") suite = config.getoption("--suite") if suite == "a": # 直接覆盖testpaths选项,指定测试目录 config.option.testpaths = ["tests/a"] elif suite == "b": config.option.testpaths = ["tests/b"]
额外优化(可选)
如果你的pytest.ini原本就设置了默认testpaths(比如testpaths = tests),希望未指定--suite时保持原有行为,可以调整逻辑:
@pytest.hookimpl() def pytest_configure(config): print("Determining test directory") suite = config.getoption("--suite") if suite != "None": if suite == "a": config.option.testpaths = ["tests/a"] elif suite == "b": config.option.testpaths = ["tests/b"] # 未指定suite时,保留pytest.ini的原有testpaths设置
现在运行pytest --suite a,就只会收集并运行tests/a下的测试用例了。
内容的提问来源于stack exchange,提问作者Drew Ackerman
相关产品推荐
相关产品推荐

