Testing and Django settings

Tags: django

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!

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):