mirror of
https://github.com/django/django.git
synced 2025-08-03 10:34:04 +00:00
Fixed #25146 -- Allowed method_decorator() to decorate classes.
This commit is contained in:
parent
1a76257b1b
commit
3bdaaf6777
5 changed files with 102 additions and 9 deletions
|
@ -7,6 +7,7 @@ from django.contrib.auth.decorators import (
|
|||
)
|
||||
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
|
||||
from django.middleware.clickjacking import XFrameOptionsMiddleware
|
||||
from django.test import SimpleTestCase
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.functional import allow_lazy, lazy
|
||||
from django.views.decorators.cache import (
|
||||
|
@ -189,7 +190,7 @@ class ClsDec(object):
|
|||
return update_wrapper(wrapped, f)
|
||||
|
||||
|
||||
class MethodDecoratorTests(TestCase):
|
||||
class MethodDecoratorTests(SimpleTestCase):
|
||||
"""
|
||||
Tests for method_decorator
|
||||
"""
|
||||
|
@ -274,6 +275,54 @@ class MethodDecoratorTests(TestCase):
|
|||
|
||||
self.assertEqual(Test().method(1), 1)
|
||||
|
||||
def test_class_decoration(self):
|
||||
"""
|
||||
@method_decorator can be used to decorate a class and its methods.
|
||||
"""
|
||||
def deco(func):
|
||||
def _wrapper(*args, **kwargs):
|
||||
return True
|
||||
return _wrapper
|
||||
|
||||
@method_decorator(deco, name="method")
|
||||
class Test(object):
|
||||
def method(self):
|
||||
return False
|
||||
|
||||
self.assertTrue(Test().method())
|
||||
|
||||
def test_invalid_non_callable_attribute_decoration(self):
|
||||
"""
|
||||
@method_decorator on a non-callable attribute raises an error.
|
||||
"""
|
||||
msg = (
|
||||
"Cannot decorate 'prop' as it isn't a callable attribute of "
|
||||
"<class 'Test'> (1)"
|
||||
)
|
||||
with self.assertRaisesMessage(TypeError, msg):
|
||||
@method_decorator(lambda: None, name="prop")
|
||||
class Test(object):
|
||||
prop = 1
|
||||
|
||||
@classmethod
|
||||
def __module__(cls):
|
||||
return "tests"
|
||||
|
||||
def test_invalid_method_name_to_decorate(self):
|
||||
"""
|
||||
@method_decorator on a nonexistent method raises an error.
|
||||
"""
|
||||
msg = (
|
||||
"The keyword argument `name` must be the name of a method of the "
|
||||
"decorated class: <class 'Test'>. Got 'non_existing_method' instead"
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
@method_decorator(lambda: None, name="non_existing_method")
|
||||
class Test(object):
|
||||
@classmethod
|
||||
def __module__(cls):
|
||||
return "tests"
|
||||
|
||||
|
||||
class XFrameOptionsDecoratorsTests(TestCase):
|
||||
"""
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue