Url 测试 ModelViewSet 时未解析

Url not parsed when testing a ModelViewSet

我正在尝试测试 Django Rest Framework 视图。当我从真实的 api 客户端调用我的端点时,pk 已正确设置。从测试中调用时,pk 为 None.

class ResourceViewSet(ModelViewSet):
    serializer_class = ResourceSerializer

    @action(detail=True)
    def foo(self, request, pk=None):
        print(pk) # None when called by the test


def test_foo(client: Client, db):
    request = factory.post(f'/api/resource/1/foo/')
    view = ResourceViewSet.as_view({'post': 'foo'})
    response = view(request)

我应该如何修复我的测试?

直接测试视图时,您正在绕过 url resolving/mapping 逻辑。因此,您应该将参数作为 args/kwargs 传递,最后您调用 foo 函数:

def test_foo(client: Client, db):
    request = factory.post(f'/api/resource/1/foo/')
    view = ResourceViewSet.as_view({'post': 'foo'})
    response = view(request, pk=1)

如果您想测试整个堆栈,还有 urls,我建议您使用 APIClient