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.
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.
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).
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 ...
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With