Django UrlResolver, adding urls at runtime for testing

jbcurtin picture jbcurtin · Feb 3, 2011 · Viewed 8.6k times · Source

I'm looking to do some tests and I'm not really familiar with the URLResolver quite yet but I'd like to solve this issue quickly.

In a TestCase, I'd like to add a URL to the resolver so that I can then use Client.get('/url/') and keep it separate from urls.py.

Answer

renskiy picture renskiy · Aug 5, 2015

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 TestCase
from django.test.utils import override_settings

urlpatterns = [
    # 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.