gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:28:26 26 4
gpt4 key购买 nike

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

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")
在我的实际用例中,我会根据传递给测试函数的参数初始化和清理数据库。
我已经阅读过示例,但这些示例似乎都没有涵盖所有设置、测试和拆卸都被参数化的情况。

最佳答案

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

关于python - 参数化 pytest - 也将参数传递给设置和拆卸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68099559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com