Find out django url parse process from Debug And Testing

103 阅读1分钟

It raise a error when I write TestCase for detail page for django:

 File "C:\Users\laoju\.virtualenvs\ulibrary-django-server-Dgm6L-sx\Lib\site-packages\rest_framework\generics.py", line 88, in get_object
    assert lookup_url_kwarg in self.kwargs, (
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.

This is my test case

class UserTestCase(TestCase, TransactionTestCase):
    databases = {'default'}

    def setUp(self):
        from django.core.management import call_command
        call_command('migrate', verbosity=0, interactive=False, database='default')
        User.objects.create(username="user1")

    def test_detail_without_authenticated(self):
        factory = APIRequestFactory()
        request = factory.get('/user/1')
        view = UserDetail.as_view()
        response = view(request)
        count = User.objects.count()
        self.assertEqual(count, 1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

And this is my url define

urlpatterns = [
    path('user/', views.UserList.as_view()),
    path('user/<int:pk>', views.UserDetail.as_view()),

Debug Normal Reqest

When I use debug, this line raise error:

image.png

I am confuse because when I use browser to request, it is ok. So I follow the thread function call stack, I found **kwargs is {} when I run test and access /user/1 but it will be {pk: 1} when normal startserver. But django drf's docs doesn't say it need some specail conf for urlpatterns.

But I think here must have some problem.

image.png

We can find normal request will resolve system url.

image.png

After resolve url, it will magically let view have {pk:1}

image.png

Debug Testing

image.png

It doesn't have url resolve step and directly into last step.

How to resolve this problem?

use rest_framework's APIClient

image.png Afer this modify, the problem is resolved.

image.png

image.png

Now function call stack is very familiar and test case is success!

What we learn

  • where is url parse step
  • how drf parse urlpatterns into kwargs

Thanks for reading.