I am trying to test a Django Rest Framework view. When I call my endpoint from a real api client, pk is correctly set. When it is called from the test, pk is 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)
How should I fix my test?
When testing the view directly as you are doing, you are bypassing the url resolving/mapping logic. Therefore, you should pass the parameters as args/kwargs, in the end you are calling the foo
function:
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)
If you'd like to test the whole stack, also the urls, I'd recommend you use the APIClient.