test_Cache.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #
  2. # Copyright (c) Daniel Sheffield 2023
  3. #
  4. # All rights reserved
  5. #
  6. # THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
  7. from pytest import fixture
  8. from time import time
  9. from app.rest.PageCache import PageCache
  10. from app.rest.CachedLoadingPage import (
  11. CachedLoadingPage,
  12. )
  13. @fixture
  14. def cache():
  15. return PageCache(0)
  16. def test_add(cache: PageCache):
  17. val = 'test-cached-value'
  18. key = 'test-key'
  19. assert cache.add(key, CachedLoadingPage(val, lambda _: None, incremental=False)).value == val
  20. def test_get(cache: PageCache):
  21. val = 'test-cached-value'
  22. key = 'test-key'
  23. assert cache.get(key) is None
  24. assert cache.add(key, CachedLoadingPage(val, lambda q: q.put('next-val'), incremental=False)).value == val
  25. assert cache.get(key).value == 'next-val'
  26. def test_remove(cache: PageCache):
  27. val = 'test-cached-value'
  28. key = 'test-key'
  29. assert cache.get(key) is None
  30. assert cache.add(key, CachedLoadingPage(val, lambda q: q.put('next-val'), incremental=False)).value == val
  31. cache.remove(key)
  32. assert cache.get(key) is None
  33. def test_enforce_limit(cache: PageCache):
  34. val = 'test-cached-value'
  35. key = 'test-key'
  36. assert cache.add(key, CachedLoadingPage(val, lambda _: None, incremental=False)).value == val
  37. # adding more exceeds limit
  38. assert cache.add('other', CachedLoadingPage(val, lambda _: None, incremental=False)).value == val
  39. assert cache.get(key) is None
  40. assert cache.get('other').value == val
  41. def test_clean_stale(cache: PageCache):
  42. val = 'test-cached-value'
  43. key = 'test-key'
  44. page = CachedLoadingPage(val, lambda _: None, incremental=False)
  45. page._created = time() - 10*60
  46. # add stale page
  47. assert cache.add(key, page).value == val
  48. assert cache.get(key) is None
  49. page = CachedLoadingPage(val, lambda _: None, incremental=False)
  50. assert cache.add(key, page).value == val
  51. # make page stale
  52. page._created = time() - 10*60
  53. assert cache.get(key) is None
  54. page = CachedLoadingPage(val, lambda _: None, incremental=False)
  55. assert cache.add(key, page).value == val
  56. # make page stale
  57. page._created = time() - 10*60
  58. # stale page is rotated out on addition
  59. assert cache.add('other', CachedLoadingPage(val, lambda _: None, incremental=False)).value == val
  60. assert cache.get(key) is None
  61. assert cache.get('other').value == val