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

问题描述 投票:0回答:1

我使用 pytest 固定装置,它返回对象 {"article_new_1":article_new_1, "article_new_2":article_new_2}:

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

我尝试使用夹具对测试进行参数化。我想将两篇夹具文章粘贴到 @pytest.mark.parametrize

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

问题:我应该粘贴什么来代替 create_articles_new.article_new_1create_articles_new.article_new_2

python testing pytest parametrized-testing pytest-fixtures
1个回答
0
投票

要让夹具创建参数化,需要通过声明

indirect=True
来调用它。但是,您不会将
expected
作为单独的测试函数参数。相反,
article
将是由
tuple
对象组成的
Article
(我假设
ArticleFactory
创建
Article
)和预期结果:

import pytest
from _pytest.fixtures import SubRequest


@pytest.fixture()
def article(request: SubRequest) -> tuple[Article, int]:
    return (
        ArticleFactory.create(
            category=request.param[0], status=ArticleStatusChoices.NEW
        ),
        request.param[1],
    )


@pytest.mark.parametrize(
    "article",
    [
        ("category_1", 200),
        ("category_2", 403),
    ],
    indirect=True,
)
def test_articles(client, article: tuple[Article, int]) -> None:
    res = client.get(
        reverse("get_article", kwargs={"article_guid": article[0].guid})
    )
    assert res.status_code == article[1]

注释

  • 夹具可以通过
    request
    夹具及其
    param
    属性访问传递的参数化参数。
  • article
    夹具不需要返回元组。你可以让它返回一个字典、数据类或任何你认为更合适的东西。
  • 导入
  • SubRequest
    只是为了提示您的装置将使用什么对象。可以省略。
© www.soinside.com 2019 - 2024. All rights reserved.