参数化 pytest - 也将参数传递给设置和拆卸

时间:2021-06-23 12:08:53

标签: python pytest

如何将与传递给测试函数的参数相同的参数传递给设置和拆卸函数?

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")

在我的实际用例中,我会根据传递给测试函数的参数初始化和清理数据库。

我已经阅读过示例,但这些示例似乎都没有涵盖所有设置、测试和拆卸都被参数化的情况。

1 个答案:

答案 0 :(得分:2)

使用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