首页 > 解决方案 > 使用 django 模型作为 pytest 参数化的参数

问题描述

我正在尝试测试是否允许不同业务组的用户使用 pytest 的参数化功能在 web 应用程序中执行操作,但我无法访问参数化中的固定装置值。

第一种方法:

@pytest.fixture
def mike_user():
    user = User(username="mike", email="mike@test.com",)
    user.set_password("test")
    user.save()
    return user


@pytest.fixture
def mike_business_group(mike_user):
    bg = BusinessGroup.objects.create(
        name="Mike Business Group", user=mike_user
    )
    bg.save()
    return bg.pk


@pytest.mark.django_db
@pytest.mark.parametrize(
    "resource, user, serialized_data, success",
    [
        (
            "/business/",
            mike_user,
            {
                "name": "New business",
                "description": "Hi Stackoverflow",
                "group": mike_business_group,
            },
            True,
        ),
    ],
)
def test_create_model_with_related_owner(
    apiclient, user, resource, serialized_data, success
):
    apiclient.force_authenticate(user=user)
    response = apiclient.post(resource, data=serialized_data)
    assert (
        response.status_code == 201
    ) is success

看到lazy_fixture 包,我尝试了以下方法,但它只成功解决mike_user了第二个分辨率的以下字典值:

{'name': 'Marina L4bs', 'description': 'Happy BioHacking', 'group': <LazyFixture "mike_business_group">}

第二种方法:

@pytest.mark.django_db
@pytest.mark.parametrize(
    "resource, user, serialized_data, success",
    [
        (
            "/business/",
            pytest.lazy_fixture("mike_user"),
            {
                "name": "Marina L4bs",
                "description": "Happy BioHacking",
                "group": pytest.lazy_fixture('mike_business_group'),
            },
            True,
        ),
    ],
)

标签: pythondjangodjango-modelspytest

解决方案


作为第三种方法,我为参数化的第二个参数创建了一个夹具,而不是尝试延迟加载 business_group 的值,但我认为即使它有效,它也不是正确的方法,应该存在更好的方法.

@pytest.fixture
def business_creation_for_mike_business_group(mike_business_group):
    return {
        "name": "Marina L4bs",
        "description": "Happy BioHacking",
        "group": mike_business_group,
    }

@pytest.mark.django_db
@pytest.mark.parametrize(
    "resource, user, serialized_data, success",
    [
        (
            "/business/",
            pytest.lazy_fixture("mike_user"),
            pytest.lazy_fixture("business_creation_for_mike_business_group"),
            True,
        ),
    ],
)

推荐阅读