Commits

Lukas Linhart committed 924bf08

Added utility function for mocking settings attribute (refs #34)

  • Participants
  • Parent commits f96186c

Comments (0)

Files changed (3)

djangosanetesting/utils.py

 
     return twill_go_with_relative_paths
 
+def mock_settings(settings_attribute, value):
+    def wrapper(f):
+        def wrapped(*args, **kwargs):
+            if hasattr(settings, settings_attribute):
+                delete = True
+            else:
+                delete = False
+                original_value = getattr(settings, settings_attribute)
+
+            setattr(settings, settings_attribute, value)
+
+            retval = f(*args, **kwargs)
+
+            if delete:
+                delattr(settings, settings_attribute)
+            else:
+                setattr(settings, settings_attribute, original_value)
+
+            return retval
+        return wrapped
+    return wrapper
+

testproject/settings.py

 
 CACHE_BACKEND = 'locmem://'
 
+NONSENSICAL_SETTING_ATTRIBUTE_FOR_MOCK_TESTING = "owned"
+
 from config import *
 

testproject/test/test_unit.py

 # -*- coding: utf-8 -*-
 from djangosanetesting.cases import UnitTestCase
+from djangosanetesting.utils import mock_settings
 
 from django.core.cache import cache
+from django.conf import settings
 
 from testapp.models import ExampleModel
 
 
 def function_test():
     # just to verify we work with them
-    assert True is True
+    assert True is True
+
+class TestMocking(UnitTestCase):
+
+    def test_sanity_for_missing_setting_present(self):
+        self.assert_false(hasattr(settings, "INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT"))
+    
+    def test_expected_setting_present(self):
+        self.assert_equals("owned", settings.NONSENSICAL_SETTING_ATTRIBUTE_FOR_MOCK_TESTING)
+
+    @mock_settings("INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT", "Cthulhed!")
+    def test_setting_mocked(self):
+        self.assert_equals("Cthulhed!", settings.INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT)
+
+    @mock_settings("NONSENSICAL_SETTING_ATTRIBUTE_FOR_MOCK_TESTING", "pwned!")
+    def test_existing_setting_mocked(self):
+        self.assert_equals("pwned!", settings.NONSENSICAL_SETTING_ATTRIBUTE_FOR_MOCK_TESTING)