Created
February 18, 2011 15:04
-
-
Save prestontimmons/833776 to your computer and use it in GitHub Desktop.
Override a Django setting during a test with a context processor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
''' | |
Borrowed from Django CMS. This is too useful to live without | |
''' | |
from django.conf import settings | |
class NULL: | |
pass | |
class SettingsOverride(object): | |
""" | |
Overrides Django settings within a context and resets them to their inital | |
values on exit. | |
Example: | |
with SettingsOverride(DEBUG=True): | |
# do something | |
""" | |
def __init__(self, **overrides): | |
self.overrides = overrides | |
def __enter__(self): | |
self.old = {} | |
for key, value in self.overrides.items(): | |
self.old[key] = getattr(settings, key, NULL) | |
setattr(settings, key, value) | |
def __exit__(self, type, value, traceback): | |
for key, value in self.old.items(): | |
if value is not NULL: | |
setattr(settings, key, value) | |
else: | |
delattr(settings,key) # do not pollute the context! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment