Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
YPCrumble Avatar asked Nov 02 '25 04:11

YPCrumble


1 Answers

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') 
like image 100
Alasdair Avatar answered Nov 04 '25 02:11

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!