lrucache.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from ..lrucache import LRUCache
  2. import pytest
  3. from tempfile import TemporaryFile
  4. class TestLRUCache:
  5. def test_lrucache(self):
  6. c = LRUCache(2, dispose=lambda _: None)
  7. assert len(c) == 0
  8. assert c.items() == set()
  9. for i, x in enumerate('abc'):
  10. c[x] = i
  11. assert len(c) == 2
  12. assert c.items() == set([('b', 1), ('c', 2)])
  13. assert 'a' not in c
  14. assert 'b' in c
  15. with pytest.raises(KeyError):
  16. c['a']
  17. assert c['b'] == 1
  18. assert c['c'] == 2
  19. c['d'] = 3
  20. assert len(c) == 2
  21. assert c['c'] == 2
  22. assert c['d'] == 3
  23. del c['c']
  24. assert len(c) == 1
  25. with pytest.raises(KeyError):
  26. c['c']
  27. assert c['d'] == 3
  28. c.clear()
  29. assert c.items() == set()
  30. def test_dispose(self):
  31. c = LRUCache(2, dispose=lambda f: f.close())
  32. f1 = TemporaryFile()
  33. f2 = TemporaryFile()
  34. f3 = TemporaryFile()
  35. c[1] = f1
  36. c[2] = f2
  37. assert not f2.closed
  38. c[3] = f3
  39. assert 1 not in c
  40. assert f1.closed
  41. assert 2 in c
  42. assert not f2.closed
  43. del c[2]
  44. assert 2 not in c
  45. assert f2.closed
  46. c.clear()
  47. assert c.items() == set()
  48. assert f3.closed