Skip to content

Instantly share code, notes, and snippets.

@blaix
Created April 3, 2012 19:32
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaix/2294982 to your computer and use it in GitHub Desktop.
Save blaix/2294982 to your computer and use it in GitHub Desktop.
Stubbing django settings with Mock
SOME_SETTING = 'some value'
from django.test import TestCase
from myapp.utils import get_some_setting
from mock import patch
class SimpleTest(TestCase):
# see http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch
@patch('myapp.utils.settings', SOME_SETTING='FAKED!')
def test_get_some_setting_returns_some_setting(self, settings):
assert get_some_setting() == 'FAKED!'
from django.conf import settings
def get_some_setting():
return settings.SOME_SETTING
@kjirou
Copy link

kjirou commented Dec 24, 2012

This article was very helpful for me.
Thank you!

But, that way overwrite entire "settings" variable in testing.
How about the following ways

from django.conf import settings
import myapp

def _get_some_setting():
    return settings.SOME_SETTING

def get_some_setting():
    return myapp.utils._get_some_setting()
@patch('myapp.utils._get_some_setting', return_value='FAKED!')

.. or, is there a better way?

@pymen
Copy link

pymen commented Mar 13, 2014

I think since 1.4v better way:

from django.test.utils import override_settings

@override_settings(SOME_SETTING='some-data')
def test(self):

@jvc26
Copy link

jvc26 commented Mar 19, 2014

@pymen - unfortunately that approach doesn't work if you've already imported the value at the point of module load.

If mymodule has already been imported with the original settings, you don't get the @override_settings() update, and so the mock solution is a good workaround for this

@ChiChou
Copy link

ChiChou commented Oct 15, 2014

Django 1.4 provides a decoraor @override_settings allows you mock Django settings.
So the recommended way is:

from django.test.utils import override_settings
...


class ABCTest(TestCase)

    @override_settings(DEBUG=False)
    def test_xyz(self):
        # do something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment