Handle optional url parameter in Django unit test case

3.9k views Asked by At

I have created a Dynamic Url with optional parameter

e.g., If my url is as www.example.com/getTest/1/ Now this 1 in url is optional , to handle this in views I have used None like

def function(request, id=None):
   pass

Thus if there is no id in URL then still the function works for me. But I am facing issue while testing this in unit cases. if I use url as url = reverse('yescourse:academypage_url', args=[None]) it gives me the error

NoReverseMatch: Reverse for 'academypage_url' with arguments '('new', None)' and keyword arguments '{}' not found.

So Please Tell me how I can handle these optional url in Test cases or in Reverse.

Edit :

 url(r'^getTest/(?P<action>\w+)/(?P<id>\d*)$', 'app.views.create_edit_academypage', name='academypage_url'),
1

There are 1 answers

2
bruno desthuilliers On BEST ANSWER

You made the view function's id parameter optional, but it's not optional in the url pattern. You firsty need to rewrite your pattern as :

r'^getTest/(?P<action>\w+)/(?P<id>\d+)?$'

=> the whole 'id' sub-pattern is optional, but if it's not it must match one or more numerics.

Once done, you can reverse the url by not passing any of the args nor kwargs arguments:

url = reverse('yescourse:academypage_url')

or by passing an empty list

url = reverse('yescourse:academypage_url', args=[])

or by passing None

url = reverse('yescourse:academypage_url', args=None)

but not by passing a list containing None.