Validating Django with URLs with optional GET parameters

I'm trying to write some tests for a Django application that I am working on, but I have not yet decided on the exact URLs that I want to use for each view. Therefore, I use named URLs in tests.

For example, I have a url called dashboard:

c = Client() resp = c.get(reverse('dashboard')) 

This presentation should be available only to registered users. If the current user is anonymous, they should redirect them to the login page, which is also a named URL. However, when he does this, he uses the optional GET parameter to track the URL just received, resulting in the following:

 /login?next=dashboard 

When I try to verify this redirect, it fails due to these additional parameters:

 # It expecting '/login' but gets '/login?next=dashboard' self.assertRedirects(resp, reverse('login')) 

Obviously, it works if I hardcode them in the test:

 self.assertRedirects(resp, '/login?next=dashboard') 

But then, if I ever decide to change the URL of my view in the dashboard, I will have to update all those tests that use it.

Is there something I can do to make it easier to handle these extra parameters?

Any advice is appreciated.

Thanks.

+9
source share
1 answer

As you can see, reverse(...) returns a string. You can use it like:

 self.assertRedirects(resp, '%s?next=dashboard' % reverse('login')) 
+5
source

Source: https://habr.com/ru/post/1398005/


All Articles