是否可以对pytest参数值进行子参数化



我正在做一个DRF(REST API(项目,我正在使用pytest。我经常发现自己在写几乎相同的测试参数,我一直在想我是否遗漏了什么。我还没有阅读完整的pytest文档,尽管我确实阅读了关于测试的整个django文档章节(对我的情况没有太大帮助(,现在我已经花了几个小时试图找到解决方案。假设我有这样的观点:

from rest_framework import generics
from myapp.permissions import IsStaff, IsAdmin
class MessagesListView(generics.ListAPIView):
permission_classes = [IsStaff | IsAdmin] 
# ...

(注意:仅举个例子,请假设具有IsAdmin权限的用户不一定具有IsStaff权限;这不是问题的重点。(

为了这个观点,我写了一个测试:

import pytest
from rest_framework.reverse import reverse_lazy
from pytest_lazy_fixture import lazy_fixture
class TestMessagesListViewPermissions:
def get_response(self, client):
url = reverse_lazy("api:messages-list")
return client.get(url)

@pytest.mark.parametrize(
argnames=["client", "expected_response_status"],
argvalues=[
pytest.param(
"anonymous_client",
status.HTTP_403_FORBIDDEN,
),
pytest.param(
"authenticated_client",
status.HTTP_403_FORBIDDEN,
),
pytest.param(
"staff_client",
status.HTTP_200_OK,
),
pytest.param(
"admin_client",
status.HTTP_200_OK,
),
],
)
def test__permissions(self, client, expected_response_status):
# WHEN
response = self.get_response(client)
# THEN
assert response.status_code == expected_response_status

有4个不同的client值,但1+2nd和3+4th导致相同的响应状态代码。正如我所说,这是一个简化的例子,但如果有10个参数呢?我想做的是这样的事情:

@pytest.mark.parametrize(
argnames=["client", "expected_response_status"],
argvalues=[
pytest.param(
ParamList["anonymous_client", "authenticated_client"],
status.HTTP_403_FORBIDDEN,
),
pytest.param(
ParamList["staff_client", "admin_client"],
status.HTTP_200_OK,
),
],
)

有没有我缺少的pytest功能,或者是一个插件使这成为可能?

您考虑过pytest子测试吗?

以下是关于其优点和缺点的长时间讨论:https://blog.ganssle.io/articles/2020/04/subtests-in-python.html

最新更新