1
2
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
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 """
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
32 loading.cache.loaded = False
33 call_command('syncdb', verbosity=0)
34
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
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 """
58
60 self.settings_manager.revert()
61