How do you set DEBUG to True when running a Django test? - django

I'm currently running some Django tests and it looks that DEBUG=False by default. Is there a way to run a specific test where I can set DEBUG=True at the command line or in code?

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

Starting with Django 1.11 you can use --debug-mode to set the DEBUG setting to True prior to running tests.

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

Okay let's say you want to write tests for error testcase for which the urls are :-
urls.py
if settings.DEBUG:
urlpatterns += [
url(r'^404/$', page_not_found_view),
url(r'^500/$', my_custom_error_view),
url(r'^400/$', bad_request_view),
url(r'^403/$', permission_denied_view),
]
test_urls.py:-
from django.conf import settings
class ErroCodeUrl(TestCase):
def setUp(self):
settings.DEBUG = True
def test_400_error(self):
response = self.client.get('/400/')
self.assertEqual(response.status_code, 500)
Hope you got some idea!

Nothing worked for me except https://stackoverflow.com/a/1118271/5750078
Use Python 3.7
breakpoint()
method.
Works fine on pycharm

You can't see the results of DEBUG=True when running a unit test. The pages don't display anywhere. No browser.
Changing DEBUG has no effect, since the web pages (with the debugging output) are not visible anywhere.
If you want to see a debugging web page related to a failing unit test, then do this.
Drop your development database.
Rerun syncdb to build an empty development database.
Run the various loaddata scripts to rebuild the fixtures for that test in your development database.
Run the server and browse the page.
Now you can see the debug output.

Related

pytest-django won't allow database access even with mark

I'm having a difficult time figuring out what is wrong with my setup. I'm trying to test a login view, and no matter what I try, I keep getting:
Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
My test:
import pytest
from ..models import User
#pytest.mark.django_db
def test_login(client):
# If an anonymous user accesses the login page:
response = client.get('/users/login/')
# Then the server should respond with a successful status code:
assert response.status_code == 200
# Given an existing user:
user = User.objects.get(username='user')
# If we attempt to log into the login page:
response = client.post('/users/login/', {'username': user.username, 'password': 'somepass'})
# Then the server should redirect the user to the default redirect location:
assert response.status_code == 302
My conftest.py file, in the same tests directory:
import pytest
from django.core.management import call_command
#pytest.fixture(autouse=True)
def django_db_setup(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
call_command('loaddata', 'test_users.json')
My pytest.ini file (which specifies the correct Django settings file):
[pytest]
DJANGO_SETTINGS_MODULE = config.settings
I'm stumped. I've tried using scope="session" like in the documentation together with either an #pytest.mark.django_db mark, a db fixture (as a parameter to the test function), or both with no luck. I've commented out each line of the test to figure out which one was triggering the problem, but couldn't figure it out. I could only get the test to run at all if I removed all db-dependent fixtures/marks/code from the test and had a simple assert True. I don't believe the issue is in my Django settings, as the development server runs fine and is able to access the database.
What am I missing here?
Apparently this is a case of "deceiving exception syndrome". I had a migration that created groups with permissions, and since tests run all migrations at once, the post-migrate signal that creates the permissions that migration depends on was never run before getting to that migration.
It seems that if there is any database-related error before the actual tests start running, this exception is raised, which makes it very difficult to debug exactly what is going wrong. I ended up updating my migration script to manually cause permissions to be created so that the migration could run, and the error went away.
You can add below code in your conftest.py as per the official documentation to allow DB access without django_db marker.
#pytest.fixture(autouse=True)
def enable_db_access_for_all_tests(db):
pass
Ref: https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-give-database-access-to-all-my-tests-without-the-django-db-marker

Django Email Backend Setting Not Working

I have a unit test with a test-specific settings file, which includes:
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/my/file/path'
This wasn't working, so I dropped into the debugger to check the settings in the middle of running my test:
ipdb> from django.conf import settings
ipdb> settings.EMAIL_BACKEND
'django.core.mail.backends.locmem.EmailBackend'
ipdb> settings.EMAIL_FILE_PATH
'/my/file/path'
The file path setting worked, but the backend setting didn't!
Does anyone know why?
What else could I check/configure?
Is this something for a bug report?
Django 1.11
This is documented behaviour. Django replaces the regular email backend with a dummy one. You then access the "sent" emails in your tests with mail.outbox. See the docs for more info.
I believe you might be able to override the EMAIL_BACKEND for a single test or testcase with override_settings
from django.test import TestCase, override_settings
class MyTest(TestCase):
#override_settings(EMAIL_BACKEND='django.core.mail.backends.filebased.EmailBackend')
def test_email(self):
...
Follow this example to override the settings in your tests: https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.settings

Django Selenium LiveServerTestCase not loading the page in browser (error 500)

I have a test Django project called MyApp, running over WSGI on port 8083. When I go to http://myapp:8083, I see the standard Django "it's working" page. I wrote a functional test using selenium bindings in Django to launch a browser and load the above mentioned page. When I run the test, though, I get an error message "Address already in use". So I run the test using another port like this: python manage.py test --liveserver=myapp:8084
This opens the browser, but shows "Page not found" error instead of the default Django page. What am I doing wrong? Any ideas? Thank you!
The test.py file content:
class CoreSeleniumTestCase(LiveServerTestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
cls.driver.maximize_window()
super(CoreSeleniumTestCase, cls).setUpClass()
#classmethod
def tearDownClass(cls):
cls.driver.quit()
super(CoreSeleniumTestCase, cls).tearDownClass()
def testIndexShouldLoad(self):
self.driver.get('%s%s' % (self.live_server_url, '/'))
I finally found the problem. At some point, Django removed MEDIA_ROOT from the settings.py file by default. It turns out that this setting must be in the file for Selenium tests to work properly. Once I reintroduced the setting and assigned a directory to it, the Selenium tests started to work as expected.

Django LiveTestServerCase not using proper settings

In a Django project I'm using selenium to run some UI tests, using a LiveServerTestCase.
One of my test cases is failing, and when using the Firefox driver I can see a page throwing "Server Error (500)", which means DEBUG is set to False which is not the case when I run the local development server.
How is the test server being launched? Why is not using my settings which define DEBUG = True?
Other URLs (such as the homepage URL) return fine, so the server is working. But I just don't get why it's not showing debug information, and which settings it's using.
My test case for reference:
class LoginTest(LiveServerTestCase):
#classmethod
def setUpClass(cls):
try:
from selenium.webdriver import PhantomJS
cls.selenium = PhantomJS()
except:
from selenium.webdriver.firefox.webdriver import WebDriver
cls.selenium = WebDriver()
super(LoginTest, cls).setUpClass()
#classmethod
def tearDownClass(cls):
cls.selenium.quit()
super(LoginTest, cls).tearDownClass()
def test_fb_login(self):
self.selenium.get('%s%s' % (self.live_server_url, reverse('account_login')))
# TEST SERVER RETURNS 500 ON THIS URL WITH NO DEBUG INFO
According to Testing Django Application - Django Documentation:
Regardless of the value of the DEBUG setting in your configuration
file, all Django tests run with DEBUG=False. This is to ensure that
the observed output of your code matches what will be seen in a
production setting.
It should still be possible to override this using:
with self.settings(DEBUG=True):
...
Although I wouldn't recommend it, it can still be useful from time to time. (Thomas Orozco's comment)
You can also change your settings in TestCase setUp() method.
from django.conf import settings
class MyTest(LiveServerTestCase):
def setUp(self):
# Change settings here
settings.DEBUG = True
# ...
I ran into the same issue and it is possible to override settings with a decorator.
based on your example you would import override_settings and place the decorator above the class:
from django.conf import settings
from django.test import override_settings
#override_settings(DEBUG=True)
class LoginTest(LiveServerTestCase):
...
details in django docs

Django app_cache_ready method returns True on Dev and False on production

I can't figure out what can be the reason.
On my dev machine the exactly same django project runs properly, while on production in the custom middleware code app_cache_ready() method always returns False. If I ignore and bypass it cache.set does not cache the object.
My dev environment uses runserver to launch the server, while the production uses Apache and mod_wsgi with virtualhost directives.
Does anyone have a clue what might be the problem? I have already spent couple of hours with no success.
Thanks in advance
Below is the simplified code that fails to cache again:
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, Http404
from django.core.cache import cache
from django.db.models.loading import app_cache_ready
from django.utils.cache import patch_vary_headers
class MyMiddleware(object):
def process_request(self, request):
key='kuku'
val=cache.get(key)
if not val:
logger.warn('Cached key is not available')
cache.set(key,5)
else:
logger.warn('Cached key is %s' % str(val))
With subsequent calls I see always Cached key is not available.