我提前为重复参数这个词 1000 次而道歉。我的用例如下。
我正在使用 pytest 来测试解析器,该解析器解析在线商店产品页面中的字段。
我已经参数化了一个 fixture ,以便每个 fixture 导入一个产品的数据。我所说的数据是指 HTML 源代码和具有预期值的字段列表。接下来我有一个参数化测试,它采用元组列表(字段,期望值),以便每个字段都有自己的测试。
基本上,“基本”问题会像这样:
from pytest import fixture, mark
products = [
{
'text': 'bla bla',
'fields': [('bla', 0), ('foo', -1)]
},
{
'text': 'foo bar',
'fields': [('bla', -1), ('foo', 0), ('bar', 4)]
}
]
@fixture(params=products)
def product(request):
return request.param
@mark.parametrize('field_key, field_value', product['fields'])
def test_parser(product, field_key, field_value):
assert product['text'].find(field_key) == field_value
在 @mark.parametrize
装饰器的上下文中,product
不被解释为固定装置,因此 pytest 返回:
TypeError: 'function' object has no attribute '__getitem__'
pytest 有很多自省(introspection)魔法,我在寻找解决方案时遇到了麻烦。我看了看 this question但这不是我想要的。有没有办法做到这一点?谢谢。
最佳答案
我认为您不需要固定装置来实现您的目标。
根据您的示例数据,这是一种可能的方式:
from pytest import mark
products = [
{
'text': 'bla bla',
'fields': [('bla', 0), ('foo', -1)]
},
{
'text': 'foo bar',
'fields': [('bla', -1), ('foo', 0), ('bar', 4)]
}
]
possible_params = []
for product in products: # Iterate over the products to build all desired invocations
for field_key, field_value in product['fields']:
possible_params.append((product['text'], field_key, field_value))
@mark.parametrize('text,field_key,field_value', possible_params)
def test_parser(text, field_key, field_value):
assert text.find(field_key) == field_value
关于python - 如何参数化测试,从参数化 fixture 中获取参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124766/