简体   繁体   English

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

[英]Parameterized pytest - pass parameters to setup and teardown also

How can I pass same parameters to setup and teardown functions as which I pass to test function?如何将与传递给测试函数的参数相同的参数传递给设置和拆卸函数?

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

In my real usecase I would initialize and clean database according to parameters passed to test function.在我的实际用例中,我会根据传递给测试函数的参数初始化和清理数据库。

I have read examples, but none of those seem to cover case where all setup, test and teardown are parameterized.我已经阅读过示例,但这些示例似乎都没有涵盖所有设置、测试和拆卸都被参数化的情况。

Use fixture for the setup and teardown, you can send the paramters to it使用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("*************************************")

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM