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!

blog comments powered by Disqus
 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

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):