test_cache.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import sys
  2. from sympy.core.cache import cacheit, cached_property, lazy_function
  3. from sympy.testing.pytest import raises
  4. def test_cacheit_doc():
  5. @cacheit
  6. def testfn():
  7. "test docstring"
  8. pass
  9. assert testfn.__doc__ == "test docstring"
  10. assert testfn.__name__ == "testfn"
  11. def test_cacheit_unhashable():
  12. @cacheit
  13. def testit(x):
  14. return x
  15. assert testit(1) == 1
  16. assert testit(1) == 1
  17. a = {}
  18. assert testit(a) == {}
  19. a[1] = 2
  20. assert testit(a) == {1: 2}
  21. def test_cachit_exception():
  22. # Make sure the cache doesn't call functions multiple times when they
  23. # raise TypeError
  24. a = []
  25. @cacheit
  26. def testf(x):
  27. a.append(0)
  28. raise TypeError
  29. raises(TypeError, lambda: testf(1))
  30. assert len(a) == 1
  31. a.clear()
  32. # Unhashable type
  33. raises(TypeError, lambda: testf([]))
  34. assert len(a) == 1
  35. @cacheit
  36. def testf2(x):
  37. a.append(0)
  38. raise TypeError("Error")
  39. a.clear()
  40. raises(TypeError, lambda: testf2(1))
  41. assert len(a) == 1
  42. a.clear()
  43. # Unhashable type
  44. raises(TypeError, lambda: testf2([]))
  45. assert len(a) == 1
  46. def test_cached_property():
  47. class A:
  48. def __init__(self, value):
  49. self.value = value
  50. self.calls = 0
  51. @cached_property
  52. def prop(self):
  53. self.calls = self.calls + 1
  54. return self.value
  55. a = A(2)
  56. assert a.calls == 0
  57. assert a.prop == 2
  58. assert a.calls == 1
  59. assert a.prop == 2
  60. assert a.calls == 1
  61. b = A(None)
  62. assert b.prop == None
  63. def test_lazy_function():
  64. module_name='xmlrpc.client'
  65. function_name = 'gzip_decode'
  66. lazy = lazy_function(module_name, function_name)
  67. assert lazy(b'') == b''
  68. assert module_name in sys.modules
  69. assert function_name in str(lazy)
  70. repr_lazy = repr(lazy)
  71. assert 'LazyFunction' in repr_lazy
  72. assert function_name in repr_lazy
  73. lazy = lazy_function('sympy.core.cache', 'cheap')