将命令行参数作为参数传递给py.test fixture

时间:2016-08-05 18:10:55

标签: python pytest

不可否认,这不是开始时最好的方法,更重要的是解决了夹具参数,即在其他一切之前调用Options.get_option()。 建议和建议将不胜感激。

来自config.py

class Options(object):
    option = None

    @classmethod
    def get_option(cls):
        return cls.option

来自conftest.py

@pytest.yield_fixture(scope='session', autouse=True)
def session_setup():
    Options.option = pytest.config.getoption('--remote')

def pytest_addoption(parser):
    parser.addoption("--remote", action="store_true", default=False, help="Runs tests on a remote service.")




@pytest.yield_fixture(scope='function', params=Options.get_option())
def setup(request):
    if request.param is None:
        raise Exception("option is none")

2 个答案:

答案 0 :(得分:7)

不要使用自定义Options类,而是直接向config请求选项。

pytest_generate_tests可用于参数化类似夹具的测试参数。

conftest.py

def pytest_addoption(parser):
    parser.addoption("--pg_tag", action="append", default=[],
                     help=("Postgres server versions. "
                           "May be used several times. "
                           "Available values: 9.3, 9.4, 9.5, all"))

def pytest_generate_tests(metafunc):
    if 'pg_tag' in metafunc.fixturenames:
        tags = set(metafunc.config.option.pg_tag)
        if not tags:
            tags = ['9.5']
        elif 'all' in tags:
            tags = ['9.3', '9.4', '9.5']
        else:
            tags = list(tags)
        metafunc.parametrize("pg_tag", tags, scope='session')

@pytest.yield_fixture(scope='session')
def pg_server(pg_tag):
    # pg_tag is parametrized parameter
    # the fixture is called 1-3 times depending on --pg_tag cmdline

修改:用metafunc.parametrize用法替换旧示例。

答案 1 :(得分:2)

最新文档中有一个关于如何执行此操作的示例。它有点被埋葬了,说实话,我第一次阅读文档时会给它上釉:https://docs.pytest.org/en/latest/parametrize.html#basic-pytest-generate-tests-example

  

基本pytest_generate_tests示例

     

有时您可能想要实现自己的参数化方案或   实现一些动力来确定a的参数或范围   夹具。为此,您可以使用pytest_generate_tests钩子   收集测试功能时调用。通过传入的metafunc   对象,您可以检查请求的测试上下文,大多数   重要的是,你可以调用metafunc.parametrize()来导致   参数化。

     

例如,假设我们想要运行一个测试字符串输入   我们想通过一个新的pytest命令行选项设置它。我们先来吧   编写一个接受stringinput fixture函数参数的简单测试:

# content of test_strings.py

def test_valid_string(stringinput):
    assert stringinput.isalpha()
     

现在我们添加一个包含添加命令的conftest.py文件   line选项和我们测试函数的参数化:

# content of conftest.py

def pytest_addoption(parser):
    parser.addoption("--stringinput", action="append", default=[],
        help="list of stringinputs to pass to test functions")

def pytest_generate_tests(metafunc):
    if 'stringinput' in metafunc.fixturenames:
        metafunc.parametrize("stringinput",
                             metafunc.config.getoption('stringinput'))
     

如果我们现在传递两个stringinput值,我们的测试将运行两次:

$ pytest -q --stringinput="hello" --stringinput="world" test_strings.py`
..
2 passed in 0.12 seconds
相关问题