You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pytest Fixture中使用字典作为参数?

如何在Pytest Fixture中使用字典作为参数?

你遇到的AttributeError: 'SubRequest' object has no attribute 'param'错误,其实是因为间接参数化的配置没做对,几个小调整就能解决问题,咱们一步步来梳理:

首先看你遇到的错误详情:

E       AttributeError: 'SubRequest' object has no attribute 'param'

你的fixture和测试用例逻辑是对的,但参数化的名称没对应上,导致fixture拿不到传递的字典参数。

问题根源&修复步骤

  • 参数名称必须和fixture名一致
    当你用indirect=True时,@pytest.mark.parametrize的第一个参数得是你要传参的fixture名称(也就是user_create),而不是自定义的dict_param。indirect=True的作用就是把参数传递给同名的fixture,这样fixture里的request.param才能正常拿到值。

  • 测试用例不需要额外接收dict_param
    因为参数已经通过间接方式传给了fixture,测试用例里只需要接收fixture实例就行,多余的参数反而会出错。

修正后的完整代码

修正后的fixture代码

@pytest.fixture(scope="session")
def user_create(authentification_page, request):
    page = authentification_page
    page.get_by_role("link", name="Sign up").click()
    # 现在可以正常通过request.param获取字典里的各个字段
    page.get_by_test_id("given_name").fill(request.param['given_name'])
    page.get_by_test_id("phone_number").fill(request.param['phone_number'])
    page.get_by_test_id("family_name").fill(request.param['family_name'])
    page.get_by_test_id("email").fill(request.param['email'])
    page.get_by_test_id("password").fill(request.param['password'])
    page.get_by_test_id("submit").click()

    yield page

修正后的测试用例

@pytest.mark.parametrize(
    "user_create",  # 这里要和fixture名称完全一致
    [
        {
            "given_name": "test",
            "phone_number": "+330697885878",
            "family_name": "test",
            "email": "test1@gmail.com",
            "password": "Motdepasse2023*"
        }
    ],
    indirect=True  # 开启间接参数化,让字典参数传递给fixture
)
def test_user_create(user_create):
    page = user_create
    # 这里可以添加注册后的断言,比如检查页面跳转、提示信息等

额外小提示

如果后续需要用多个不同的字典参数跑测试,只需要在@pytest.mark.parametrize的列表里添加更多字典元素就行,pytest会自动循环执行每个参数对应的测试。另外要注意scope="session"的使用:如果这个fixture是会话级,整个测试过程只会执行一次注册;如果每个测试用例需要独立的用户,建议把scope改成function或者class。

备注:内容来源于stack exchange,提问作者Nawel Mele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:43:12