dimanche 24 juillet 2016

Django Rest Framework test fails: Expected view to be called with a URL keyword argument

I am running tests on UserDetail view written using Django Rest framework.

urls.py

    url(r'^(?P<pk>[0-9]+)$', views.UserDetail.as_view(), name='user-detail'),

test_api.py

BaseAPITestCase(APITestCase):
    def setUp(self):
        self.superuser = User.objects.create_superuser('admin', 'admin@test.com', 'johnpassword')
        self.client.login(username='john', password='johnpassword')
        self.user = User.objects.create(username="user1", password="pass", email="user1@test.com")


class ReadUserTest(BaseAPITestCase):
# check read permissions
    def test_user_can_read_self_detail(self):
        url = '/api/users/'+str(self.user.id)
        factory = APIRequestFactory()
        request = factory.get(url)
        force_authenticate(request, self.user)
        response = (UserDetail.as_view())(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

However, running this test, gives me following error. The 'pk' agrument is not getting passed to the UserDetail view.

AssertionError: Expected view UserDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

How do I test views with URL arguments?

Aucun commentaire:

Enregistrer un commentaire