如何将与传递给测试函数相同的参数传递给setup和teardown函数?
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")在我的实际用例中,我会根据传递给测试函数的参数来初始化和清理数据库。
我读过一些例子,但这些例子似乎都不能涵盖所有的设置、测试和拆卸都是参数化的情况。
发布于 2021-06-23 20:13:39
使用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 == 42https://stackoverflow.com/questions/68099559
复制相似问题