python - 如何参数化测试,从参数化 fixture 中获取参数?

标签 python python-2.7 parameters pytest fixtures

我提前为重复参数这个词 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/

相关文章:

python-2.7 - 从 Flask 服务器访问客户端网络摄像头

python - SymPy 1.0 中的集成错误

jquery - 使用 .load() 检索参数

java - 方法接受唯一对象的任意组合作为参数的巧妙方法?

python - 在 pyhook Pumpmessages 中使用自己的代码

python - 如何将反斜杠转义序列放入 f-string

python - 在循环中恢复循环的Pythonic方法是什么

c# - 为什么这个带有参数化 sql 的 C# 数据库应用程序不能工作?

python - 显示奇数误差线的条形图

python - Google 应用程序引擎模块 :Confused about routing (dispatch. yaml)