使用固定装置和命令行参数对pytest测试进行参数化

时间:2018-06-27 20:44:40

标签: python pytest parameterized-unit-test

尝试将命令行参数(table_name)放入pytest中(通过conftest.py,请参见下文),并在助手方法中使用该参数在数据库中进行查询,然后使用查询结果创建参数化的测试输入在test_函数上使用@ pytest.mark.parametrize。

#contents of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--table_name", action="store", default=None, help="enter table name")

@pytest.fixture
def table_name(request):
    return request.config.getoption('--table_name')

问题是:使用固定装置检索命令行参数(table_name),我们希望将其传递给helper方法以进行查询并将查询结果放入列表中,但是由于helper方法接受一个灯具,不能在另一个灯具/测试功能之外调用它。因此我们无法将列表放入参数化的test_function参数中

#helper method
def get_test_cases(table_name):
    #connect to DB, makes query
    #puts all query results into a list called tests
    return tests

#test function
@pytest.mark.parametrize("columns...", (values...)) #list is read as values
def test_function(columns):
    #assertion tests

有什么方法可以使用命令行参数,也可以将数据库查询的结果传递到参数化的标记/参数中?

1 个答案:

答案 0 :(得分:2)

关于帮助程序如何从数据库读取测试值或如何调用该帮助程序以生成pytest.mark.parameterize()的值的描述尚不十分清楚,但是该帮助程序是否能够每个获取一个测试用例调用(而不是一次显示整个列表),则可以使助手本身成为一个固定装置,并对其进行多次调用,对于@ pytest.mark.parametrize()装饰中列出的每个测试用例一次。假设数据库在数据库行中包含每个测试用例,并通过“测试ID”列为它建立索引。

@pytest.fixture
def test_case(request,table_name):
# this is the get-test-case helper, note it is a fixture,
# so it can have table_name as an argument
# request.param will be our test ID here, see the mark.parametrize below
    return query("select * from %s where test_id = %s",
                 (table_name, request.param))

@pytest.mark.parametrize("test_case,p1,p2",
    [ ("TstID1", 1, 2), ("TstID2", 3, 3) ], indirect=["test_case"])
def test_function(test_case, p1, p2):
    # test_case here will be the query result from the call to the test_case() fixture! p1 and p2 will come directly from the parameterize mark.

请注意常规参数p1和p2是如何按原样传递的,但是标记为间接参数的参数是通过固定装置传递的(这还确保了在实际运行测试时执行查询数据库的“昂贵”操作, pytest运行“收集阶段”并准备要运行的测试列表时不会。