Backport an updated override_settings now included in Django trunk

Works better when decorating a TestCase
This commit is contained in:
Eric Davis 2011-06-29 10:47:37 -07:00
parent 7fafba34b4
commit 5bf02a8a07

View file

@ -10,14 +10,13 @@ from django.template import Template, Context, RequestContext
from django.test.testcases import TestCase as DjangoTestCase
from django.utils.functional import wraps
# Backported from Django trunk (r16377)
class override_settings(object):
"""
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the ``with`` statement. In either event entering/exiting
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the ``with`` statement. In either event entering/exiting
are called before and after, respectively, the function/block is executed.
Via: http://djangosnippets.org/snippets/2437/
"""
def __init__(self, **kwargs):
self.options = kwargs
@ -29,11 +28,21 @@ class override_settings(object):
def __exit__(self, exc_type, exc_value, traceback):
self.disable()
def __call__(self, func):
@wraps(func)
def inner(*args, **kwargs):
with self:
return func(*args, **kwargs)
def __call__(self, test_func):
from django.test import TestCase
if isinstance(test_func, type) and issubclass(test_func, TestCase):
class inner(test_func):
def _pre_setup(innerself):
self.enable()
super(inner, innerself)._pre_setup()
def _post_teardown(innerself):
super(inner, innerself)._post_teardown()
self.disable()
else:
@wraps(test_func)
def inner(*args, **kwargs):
with self:
return test_func(*args, **kwargs)
return inner
def enable(self):