Last Updated: February 25, 2016
·
4.827K
· prudnikov

Custom settings when testing Django app

Sometimes you want to use different settings in your unittest test cases. Sometimes I see people doing it wrong, but there is an easy way of doing this by using override_settings decorator.

from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings

class MyTest(TestCase):
    @override_settings(INTERNAL_IPS=())
    def test_public_access(self):
        self.assertEqual(settings.INTERNAL_IPS, ())

    @override_settings(INTERNAL_IPS=('127.0.0.1',))
    def test_internal_access(self):
        self.assertEqual(settings.INTERNAL_IPS, ('127.0.0.1',))

    @override_settings(SOME_NEW_SETTINGS="YES")
    def test_custom_settings(self):
        self.assertEqual(
            getattr(settings, "SOME_NEW_SETTINGS", "NO"), 
            "YES"
        )