Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test django urls?

I have achieved 100% test coverage in my application everywhere except my urls.py. Do you have any recommendations for how I could write meaningful unit tests for my URLs?

FWIW This question has arisen as I am experimenting with Test-Driven Development and want failing tests before I write code to fix them.

like image 901
meshy Avatar asked Sep 24 '13 16:09

meshy


People also ask

How do I test my Django site?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

How can we handle URLs in Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

How do you write unit test cases in Django?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...

What is SimpleTestCase?

If your tests make any database queries, use subclasses TransactionTestCase or TestCase . SimpleTestCase. databases. SimpleTestCase disallows database queries by default. This helps to avoid executing write queries which will affect other tests since each SimpleTestCase test isn't run in a transaction.


1 Answers

One way would be to reverse URL names and validate

Example

urlpatterns = [     url(r'^archive/(\d{4})/$', archive, name="archive"),     url(r'^archive-summary/(\d{4})/$', archive, name="archive-summary"), ] 

Now, in the test

from django.urls import reverse  url = reverse('archive', args=[1988]) assertEqual(url, '/archive/1988/')  url = reverse('archive-summary', args=[1988]) assertEqual(url, '/archive-summary/1988/') 

You are probably testing the views anyways.

Now, to test that the URL connect to the right view, you could use resolve

from django.urls import resolve  resolver = resolve('/summary/') assertEqual(resolver.view_name, 'summary') 

Now in the variable resolver (ResolverMatch class instance), you have the following options

 'app_name',  'app_names',  'args',  'func',  'kwargs',  'namespace',  'namespaces',  'url_name',  'view_name' 
like image 89
karthikr Avatar answered Sep 29 '22 03:09

karthikr