[英]How to use the output of a fixture as input to a function as parametrize pytest
我的目標是從test_add將一個值傳遞給夾具,並且夾具返回一個元組列表,需要將其作為參數傳遞給test_add function。
下面是我正在嘗試的代碼,但它不起作用
文件: conftest.py
@pytest.fixture
def testme(request):
in_value = request.param
return [(1*in_value,1),(3*in_value,2),(4*in_value,5)]
文件: test_demo.py
@pytest.mark.parametrize("testme",[(10)])
@pytest.mark.parametrize("input_a,input_b",testme)
def test_add(input_a,input_b):
print(input_a+input_b)
提前感謝所有幫助。
問題是您不能直接在pytest.mark.parametrize
中訪問夾具,所以這不起作用。 最接近 go 的方式可能是在同一個測試中運行所有參數化測試:
@pytest.mark.parametrize("testme", [10], indirect=True)
def test_add(testme):
for (input_a, input_b) in testme:
print(input_a, input_b)
如果您想真正對測試進行參數化,則必須在運行時使用pytest_generate_tests
進行參數化。 在這種情況下,您不能使用夾具來提供所需的參數。 一種可能性是使用包含此值的自定義標記和 function 在運行時根據此值生成參數:
def pytest_generate_tests(metafunc):
# read the marker value, if the marker is set
mark = metafunc.definition.get_closest_marker("in_value")
if mark is not None and mark.args:
in_value = mark.args[0]
# make sure the needed arguments are there
if metafunc.fixturenames[:2] == ["input_a", "input_b"]:
metafunc.parametrize("input_a,input_b", get_value(in_value))
def get_value(in_value):
return [(1 * in_value, 1), (3 * in_value, 2), (4 * in_value, 5)]
@pytest.mark.in_value(10)
def test_add(input_a, input_b):
print(input_a, input_b)
在這種情況下,您還希望在conftest.py
中注冊自定義標記以避免警告:
def pytest_configure(config):
config.addinivalue_line("markers",
"in_value: provides the value for....")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.