假设我有以下测试:
@pytest.fixture(params=['a'])
def ascii(request):
return ord(request.param)
def test_ascii(ascii):
assert ascii == 97
这个效果很好。现在假设我想添加
'b'
作为参数。理想情况下,我可以用 @pytest.mark.parametrize('ascii_val', [97, 98])
之类的东西来装饰测试,添加 ascii_val
作为测试的补充,并断言 ascii == ascii_val
。然而,Pytest 也会针对 98 断言 'a'
,针对 97 断言 'b'
。
有什么办法让我将
'a'
与97关联起来,'b'
与98关联起来吗?我这样问是因为我将进行很多测试,例如 test_ascii
,我将在其中检查某些输入在给定不同分析技术的情况下是否始终输出相同的输出。
至少对于您给出的简单示例,为什么使用参数化夹具而不是参数化您的测试?
这样的东西应该有效:
@pytest.mark.parametrize('char, expected', [('a', 97), ('b', 98)])
def test_ascii(char, expected):
assert ord(char) == expected
如果你真的想使用一个固定装置,你总是可以从中返回一个
(char, expected)
元组并使用它。
另一个例子,扩展了另一个答案中关于在参数化中嵌入预期响应的概念。可以填充单个值或只是一个可以在多个断言语句中使用的字典。不可否认,这有点做作,因为被测试的函数仅返回 1 个值,对此相等性测试是相当结论性的......但对于更复杂的函数,我发现这种方法可行:
import pytest
data = [
{
'case': 'letter a',
'ltr': 'a',
'expected': {'val': 97, 'greater': False}
},
{
'case': 'letter b',
'ltr': 'b',
'expected': {'val': 98, 'greater': True}
}
]
@pytest.fixture()
def ascii(request):
return ord(request.param['ltr']), request.param['expected']
@pytest.mark.parametrize('ascii', argvalues=data, indirect=True, ids=[t['case'] for t in data])
def test_ascii(ascii):
ascii_val, expected = ascii
assert ascii_val == expected['val']
greater = ascii_val > 97.5
assert greater == expected['greater']