How do you set DEBUG to True when running a Django test?
Solution 1:
For a specific test inside a test case, you can use the override_settings decorator:
from django.test.utils import override_settings
from django.conf import settings
class TestSomething(TestCase):
@override_settings(DEBUG=True)
def test_debug(self):
assert settings.DEBUG
Solution 2:
Starting with Django 1.11 you can use --debug-mode
to set the DEBUG setting to True prior to running tests.
Solution 3:
The accepted answer didn't work for me. I use Selenium for testing, and setting @override_settings(DEBUG=True)
makes the test browser always display 404
error on every page. And DEBUG=False
does not show exception tracebacks. So I found a workaround.
The idea is to emulate DEBUG=True
behaviour, using custom 500
handler and built-in django 500
error handler.
-
Add this to myapp.views:
import sys from django import http from django.views.debug import ExceptionReporter def show_server_error(request): """ 500 error handler to show Django default 500 template with nice error information and traceback. Useful in testing, if you can't set DEBUG=True. Templates: `500.html` Context: sys.exc_info() results """ exc_type, exc_value, exc_traceback = sys.exc_info() error = ExceptionReporter(request, exc_type, exc_value, exc_traceback) return http.HttpResponseServerError(error.get_traceback_html())
-
urls.py:
from django.conf import settings if settings.TESTING_MODE: # enable this handler only for testing, # so that if DEBUG=False and we're not testing, # the default handler is used handler500 = 'myapp.views.show_server_error'
-
settings.py:
# detect testing mode import sys TESTING_MODE = 'test' in sys.argv
Now if any of your Selenium tests encounters 500 error, you'll see a nice error page with traceback and everything. If you run a normal non-testing environment, default 500 handler is used.
Inspired by:
- Where in django is the default 500 traceback rendered so that I can use it to create my own logs?
- django - how to detect test environment