test_functional.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import unittest
  2. from django.utils.functional import lazy, lazy_property, cached_property
  3. class FunctionalTestCase(unittest.TestCase):
  4. def test_lazy(self):
  5. t = lazy(lambda: tuple(range(3)), list, tuple)
  6. for a, b in zip(t(), range(3)):
  7. self.assertEqual(a, b)
  8. def test_lazy_base_class(self):
  9. """Test that lazy also finds base class methods in the proxy object"""
  10. class Base(object):
  11. def base_method(self):
  12. pass
  13. class Klazz(Base):
  14. pass
  15. t = lazy(lambda: Klazz(), Klazz)()
  16. self.assertTrue('base_method' in dir(t))
  17. def test_lazy_property(self):
  18. class A(object):
  19. def _get_do(self):
  20. raise NotImplementedError
  21. def _set_do(self, value):
  22. raise NotImplementedError
  23. do = lazy_property(_get_do, _set_do)
  24. class B(A):
  25. def _get_do(self):
  26. return "DO IT"
  27. self.assertRaises(NotImplementedError, lambda: A().do)
  28. self.assertEqual(B().do, 'DO IT')
  29. def test_cached_property(self):
  30. """
  31. Test that cached_property caches its value,
  32. and that it behaves like a property
  33. """
  34. class A(object):
  35. @cached_property
  36. def value(self):
  37. return 1, object()
  38. def other_value(self):
  39. return 1
  40. other = cached_property(other_value, name='other')
  41. a = A()
  42. # check that it is cached
  43. self.assertEqual(a.value, a.value)
  44. # check that it returns the right thing
  45. self.assertEqual(a.value[0], 1)
  46. # check that state isn't shared between instances
  47. a2 = A()
  48. self.assertNotEqual(a.value, a2.value)
  49. # check that it behaves like a property when there's no instance
  50. self.assertIsInstance(A.value, cached_property)
  51. # check that overriding name works
  52. self.assertEqual(a.other, 1)
  53. self.assertTrue(callable(a.other_value))
  54. def test_lazy_equality(self):
  55. """
  56. Tests that == and != work correctly for Promises.
  57. """
  58. lazy_a = lazy(lambda: 4, int)
  59. lazy_b = lazy(lambda: 4, int)
  60. lazy_c = lazy(lambda: 5, int)
  61. self.assertEqual(lazy_a(), lazy_b())
  62. self.assertNotEqual(lazy_b(), lazy_c())