Created
April 3, 2012 19:32
-
-
Save blaix/2294982 to your computer and use it in GitHub Desktop.
Stubbing django settings with Mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SOME_SETTING = 'some value' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
def get_some_setting(): | |
return settings.SOME_SETTING |
I think since 1.4v better way:
from django.test.utils import override_settings
@override_settings(SOME_SETTING='some-data')
def test(self):
@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
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
This article was very helpful for me.
Thank you!
But, that way overwrite entire "settings" variable in testing.
How about the following ways
.. or, is there a better way?