Package expedient :: Package common :: Package tests :: Module manager
[hide private]
[frames] | no frames]

Source Code for Module expedient.common.tests.manager

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