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

如何在@pytest.mark.parametrize中从fixture获取精确值?

解决方案

你不能直接在@pytest.mark.parametrize里用字符串create_articles_new.article_new_1引用fixture返回的对象,因为这些字符串不会被pytest自动解析为fixture的属性。以下是两种可行的解决方式:

方法一(推荐):通过键名从fixture字典中获取对象

修改参数化内容为字典的键名,在测试函数中注入create_articles_new fixture,再通过键名取出对应的文章对象:

@pytest.mark.parametrize(
    "article_key,expected",
    [
        ("article_new_1", 200),
        ("article_new_2", 403),
    ],
)
def test_articles(client, create_articles_new, article_key, expected):
    article = create_articles_new[article_key]
    res = client.get(reverse("get_article", kwargs={"article_guid": article.guid}))
    assert res.status_code == expected

方法二:拆分fixture为独立的单个对象fixture

如果后续测试更常单独使用这两个文章对象,可以把原fixture拆分为两个独立的fixture:

@pytest.fixture
def article_new_1(create_categories):
    return ArticleFactory.create(category=create_categories["category_1"], status=ArticleStatusChoices.NEW)

@pytest.fixture
def article_new_2(create_categories):
    return ArticleFactory.create(category=create_categories["category_2"], status=ArticleStatusChoices.NEW)

然后在参数化时使用pytest.param结合indirect参数,让pytest解析fixture名称:

@pytest.mark.parametrize(
    "article,expected",
    [
        (pytest.param("article_new_1", 200, indirect=["article"])),
        (pytest.param("article_new_2", 403, indirect=["article"])),
    ],
)
def test_articles(client, article, expected):
    res = client.get(reverse("get_article", kwargs={"article_guid": article.guid}))
    assert res.status_code == expected

这种方式更适合单个对象的fixture场景,原fixture返回字典的情况下,方法一更简洁高效。

内容的提问来源于stack exchange,提问作者serg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:31:04