Package madrona :: Package common :: Module test_settings_manager
[hide private]

Source Code for Module madrona.common.test_settings_manager

 1  # Shamelessly copied from here: 
 2  # http://www.djangosnippets.org/snippets/1011/ 
 3   
 4  from django.conf import settings 
 5  from django.core.management import call_command 
 6  from django.db.models import loading 
 7  from django.test import TestCase 
 8   
 9  NO_SETTING = ('!', None) 
10   
11 -class TestSettingsManager(object):
12 """ 13 A class which can modify some Django settings temporarily for a 14 test and then revert them to their original values later. 15 16 Automatically handles resyncing the DB if INSTALLED_APPS is 17 modified. 18 19 """
20 - def __init__(self):
21 self._original_settings = {}
22
23 - def set(self, **kwargs):
24 for k,v in kwargs.iteritems(): 25 self._original_settings.setdefault(k, getattr(settings, k, 26 NO_SETTING)) 27 setattr(settings, k, v) 28 if 'INSTALLED_APPS' in kwargs: 29 self.syncdb()
30
31 - def syncdb(self):
32 loading.cache.loaded = False 33 call_command('syncdb', verbosity=0)
34
35 - def revert(self):
36 for k,v in self._original_settings.iteritems(): 37 if v == NO_SETTING: 38 delattr(settings, k) 39 else: 40 setattr(settings, k, v) 41 if 'INSTALLED_APPS' in self._original_settings: 42 self.syncdb() 43 self._original_settings = {}
44 45
46 -class SettingsTestCase(TestCase):
47 """ 48 A subclass of the Django TestCase with a settings_manager 49 attribute which is an instance of TestSettingsManager. 50 51 Comes with a tearDown() method that calls 52 self.settings_manager.revert(). 53 54 """
55 - def __init__(self, *args, **kwargs):
56 super(SettingsTestCase, self).__init__(*args, **kwargs) 57 self.settings_manager = TestSettingsManager()
58
59 - def tearDown(self):
60 self.settings_manager.revert()
61