Search code examples
djangodjango-urlsdjango-testingdjango-settings

How do I re-evaluate my urls.py file after every test within a Django tests.py file?


I have the following construction in my urls.py - it allows me to visually check the format of emails that I send in the browser when I'm developing:

urlpatterns = [Various url pattenrns]

if settings.DEBUG:
    urlpatterns += [URL Pattern for checking emails]

My issue is that when I run my test suite the code only checks settings.DEBUG one time - not each time a test or even a TestCase runs.

I'm trying to use the @override_settings decorator before my tests that apply to the DEBUG=True urlpattern with something like:

# Most of my tests run fine with Debug=False

@override_settings(DEBUG=True)
# Tests that use the URL pattern for checking emails

However, I can't seem to get this to properly toggle the Url pattern between tests...presumably because my urls.py file only loads once for the entire app's tests.

Is there a way to use this type of construction in my urls.py and run my tests? Is there a reason I shouldn't be using this type of conditional in my urls.py?


Solution

  • As you say, using @override_settings(DEBUG=True) won't work, because Django has already loaded the URL config and evaluated settings.DEBUG.

    An alternative would be to create another root url config that always includes the debug view.

    # mysite/debug_urls.py
    from django.conf.urls import url
    from mysite.urls import urlpatterns as mysite_urlpatterns
    
    urlpatterns = mysite_urlpatterns + [
        url(...),
    ]
    

    Then, in your test, override the URL config:

    @override_settings(ROOT_URLCONF='mysite.debug_urls')