You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

84 lines
2.4 KiB

  1. import nilmdb
  2. from nilmdb.utils.printf import *
  3. import nose
  4. from nose.tools import *
  5. from nose.tools import assert_raises
  6. import threading
  7. import time
  8. import inspect
  9. from testutil.helpers import *
  10. @nilmdb.utils.lru_cache(size = 3)
  11. def foo1(n):
  12. return n
  13. @nilmdb.utils.lru_cache(size = 5)
  14. def foo2(n):
  15. return n
  16. def foo3d(n):
  17. foo3d.destructed.append(n)
  18. foo3d.destructed = []
  19. @nilmdb.utils.lru_cache(size = 3, onremove = foo3d)
  20. def foo3(n):
  21. return n
  22. class Foo:
  23. def __init__(self):
  24. self.calls = 0
  25. @nilmdb.utils.lru_cache(size = 3, keys = slice(1, 2))
  26. def foo(self, n, **kwargs):
  27. self.calls += 1
  28. class TestLRUCache(object):
  29. def test(self):
  30. [ foo1(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  31. eq_(foo1.cache_info(), (6, 3))
  32. [ foo1(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  33. eq_(foo1.cache_info(), (15, 3))
  34. [ foo1(n) for n in [ 4, 2, 1, 1, 4 ] ]
  35. eq_(foo1.cache_info(), (18, 5))
  36. [ foo2(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  37. eq_(foo2.cache_info(), (6, 3))
  38. [ foo2(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  39. eq_(foo2.cache_info(), (15, 3))
  40. [ foo2(n) for n in [ 4, 2, 1, 1, 4 ] ]
  41. eq_(foo2.cache_info(), (19, 4))
  42. [ foo3(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  43. eq_(foo3.cache_info(), (6, 3))
  44. [ foo3(n) for n in [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] ]
  45. eq_(foo3.cache_info(), (15, 3))
  46. [ foo3(n) for n in [ 4, 2, 1, 1, 4 ] ]
  47. eq_(foo3.cache_info(), (18, 5))
  48. eq_(foo3d.destructed, [1, 3])
  49. with assert_raises(KeyError):
  50. foo3.cache_remove(1,2,3)
  51. foo3.cache_remove(1)
  52. eq_(foo3d.destructed, [1, 3, 1])
  53. foo3.cache_remove_all()
  54. eq_(foo3d.destructed, [1, 3, 1, 2, 4 ])
  55. foo = Foo()
  56. foo.foo(5)
  57. foo.foo(6)
  58. foo.foo(7)
  59. foo.foo(5)
  60. eq_(foo.calls, 3)
  61. # Can't handle keyword arguments right now
  62. with assert_raises(NotImplementedError):
  63. foo.foo(3, asdf = 7)
  64. # Verify that argspecs were maintained
  65. eq_(inspect.getargspec(foo1),
  66. inspect.ArgSpec(args=['n'],
  67. varargs=None, keywords=None, defaults=None))
  68. eq_(inspect.getargspec(foo.foo),
  69. inspect.ArgSpec(args=['self', 'n'],
  70. varargs=None, keywords="kwargs", defaults=None))