参数化 pytest - 也将参数传递给设置和拆卸
Parameterized pytest - pass parameters to setup and teardown also
如何将与传递给测试函数的参数相同的参数传递给设置和拆卸函数?
import pytest
test_data = [("3+5", 8), ("2+4", 6), ("6*9", 42)]
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
assert eval(test_input) == expected
def setup():
print("setup")
def teardown():
print("teardown")
在我的实际用例中,我会根据传递给测试函数的参数初始化和清理数据库。
我已阅读示例,但其中 none 似乎涵盖了所有设置、测试和拆卸均已参数化的情况。
使用fixture
进行设置和拆卸,你可以将参数发送给它
test_data = [("3+5", 8), ("2+4", 6), ("6*9", 42)]
@pytest.fixture(scope='function', autouse=True)
def setup_and_teardown(test_input, expected):
print("setup")
print('Parameters:', test_input, expected)
yield
print("teardown")
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
assert eval(test_input) == expected
print("*************************************")
输出:
setup
test_input: 3+5 expected: 8
PASSED [ 33%]*************************************
teardown
setup
test_input: 2+4 expected: 6
PASSED [ 66%]*************************************
teardown
setup
test_input: 6*9 expected: 42
FAILED [100%]
Tests\Example_test.py:34 (test_eval[6*9-42])
54 != 42
Expected :42
Actual :54
<Click to see difference>
test_input = '6*9', expected = 42
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E assert 54 == 42
如何将与传递给测试函数的参数相同的参数传递给设置和拆卸函数?
import pytest
test_data = [("3+5", 8), ("2+4", 6), ("6*9", 42)]
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
assert eval(test_input) == expected
def setup():
print("setup")
def teardown():
print("teardown")
在我的实际用例中,我会根据传递给测试函数的参数初始化和清理数据库。
我已阅读示例,但其中 none 似乎涵盖了所有设置、测试和拆卸均已参数化的情况。
使用fixture
进行设置和拆卸,你可以将参数发送给它
test_data = [("3+5", 8), ("2+4", 6), ("6*9", 42)]
@pytest.fixture(scope='function', autouse=True)
def setup_and_teardown(test_input, expected):
print("setup")
print('Parameters:', test_input, expected)
yield
print("teardown")
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
assert eval(test_input) == expected
print("*************************************")
输出:
setup
test_input: 3+5 expected: 8
PASSED [ 33%]*************************************
teardown
setup
test_input: 2+4 expected: 6
PASSED [ 66%]*************************************
teardown
setup
test_input: 6*9 expected: 42
FAILED [100%]
Tests\Example_test.py:34 (test_eval[6*9-42])
54 != 42
Expected :42
Actual :54
<Click to see difference>
test_input = '6*9', expected = 42
@pytest.mark.parametrize("test_input,expected", test_data)
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E assert 54 == 42