pytest.ini 值设置不正确
pytest.ini value not being set correctly
正在尝试动态设置 pytest.ini 文件中的选项。选项 testpaths 确定 pytest 将从哪些目录收集测试。我想让用户能够 select 测试目录 a
或 b
。
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":
config.addinivalue_line("testpaths", "tests/a")
elif suite == "b":
config.addinivalue_line("testpaths", "tests/b")
所以如果我 运行 pytest --suite a
它应该加载测试套件下的所有测试。它不是。它加载所有测试,如选项不存在。
值设置正确。您的问题是,在调用 pytest_configure
挂钩时,ini 文件值和命令行参数已经被解析,因此添加到 ini 值不会带来任何东西 - 它们将不再被读取。特别是,来自 ini 文件的 testpaths
值已经被处理并存储在 config.args
中。所以我们可以改写config.args
:
@pytest.hookimpl()
def pytest_configure(config):
suite = config.getoption('--suite')
if suite == 'a':
config.args = ['tests/a']
elif suite == 'b':
config.args = ['tests/b']
编辑
在测试中访问配置的示例(通过 pytestconfig
fixture):
def test_spam(pytestconfig):
print(pytestconfig.getini('testpaths'))
print(pytestconfig.args)
suite_testpaths = set(pytestconfig.args) - set(pytestconfig.getini('testpaths'))
print('testpaths that were added via suite arg', suite_testpaths)
正在尝试动态设置 pytest.ini 文件中的选项。选项 testpaths 确定 pytest 将从哪些目录收集测试。我想让用户能够 select 测试目录 a
或 b
。
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":
config.addinivalue_line("testpaths", "tests/a")
elif suite == "b":
config.addinivalue_line("testpaths", "tests/b")
所以如果我 运行 pytest --suite a
它应该加载测试套件下的所有测试。它不是。它加载所有测试,如选项不存在。
值设置正确。您的问题是,在调用 pytest_configure
挂钩时,ini 文件值和命令行参数已经被解析,因此添加到 ini 值不会带来任何东西 - 它们将不再被读取。特别是,来自 ini 文件的 testpaths
值已经被处理并存储在 config.args
中。所以我们可以改写config.args
:
@pytest.hookimpl()
def pytest_configure(config):
suite = config.getoption('--suite')
if suite == 'a':
config.args = ['tests/a']
elif suite == 'b':
config.args = ['tests/b']
编辑
在测试中访问配置的示例(通过 pytestconfig
fixture):
def test_spam(pytestconfig):
print(pytestconfig.getini('testpaths'))
print(pytestconfig.args)
suite_testpaths = set(pytestconfig.args) - set(pytestconfig.getini('testpaths'))
print('testpaths that were added via suite arg', suite_testpaths)