Django UrlResolver, adding urls at runtime for testing Django UrlResolver, adding urls at runtime for testing django django

Django UrlResolver, adding urls at runtime for testing


Since Django 1.8 using of django.test.TestCase.urls is deprecated. You can use django.test.utils.override_settings instead:

from django.test import TestCasefrom django.test.utils import override_settingsurlpatterns = [    # custom urlconf]@override_settings(ROOT_URLCONF=__name__)class MyTestCase(TestCase):    pass

override_settings can be applied either to a whole class or to a particular method.


https://docs.djangoproject.com/en/2.1/topics/testing/tools/#urlconf-configuration

In your test:

class TestMyViews(TestCase):     urls = 'myapp.test_urls'

This will use myapp/test_urls.py as the ROOT_URLCONF.


I know this was asked a while ago, but I thought I'd answer it again to offer something more complete and up-to-date.

You have two options to solve this, one is to provide your own urls file, as suggested by SystemParadox's answer:

class MyTestCase(TestCase):    urls = 'my_app.test_urls'

The other is to monkey patch your urls. This is NOT the recommended way to deal with overriding urls but you might get into a situation where you still need it. To do this for a single test case without affecting the rest you should do it in your setUp() method and then cleanup in your tearDown() method.

import my_app.urlsfrom django.conf.urls import patternsclass MyTestCase(TestCase):    urls = 'my_app.urls'    def setUp(self):        super(MyTestCase, self).setUp()        self.original_urls = my_app.urls.urlpatterns        my_app.urls.urlpatterns += patterns(            '',            (r'^my/test/url/pattern$', my_view),        )    def tearDown(self):        super(MyTestCase, self).tearDown()        my_app.urls.urlpatterns = self.original_urls

Please note that this will not work if you omit the urls class attribute. This is because the urls will otherwise be cached and your monkey patching will not take effect if you run your test together with other test cases.