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