pytest.ini值未正确设置

时间:2018-01-12 22:44:22

标签: python config pytest ini

尝试动态设置pytest.ini文件中的选项。选项testpaths确定pytest将从哪些目录收集测试。我想让用户能够选择测试目录ab

conftest.py

第一个钩子创建一个解析器选项。 第二个钩子拉动解析器选项读取值并将测试路径添加到配置对象下的testpaths选项。

@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,它应该在测试套件下加载所有测试。它不是。它加载所有测试,如选项不存在。

1 个答案:

答案 0 :(得分:1)

正确设置了值。你的问题是,在调用pytest_configure个钩子时,ini文件值和命令行args已经被解析了,所以添加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)
相关问题