[英]Using funcarg value in pytest_generate_tests function
I am new to py.test and I am using funargs to generate some test data before the tests get executed.我是 py.test 的新手,我正在使用 funargs 在执行测试之前生成一些测试数据。 I want to have pytest_generate hook use the funcargs value and pass it to the test function. For eg I have a function "do_something" which queries a database for a given set of arguments and sets user's enviroment accordingly.
我想让 pytest_generate 挂钩使用 funcargs 值并将其传递给测试 function。例如,我有一个 function“do_something”,它查询数据库中给定的一组 arguments 并相应地设置用户环境。 Considering that we have a multi site setup, I want to ensure that the database has the entries against which the test is performed, before the test gets executed.
考虑到我们有一个多站点设置,我想确保在执行测试之前数据库中有针对其执行测试的条目。
def pytest_funcarg__data(request):
# Ensure test data exist in the data base
# Perform all the checks
# Final values
values = [['option1', 'option2', 'option3'],
['option1', 'option2'],
['option2', 'option3']]
# Expected result
results = [['output1'],
['output2'],
['output3']]
return (values, results)
def test_do_something(value, result):
assert do_something(value) == result
Ideally.理想情况下。 I want to iterate though the values and pass them to my test function. How can I do that?
我想遍历这些值并将它们传递给我的测试 function。我该怎么做?
Currently I am doing this:目前我正在这样做:
def pytest_funcarg__data(request):
#same as above
def pytest_funcarg__pass_data(request):
data = request.getfuncargvalue("data")
return (data[0][request.param],
data[1][request.param])
def pytest_generate_tests(metafunc):
if 'pass_data' in metafunc.funcargnames:
# If number of test cases change the change needs to made here too
metafunc.parametrize("pass_data", [0, 1, 2], indirect=True)
def test_do_something(pass_data):
assert do_something(pass_data[0] == pass_data[1]
Now, this works.现在,这有效。 But everytime I add a test case, I need to update the generate_test hook.
但是每次添加测试用例时,我都需要更新 generate_test 挂钩。 I am thinking there might be a simpler way to do this?
我在想可能有更简单的方法来做到这一点?
the pytest_generate_tests hook is executed when tests are collected.收集测试时执行 pytest_generate_tests 挂钩。 The pytest_funcarg__data factory is called when the test is executed.
执行测试时调用 pytest_funcarg__data 工厂。 Test execution happens after test collection so there is no way you could call something like "getfuncargvalue" during collection.
测试执行发生在测试收集之后,因此您无法在收集期间调用“getfuncargvalue”之类的东西。
However, it's not clear from your example why you want to use both - here is a generate_tests that should work directly with your example test:但是,从您的示例中不清楚为什么要同时使用两者 - 这是一个 generate_tests 应该直接与您的示例测试一起使用:
def pytest_generate_tests(metafunc):
params = [("input", "output")]
metafunc.parametrize(("test_case", "result"), params)
HTH. HTH。 holger
霍尔格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.