报错AttributeError: 'SubRequest'对象无'param'属性,求原因(pytest7.3.1)
错误原因与解决方法
错误根源
你当前的@pytest.mark.parametrize是针对x和y这两个参数做的参数化,并且设置了indirect=True——这表示pytest会把x、y当作fixture来解析。但entity这个fixture并没有被任何参数化装饰器绑定,它的request对象自然不存在param属性,所以调用request.param会触发AttributeError。
两种解决思路
思路1:让entity接收参数化的值
如果你的需求是给entity传递参数化数据,需要把参数化的目标改为entity,调整代码如下:
测试代码:
@pytest.mark.parametrize('entity', [('x', 'y')], indirect=True) def test_smthng(self, entity): # 若仍需单独使用x、y,可从entity返回值中拆分 pass
对应的fixture代码:
@pytest.fixture def entity(request): x, y = request.param # 此处编写entity的初始化逻辑 return (x, y) # 或返回处理后的entity对象
思路2:entity依赖已参数化的x、y
如果x、y本身是需要参数化的fixture,且entity需要用到它们的值,直接在entity fixture中依赖x和y即可,无需使用request.param:
fixture代码:
@pytest.fixture def x(request): return request.param @pytest.fixture def y(request): return request.param @pytest.fixture def entity(x, y): # 直接使用x、y的参数化值来初始化entity return f"entity with x={x}, y={y}"
测试代码:
@pytest.mark.parametrize('x,y', [('x', 'y')], indirect=True) def test_smthng(self, entity, x, y): assert entity == "entity with x=x, y=y"
内容的提问来源于stack exchange,提问作者Egor Baranov
相关产品推荐
相关产品推荐

