PageRenderTime 150ms CodeModel.GetById 81ms app.highlight 14ms RepoModel.GetById 46ms app.codeStats 7ms

/tests/regressiontests/decorators/tests.py

https://code.google.com/p/mango-py/
Python | 185 lines | 116 code | 39 blank | 30 comment | 0 complexity | c29178a5544dfc95fabcefb37c86d7ef MD5 | raw file
  1from sys import version_info
  2try:
  3    from functools import wraps
  4except ImportError:
  5    from django.utils.functional import wraps  # Python 2.4 fallback.
  6
  7from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
  8from django.contrib.admin.views.decorators import staff_member_required
  9from django.http import HttpResponse, HttpRequest
 10from django.utils.decorators import method_decorator
 11from django.utils.functional import allow_lazy, lazy, memoize
 12from django.utils.unittest import TestCase
 13from django.views.decorators.http import require_http_methods, require_GET, require_POST
 14from django.views.decorators.vary import vary_on_headers, vary_on_cookie
 15from django.views.decorators.cache import cache_page, never_cache, cache_control
 16
 17
 18def fully_decorated(request):
 19    """Expected __doc__"""
 20    return HttpResponse('<html><body>dummy</body></html>')
 21fully_decorated.anything = "Expected __dict__"
 22
 23# django.views.decorators.http
 24fully_decorated = require_http_methods(["GET"])(fully_decorated)
 25fully_decorated = require_GET(fully_decorated)
 26fully_decorated = require_POST(fully_decorated)
 27
 28# django.views.decorators.vary
 29fully_decorated = vary_on_headers('Accept-language')(fully_decorated)
 30fully_decorated = vary_on_cookie(fully_decorated)
 31
 32# django.views.decorators.cache
 33fully_decorated = cache_page(60*15)(fully_decorated)
 34fully_decorated = cache_control(private=True)(fully_decorated)
 35fully_decorated = never_cache(fully_decorated)
 36
 37# django.contrib.auth.decorators
 38# Apply user_passes_test twice to check #9474
 39fully_decorated = user_passes_test(lambda u:True)(fully_decorated)
 40fully_decorated = login_required(fully_decorated)
 41fully_decorated = permission_required('change_world')(fully_decorated)
 42
 43# django.contrib.admin.views.decorators
 44fully_decorated = staff_member_required(fully_decorated)
 45
 46# django.utils.functional
 47fully_decorated = memoize(fully_decorated, {}, 1)
 48fully_decorated = allow_lazy(fully_decorated)
 49fully_decorated = lazy(fully_decorated)
 50
 51
 52class DecoratorsTest(TestCase):
 53
 54    def test_attributes(self):
 55        """
 56        Tests that django decorators set certain attributes of the wrapped
 57        function.
 58        """
 59        self.assertEqual(fully_decorated.__name__, 'fully_decorated')
 60        self.assertEqual(fully_decorated.__doc__, 'Expected __doc__')
 61        self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
 62
 63    def test_user_passes_test_composition(self):
 64        """
 65        Test that the user_passes_test decorator can be applied multiple times
 66        (#9474).
 67        """
 68        def test1(user):
 69            user.decorators_applied.append('test1')
 70            return True
 71
 72        def test2(user):
 73            user.decorators_applied.append('test2')
 74            return True
 75
 76        def callback(request):
 77            return request.user.decorators_applied
 78
 79        callback = user_passes_test(test1)(callback)
 80        callback = user_passes_test(test2)(callback)
 81
 82        class DummyUser(object): pass
 83        class DummyRequest(object): pass
 84
 85        request = DummyRequest()
 86        request.user = DummyUser()
 87        request.user.decorators_applied = []
 88        response = callback(request)
 89
 90        self.assertEqual(response, ['test2', 'test1'])
 91
 92    def test_cache_page_new_style(self):
 93        """
 94        Test that we can call cache_page the new way
 95        """
 96        def my_view(request):
 97            return "response"
 98        my_view_cached = cache_page(123)(my_view)
 99        self.assertEqual(my_view_cached(HttpRequest()), "response")
100        my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
101        self.assertEqual(my_view_cached2(HttpRequest()), "response")
102
103    def test_cache_page_old_style(self):
104        """
105        Test that we can call cache_page the old way
106        """
107        def my_view(request):
108            return "response"
109        my_view_cached = cache_page(my_view, 123)
110        self.assertEqual(my_view_cached(HttpRequest()), "response")
111        my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
112        self.assertEqual(my_view_cached2(HttpRequest()), "response")
113        my_view_cached3 = cache_page(my_view)
114        self.assertEqual(my_view_cached3(HttpRequest()), "response")
115        my_view_cached4 = cache_page()(my_view)
116        self.assertEqual(my_view_cached4(HttpRequest()), "response")
117
118
119# For testing method_decorator, a decorator that assumes a single argument.
120# We will get type arguments if there is a mismatch in the number of arguments.
121def simple_dec(func):
122    def wrapper(arg):
123        return func("test:" + arg)
124    return wraps(func)(wrapper)
125
126simple_dec_m = method_decorator(simple_dec)
127
128
129# For testing method_decorator, two decorators that add an attribute to the function
130def myattr_dec(func):
131    def wrapper(*args, **kwargs):
132        return func(*args, **kwargs)
133    wrapper.myattr = True
134    return wraps(func)(wrapper)
135
136myattr_dec_m = method_decorator(myattr_dec)
137
138
139def myattr2_dec(func):
140    def wrapper(*args, **kwargs):
141        return func(*args, **kwargs)
142    wrapper.myattr2 = True
143    return wraps(func)(wrapper)
144
145myattr2_dec_m = method_decorator(myattr2_dec)
146
147
148class MethodDecoratorTests(TestCase):
149    """
150    Tests for method_decorator
151    """
152    def test_preserve_signature(self):
153        class Test(object):
154            @simple_dec_m
155            def say(self, arg):
156                return arg
157
158        self.assertEqual("test:hello", Test().say("hello"))
159
160    def test_preserve_attributes(self):
161        # Sanity check myattr_dec and myattr2_dec
162        @myattr_dec
163        @myattr2_dec
164        def func():
165            pass
166
167        self.assertEqual(getattr(func, 'myattr', False), True)
168        self.assertEqual(getattr(func, 'myattr2', False), True)
169
170        # Now check method_decorator
171        class Test(object):
172            @myattr_dec_m
173            @myattr2_dec_m
174            def method(self):
175                "A method"
176                pass
177
178        self.assertEqual(getattr(Test().method, 'myattr', False), True)
179        self.assertEqual(getattr(Test().method, 'myattr2', False), True)
180
181        self.assertEqual(getattr(Test.method, 'myattr', False), True)
182        self.assertEqual(getattr(Test.method, 'myattr2', False), True)
183
184        self.assertEqual(Test.method.__doc__, 'A method')
185        self.assertEqual(Test.method.im_func.__name__, 'method')