Commits

Lukas Linhart committed 518c9e5

Properly decorate mock_settings wrapped function to be recognized by nose (refs #34)

  • Participants
  • Parent commits 3c82a31

Comments (0)

Files changed (2)

djangosanetesting/utils.py

 import os
+from functools import wraps
 from django.conf import settings
 
 DEFAULT_LIVE_SERVER_PROTOCOL = "http"
 
 def mock_settings(settings_attribute, value):
     def wrapper(f):
+        @wraps(f)
         def wrapped(*args, **kwargs):
-            if hasattr(settings, settings_attribute):
+            if not hasattr(settings, settings_attribute):
                 delete = True
             else:
                 delete = False
 
             setattr(settings, settings_attribute, value)
 
-            retval = f(*args, **kwargs)
-
-            if delete:
-                delattr(settings, settings_attribute)
-            else:
-                setattr(settings, settings_attribute, original_value)
+            try:
+                retval = f(*args, **kwargs)
+            finally:
+                if delete:
+                    # could not delete directly as LazyObject does not implement
+                    # __delattr__ properly
+                    if settings._wrapped:
+                        delattr(settings._wrapped, settings_attribute)
+                else:
+                    setattr(settings, settings_attribute, original_value)
 
             return retval
         return wrapped

testproject/test/test_unit.py

     @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)
+
+class TestMockingCleansAfterItself(UnitTestCase):
+    @mock_settings("INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT", "Cthulhed!")
+    def test_aaa_mocked(self):
+        self.assert_equals("Cthulhed!", settings.INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT)
+
+    def test_bbb_attribute_not_present(self):
+        self.assert_false(hasattr(settings, "INSANE_ATTRIBUTE_THAT_SHOULD_NOT_BE_PRESENT"))
+