test_functional.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from unittest import mock
  2. from django.test import SimpleTestCase
  3. from django.test.utils import ignore_warnings
  4. from django.utils.deprecation import RemovedInDjango50Warning
  5. from django.utils.functional import cached_property, classproperty, lazy
  6. class FunctionalTests(SimpleTestCase):
  7. def test_lazy(self):
  8. t = lazy(lambda: tuple(range(3)), list, tuple)
  9. for a, b in zip(t(), range(3)):
  10. self.assertEqual(a, b)
  11. def test_lazy_base_class(self):
  12. """lazy also finds base class methods in the proxy object"""
  13. class Base:
  14. def base_method(self):
  15. pass
  16. class Klazz(Base):
  17. pass
  18. t = lazy(lambda: Klazz(), Klazz)()
  19. self.assertIn('base_method', dir(t))
  20. def test_lazy_base_class_override(self):
  21. """lazy finds the correct (overridden) method implementation"""
  22. class Base:
  23. def method(self):
  24. return 'Base'
  25. class Klazz(Base):
  26. def method(self):
  27. return 'Klazz'
  28. t = lazy(lambda: Klazz(), Base)()
  29. self.assertEqual(t.method(), 'Klazz')
  30. def test_lazy_object_to_string(self):
  31. class Klazz:
  32. def __str__(self):
  33. return "Î am ā Ǩlâzz."
  34. def __bytes__(self):
  35. return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz."
  36. t = lazy(lambda: Klazz(), Klazz)()
  37. self.assertEqual(str(t), "Î am ā Ǩlâzz.")
  38. self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.")
  39. def assertCachedPropertyWorks(self, attr, Class):
  40. with self.subTest(attr=attr):
  41. def get(source):
  42. return getattr(source, attr)
  43. obj = Class()
  44. class SubClass(Class):
  45. pass
  46. subobj = SubClass()
  47. # Docstring is preserved.
  48. self.assertEqual(get(Class).__doc__, 'Here is the docstring...')
  49. self.assertEqual(get(SubClass).__doc__, 'Here is the docstring...')
  50. # It's cached.
  51. self.assertEqual(get(obj), get(obj))
  52. self.assertEqual(get(subobj), get(subobj))
  53. # The correct value is returned.
  54. self.assertEqual(get(obj)[0], 1)
  55. self.assertEqual(get(subobj)[0], 1)
  56. # State isn't shared between instances.
  57. obj2 = Class()
  58. subobj2 = SubClass()
  59. self.assertNotEqual(get(obj), get(obj2))
  60. self.assertNotEqual(get(subobj), get(subobj2))
  61. # It behaves like a property when there's no instance.
  62. self.assertIsInstance(get(Class), cached_property)
  63. self.assertIsInstance(get(SubClass), cached_property)
  64. # 'other_value' doesn't become a property.
  65. self.assertTrue(callable(obj.other_value))
  66. self.assertTrue(callable(subobj.other_value))
  67. def test_cached_property(self):
  68. """cached_property caches its value and behaves like a property."""
  69. class Class:
  70. @cached_property
  71. def value(self):
  72. """Here is the docstring..."""
  73. return 1, object()
  74. @cached_property
  75. def __foo__(self):
  76. """Here is the docstring..."""
  77. return 1, object()
  78. def other_value(self):
  79. """Here is the docstring..."""
  80. return 1, object()
  81. other = cached_property(other_value)
  82. attrs = ['value', 'other', '__foo__']
  83. for attr in attrs:
  84. self.assertCachedPropertyWorks(attr, Class)
  85. @ignore_warnings(category=RemovedInDjango50Warning)
  86. def test_cached_property_name(self):
  87. class Class:
  88. def other_value(self):
  89. """Here is the docstring..."""
  90. return 1, object()
  91. other = cached_property(other_value, name='other')
  92. other2 = cached_property(other_value, name='different_name')
  93. self.assertCachedPropertyWorks('other', Class)
  94. # An explicit name is ignored.
  95. obj = Class()
  96. obj.other2
  97. self.assertFalse(hasattr(obj, 'different_name'))
  98. def test_cached_property_name_deprecation_warning(self):
  99. def value(self):
  100. return 1
  101. msg = "The name argument is deprecated as it's unnecessary as of Python 3.6."
  102. with self.assertWarnsMessage(RemovedInDjango50Warning, msg):
  103. cached_property(value, name='other_name')
  104. def test_cached_property_auto_name(self):
  105. """
  106. cached_property caches its value and behaves like a property
  107. on mangled methods or when the name kwarg isn't set.
  108. """
  109. class Class:
  110. @cached_property
  111. def __value(self):
  112. """Here is the docstring..."""
  113. return 1, object()
  114. def other_value(self):
  115. """Here is the docstring..."""
  116. return 1, object()
  117. other = cached_property(other_value)
  118. attrs = ['_Class__value', 'other']
  119. for attr in attrs:
  120. self.assertCachedPropertyWorks(attr, Class)
  121. def test_cached_property_reuse_different_names(self):
  122. """Disallow this case because the decorated function wouldn't be cached."""
  123. with self.assertRaises(RuntimeError) as ctx:
  124. class ReusedCachedProperty:
  125. @cached_property
  126. def a(self):
  127. pass
  128. b = a
  129. self.assertEqual(
  130. str(ctx.exception.__context__),
  131. str(TypeError(
  132. "Cannot assign the same cached_property to two different "
  133. "names ('a' and 'b')."
  134. ))
  135. )
  136. def test_cached_property_reuse_same_name(self):
  137. """
  138. Reusing a cached_property on different classes under the same name is
  139. allowed.
  140. """
  141. counter = 0
  142. @cached_property
  143. def _cp(_self):
  144. nonlocal counter
  145. counter += 1
  146. return counter
  147. class A:
  148. cp = _cp
  149. class B:
  150. cp = _cp
  151. a = A()
  152. b = B()
  153. self.assertEqual(a.cp, 1)
  154. self.assertEqual(b.cp, 2)
  155. self.assertEqual(a.cp, 1)
  156. def test_cached_property_set_name_not_called(self):
  157. cp = cached_property(lambda s: None)
  158. class Foo:
  159. pass
  160. Foo.cp = cp
  161. msg = 'Cannot use cached_property instance without calling __set_name__() on it.'
  162. with self.assertRaisesMessage(TypeError, msg):
  163. Foo().cp
  164. def test_lazy_add(self):
  165. lazy_4 = lazy(lambda: 4, int)
  166. lazy_5 = lazy(lambda: 5, int)
  167. self.assertEqual(lazy_4() + lazy_5(), 9)
  168. def test_lazy_equality(self):
  169. """
  170. == and != work correctly for Promises.
  171. """
  172. lazy_a = lazy(lambda: 4, int)
  173. lazy_b = lazy(lambda: 4, int)
  174. lazy_c = lazy(lambda: 5, int)
  175. self.assertEqual(lazy_a(), lazy_b())
  176. self.assertNotEqual(lazy_b(), lazy_c())
  177. def test_lazy_repr_text(self):
  178. original_object = 'Lazy translation text'
  179. lazy_obj = lazy(lambda: original_object, str)
  180. self.assertEqual(repr(original_object), repr(lazy_obj()))
  181. def test_lazy_repr_int(self):
  182. original_object = 15
  183. lazy_obj = lazy(lambda: original_object, int)
  184. self.assertEqual(repr(original_object), repr(lazy_obj()))
  185. def test_lazy_repr_bytes(self):
  186. original_object = b'J\xc3\xbcst a str\xc3\xadng'
  187. lazy_obj = lazy(lambda: original_object, bytes)
  188. self.assertEqual(repr(original_object), repr(lazy_obj()))
  189. def test_lazy_class_preparation_caching(self):
  190. # lazy() should prepare the proxy class only once i.e. the first time
  191. # it's used.
  192. lazified = lazy(lambda: 0, int)
  193. __proxy__ = lazified().__class__
  194. with mock.patch.object(__proxy__, '__prepare_class__') as mocked:
  195. lazified()
  196. mocked.assert_not_called()
  197. def test_lazy_bytes_and_str_result_classes(self):
  198. lazy_obj = lazy(lambda: 'test', str, bytes)
  199. msg = 'Cannot call lazy() with both bytes and text return types.'
  200. with self.assertRaisesMessage(ValueError, msg):
  201. lazy_obj()
  202. def test_classproperty_getter(self):
  203. class Foo:
  204. foo_attr = 123
  205. def __init__(self):
  206. self.foo_attr = 456
  207. @classproperty
  208. def foo(cls):
  209. return cls.foo_attr
  210. class Bar:
  211. bar = classproperty()
  212. @bar.getter
  213. def bar(cls):
  214. return 123
  215. self.assertEqual(Foo.foo, 123)
  216. self.assertEqual(Foo().foo, 123)
  217. self.assertEqual(Bar.bar, 123)
  218. self.assertEqual(Bar().bar, 123)
  219. def test_classproperty_override_getter(self):
  220. class Foo:
  221. @classproperty
  222. def foo(cls):
  223. return 123
  224. @foo.getter
  225. def foo(cls):
  226. return 456
  227. self.assertEqual(Foo.foo, 456)
  228. self.assertEqual(Foo().foo, 456)