Testing and Django settings¶
Django uses a from django.conf import settings configuration mechanism,
which makes it hard to test. The settings object is global. You have to do set
a setting and revert the change at the end of a test; quite messy.
You can do a bit better, in such a situation, by using the excellent mock library. But even mock is defeated sometimes by Django’s settings. I tried a couple of variants like the following and failed to change the settings:
import mock
class XYZTest(TestCase)
@mock.patch('django.conf.settings.DEBUG', False)
def test_xyz(self):
# ...
# Well, I'm importing settings in my views module...
@mock.patch('my_app.views.settings.DEBUG', False)
def test_xyz2(self):
# ...
After some googling I discovered something I totally missed. Django 1.4 has something real useful. The @override_settings decorator. Does exactly what I want it to do:
from django.test.utils import override_settings
...
class XYZTest(TestCase)
@override_settings(DEBUG=False)
def test_xyz(self):
# ...
Hurray!