Python 使用Pytest的参数化添加测试的说明
可以在参数化中添加测试内容的描述,当其中一个失败时,快速了解测试失败的原因 有时,您不知道测试失败的原因(您必须查看代码)。通过对每个测试的描述,您可以知道 比如说Python 使用Pytest的参数化添加测试的说明,python,pytest,Python,Pytest,可以在参数化中添加测试内容的描述,当其中一个失败时,快速了解测试失败的原因 有时,您不知道测试失败的原因(您必须查看代码)。通过对每个测试的描述,您可以知道 比如说 @pytest.mark.parametrize( "num1, num2, expect", [ (2, 2, 4), # This test verifies that 2+2 = 4. ]) def test_sum(num1, num2, expect): calc = Calc() respons
@pytest.mark.parametrize( "num1, num2, expect", [
(2, 2, 4), # This test verifies that 2+2 = 4.
])
def test_sum(num1, num2, expect):
calc = Calc()
response = calc.sum(num1, num2)
assert expect == response
如果测试失败,错误消息将显示:
src_test/calc.py::test_sum[19999997-200] FAILED
assert vo_result.code == expected_code
E AssertionError: assert 4 == 3
**The test checks if the numbers add up well.** Message invented
您可以在参数化中定义每个测试的id。ID被附加到测试名称之后。默认情况下,参数化id是参数的组合
@pytest.mark.parametrize( "num1, num2, expect", [
(2, 2, 4)], ids = ["2+2=4"])
def test_sum(num1, num2, expect):
calc = Calc()
response = calc.sum(num1, num2)
assert expect == response
当测试运行时,测试名称将是test\u sum[2+2=4]
。
当测试失败时,您可以查看测试名称并找到导致测试失败的参数集
要使单个测试失败,可以使用pytest.params。e、 g:
@pytest.mark.parametrize( "num1, num2, expect", [
(2, 2, 4), pytest.param(2,3,9, marks=pytest.mark.xfail], ids = ["2+2=4", "failing"])
def test_sum(num1, num2, expect):
calc = Calc()
response = calc.sum(num1, num2)
assert expect == response
关于pytest参考文档中参数化id的更多信息:也许最好只提供更多关于断言的信息,例如
assert vo_result.code==expected_code,f“此测试验证{num1}+{num2}={expected}”。
或在函数开头记录此消息谢谢您回答@MikhailBerlinkov,我考虑过这个选项,传入一个名为test\u name
的属性,并将其添加到assert中。我只是想知道Pytest是否还有其他方法。谢谢,我不知道这个选项。我不知道这是否是为了我的目的,但我觉得很有趣。有时我想指出的是,如果参数是这样的,那么它失败了,或者SUT的操作正确完成了。您可以在param config中对单个测试使用pytest.mark.xfail
。请参阅参数化文档()。更新了用例的答案。