test_lru_cache.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. # Copyright (C) 2006, 2008 Canonical Ltd
  2. #
  3. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  4. # General Public License as public by the Free Software Foundation; version 2.0
  5. # or (at your option) any later version. You can redistribute it and/or
  6. # modify it under the terms of either of these two licenses.
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. #
  14. # You should have received a copy of the licenses; if not, see
  15. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  16. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  17. # License, Version 2.0.
  18. #
  19. """Tests for the lru_cache module."""
  20. from dulwich import (
  21. lru_cache,
  22. )
  23. from dulwich.tests import (
  24. TestCase,
  25. )
  26. class TestLRUCache(TestCase):
  27. """Test that LRU cache properly keeps track of entries."""
  28. def test_cache_size(self):
  29. cache = lru_cache.LRUCache(max_cache=10)
  30. self.assertEqual(10, cache.cache_size())
  31. cache = lru_cache.LRUCache(max_cache=256)
  32. self.assertEqual(256, cache.cache_size())
  33. cache.resize(512)
  34. self.assertEqual(512, cache.cache_size())
  35. def test_missing(self):
  36. cache = lru_cache.LRUCache(max_cache=10)
  37. self.assertNotIn("foo", cache)
  38. self.assertRaises(KeyError, cache.__getitem__, "foo")
  39. cache["foo"] = "bar"
  40. self.assertEqual("bar", cache["foo"])
  41. self.assertIn("foo", cache)
  42. self.assertNotIn("bar", cache)
  43. def test_map_None(self):
  44. # Make sure that we can properly map None as a key.
  45. cache = lru_cache.LRUCache(max_cache=10)
  46. self.assertNotIn(None, cache)
  47. cache[None] = 1
  48. self.assertEqual(1, cache[None])
  49. cache[None] = 2
  50. self.assertEqual(2, cache[None])
  51. # Test the various code paths of __getitem__, to make sure that we can
  52. # handle when None is the key for the LRU and the MRU
  53. cache[1] = 3
  54. cache[None] = 1
  55. cache[None]
  56. cache[1]
  57. cache[None]
  58. self.assertEqual([None, 1], [n.key for n in cache._walk_lru()])
  59. def test_add__null_key(self):
  60. cache = lru_cache.LRUCache(max_cache=10)
  61. self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
  62. def test_overflow(self):
  63. """Adding extra entries will pop out old ones."""
  64. cache = lru_cache.LRUCache(max_cache=1, after_cleanup_count=1)
  65. cache["foo"] = "bar"
  66. # With a max cache of 1, adding 'baz' should pop out 'foo'
  67. cache["baz"] = "biz"
  68. self.assertNotIn("foo", cache)
  69. self.assertIn("baz", cache)
  70. self.assertEqual("biz", cache["baz"])
  71. def test_by_usage(self):
  72. """Accessing entries bumps them up in priority."""
  73. cache = lru_cache.LRUCache(max_cache=2)
  74. cache["baz"] = "biz"
  75. cache["foo"] = "bar"
  76. self.assertEqual("biz", cache["baz"])
  77. # This must kick out 'foo' because it was the last accessed
  78. cache["nub"] = "in"
  79. self.assertNotIn("foo", cache)
  80. def test_cleanup(self):
  81. """Test that we can use a cleanup function."""
  82. cleanup_called = []
  83. def cleanup_func(key, val):
  84. cleanup_called.append((key, val))
  85. cache = lru_cache.LRUCache(max_cache=2, after_cleanup_count=2)
  86. cache.add("baz", "1", cleanup=cleanup_func)
  87. cache.add("foo", "2", cleanup=cleanup_func)
  88. cache.add("biz", "3", cleanup=cleanup_func)
  89. self.assertEqual([("baz", "1")], cleanup_called)
  90. # 'foo' is now most recent, so final cleanup will call it last
  91. cache["foo"]
  92. cache.clear()
  93. self.assertEqual([("baz", "1"), ("biz", "3"), ("foo", "2")], cleanup_called)
  94. def test_cleanup_on_replace(self):
  95. """Replacing an object should cleanup the old value."""
  96. cleanup_called = []
  97. def cleanup_func(key, val):
  98. cleanup_called.append((key, val))
  99. cache = lru_cache.LRUCache(max_cache=2)
  100. cache.add(1, 10, cleanup=cleanup_func)
  101. cache.add(2, 20, cleanup=cleanup_func)
  102. cache.add(2, 25, cleanup=cleanup_func)
  103. self.assertEqual([(2, 20)], cleanup_called)
  104. self.assertEqual(25, cache[2])
  105. # Even __setitem__ should make sure cleanup() is called
  106. cache[2] = 26
  107. self.assertEqual([(2, 20), (2, 25)], cleanup_called)
  108. def test_len(self):
  109. cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
  110. cache[1] = 10
  111. cache[2] = 20
  112. cache[3] = 30
  113. cache[4] = 40
  114. self.assertEqual(4, len(cache))
  115. cache[5] = 50
  116. cache[6] = 60
  117. cache[7] = 70
  118. cache[8] = 80
  119. self.assertEqual(8, len(cache))
  120. cache[1] = 15 # replacement
  121. self.assertEqual(8, len(cache))
  122. cache[9] = 90
  123. cache[10] = 100
  124. cache[11] = 110
  125. # We hit the max
  126. self.assertEqual(10, len(cache))
  127. self.assertEqual(
  128. [11, 10, 9, 1, 8, 7, 6, 5, 4, 3],
  129. [n.key for n in cache._walk_lru()],
  130. )
  131. def test_cleanup_shrinks_to_after_clean_count(self):
  132. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3)
  133. cache.add(1, 10)
  134. cache.add(2, 20)
  135. cache.add(3, 25)
  136. cache.add(4, 30)
  137. cache.add(5, 35)
  138. self.assertEqual(5, len(cache))
  139. # This will bump us over the max, which causes us to shrink down to
  140. # after_cleanup_cache size
  141. cache.add(6, 40)
  142. self.assertEqual(3, len(cache))
  143. def test_after_cleanup_larger_than_max(self):
  144. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10)
  145. self.assertEqual(5, cache._after_cleanup_count)
  146. def test_after_cleanup_none(self):
  147. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=None)
  148. # By default _after_cleanup_size is 80% of the normal size
  149. self.assertEqual(4, cache._after_cleanup_count)
  150. def test_cleanup_2(self):
  151. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
  152. # Add these in order
  153. cache.add(1, 10)
  154. cache.add(2, 20)
  155. cache.add(3, 25)
  156. cache.add(4, 30)
  157. cache.add(5, 35)
  158. self.assertEqual(5, len(cache))
  159. # Force a compaction
  160. cache.cleanup()
  161. self.assertEqual(2, len(cache))
  162. def test_preserve_last_access_order(self):
  163. cache = lru_cache.LRUCache(max_cache=5)
  164. # Add these in order
  165. cache.add(1, 10)
  166. cache.add(2, 20)
  167. cache.add(3, 25)
  168. cache.add(4, 30)
  169. cache.add(5, 35)
  170. self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()])
  171. # Now access some randomly
  172. cache[2]
  173. cache[5]
  174. cache[3]
  175. cache[2]
  176. self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()])
  177. def test_get(self):
  178. cache = lru_cache.LRUCache(max_cache=5)
  179. cache.add(1, 10)
  180. cache.add(2, 20)
  181. self.assertEqual(20, cache.get(2))
  182. self.assertEqual(None, cache.get(3))
  183. obj = object()
  184. self.assertIs(obj, cache.get(3, obj))
  185. self.assertEqual([2, 1], [n.key for n in cache._walk_lru()])
  186. self.assertEqual(10, cache.get(1))
  187. self.assertEqual([1, 2], [n.key for n in cache._walk_lru()])
  188. def test_keys(self):
  189. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
  190. cache[1] = 2
  191. cache[2] = 3
  192. cache[3] = 4
  193. self.assertEqual([1, 2, 3], sorted(cache.keys()))
  194. cache[4] = 5
  195. cache[5] = 6
  196. cache[6] = 7
  197. self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
  198. def test_resize_smaller(self):
  199. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
  200. cache[1] = 2
  201. cache[2] = 3
  202. cache[3] = 4
  203. cache[4] = 5
  204. cache[5] = 6
  205. self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
  206. cache[6] = 7
  207. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  208. # Now resize to something smaller, which triggers a cleanup
  209. cache.resize(max_cache=3, after_cleanup_count=2)
  210. self.assertEqual([5, 6], sorted(cache.keys()))
  211. # Adding something will use the new size
  212. cache[7] = 8
  213. self.assertEqual([5, 6, 7], sorted(cache.keys()))
  214. cache[8] = 9
  215. self.assertEqual([7, 8], sorted(cache.keys()))
  216. def test_resize_larger(self):
  217. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
  218. cache[1] = 2
  219. cache[2] = 3
  220. cache[3] = 4
  221. cache[4] = 5
  222. cache[5] = 6
  223. self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
  224. cache[6] = 7
  225. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  226. cache.resize(max_cache=8, after_cleanup_count=6)
  227. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  228. cache[7] = 8
  229. cache[8] = 9
  230. cache[9] = 10
  231. cache[10] = 11
  232. self.assertEqual([3, 4, 5, 6, 7, 8, 9, 10], sorted(cache.keys()))
  233. cache[11] = 12 # triggers cleanup back to new after_cleanup_count
  234. self.assertEqual([6, 7, 8, 9, 10, 11], sorted(cache.keys()))
  235. class TestLRUSizeCache(TestCase):
  236. def test_basic_init(self):
  237. cache = lru_cache.LRUSizeCache()
  238. self.assertEqual(2048, cache._max_cache)
  239. self.assertEqual(int(cache._max_size * 0.8), cache._after_cleanup_size)
  240. self.assertEqual(0, cache._value_size)
  241. def test_add__null_key(self):
  242. cache = lru_cache.LRUSizeCache()
  243. self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
  244. def test_add_tracks_size(self):
  245. cache = lru_cache.LRUSizeCache()
  246. self.assertEqual(0, cache._value_size)
  247. cache.add("my key", "my value text")
  248. self.assertEqual(13, cache._value_size)
  249. def test_remove_tracks_size(self):
  250. cache = lru_cache.LRUSizeCache()
  251. self.assertEqual(0, cache._value_size)
  252. cache.add("my key", "my value text")
  253. self.assertEqual(13, cache._value_size)
  254. node = cache._cache["my key"]
  255. cache._remove_node(node)
  256. self.assertEqual(0, cache._value_size)
  257. def test_no_add_over_size(self):
  258. """Adding a large value may not be cached at all."""
  259. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
  260. self.assertEqual(0, cache._value_size)
  261. self.assertEqual({}, cache.items())
  262. cache.add("test", "key")
  263. self.assertEqual(3, cache._value_size)
  264. self.assertEqual({"test": "key"}, cache.items())
  265. cache.add("test2", "key that is too big")
  266. self.assertEqual(3, cache._value_size)
  267. self.assertEqual({"test": "key"}, cache.items())
  268. # If we would add a key, only to cleanup and remove all cached entries,
  269. # then obviously that value should not be stored
  270. cache.add("test3", "bigkey")
  271. self.assertEqual(3, cache._value_size)
  272. self.assertEqual({"test": "key"}, cache.items())
  273. cache.add("test4", "bikey")
  274. self.assertEqual(3, cache._value_size)
  275. self.assertEqual({"test": "key"}, cache.items())
  276. def test_no_add_over_size_cleanup(self):
  277. """If a large value is not cached, we will call cleanup right away."""
  278. cleanup_calls = []
  279. def cleanup(key, value):
  280. cleanup_calls.append((key, value))
  281. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
  282. self.assertEqual(0, cache._value_size)
  283. self.assertEqual({}, cache.items())
  284. cache.add("test", "key that is too big", cleanup=cleanup)
  285. # key was not added
  286. self.assertEqual(0, cache._value_size)
  287. self.assertEqual({}, cache.items())
  288. # and cleanup was called
  289. self.assertEqual([("test", "key that is too big")], cleanup_calls)
  290. def test_adding_clears_cache_based_on_size(self):
  291. """The cache is cleared in LRU order until small enough"""
  292. cache = lru_cache.LRUSizeCache(max_size=20)
  293. cache.add("key1", "value") # 5 chars
  294. cache.add("key2", "value2") # 6 chars
  295. cache.add("key3", "value23") # 7 chars
  296. self.assertEqual(5 + 6 + 7, cache._value_size)
  297. cache["key2"] # reference key2 so it gets a newer reference time
  298. cache.add("key4", "value234") # 8 chars, over limit
  299. # We have to remove 2 keys to get back under limit
  300. self.assertEqual(6 + 8, cache._value_size)
  301. self.assertEqual({"key2": "value2", "key4": "value234"}, cache.items())
  302. def test_adding_clears_to_after_cleanup_size(self):
  303. cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
  304. cache.add("key1", "value") # 5 chars
  305. cache.add("key2", "value2") # 6 chars
  306. cache.add("key3", "value23") # 7 chars
  307. self.assertEqual(5 + 6 + 7, cache._value_size)
  308. cache["key2"] # reference key2 so it gets a newer reference time
  309. cache.add("key4", "value234") # 8 chars, over limit
  310. # We have to remove 3 keys to get back under limit
  311. self.assertEqual(8, cache._value_size)
  312. self.assertEqual({"key4": "value234"}, cache.items())
  313. def test_custom_sizes(self):
  314. def size_of_list(lst):
  315. return sum(len(x) for x in lst)
  316. cache = lru_cache.LRUSizeCache(
  317. max_size=20, after_cleanup_size=10, compute_size=size_of_list
  318. )
  319. cache.add("key1", ["val", "ue"]) # 5 chars
  320. cache.add("key2", ["val", "ue2"]) # 6 chars
  321. cache.add("key3", ["val", "ue23"]) # 7 chars
  322. self.assertEqual(5 + 6 + 7, cache._value_size)
  323. cache["key2"] # reference key2 so it gets a newer reference time
  324. cache.add("key4", ["value", "234"]) # 8 chars, over limit
  325. # We have to remove 3 keys to get back under limit
  326. self.assertEqual(8, cache._value_size)
  327. self.assertEqual({"key4": ["value", "234"]}, cache.items())
  328. def test_cleanup(self):
  329. cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
  330. # Add these in order
  331. cache.add("key1", "value") # 5 chars
  332. cache.add("key2", "value2") # 6 chars
  333. cache.add("key3", "value23") # 7 chars
  334. self.assertEqual(5 + 6 + 7, cache._value_size)
  335. cache.cleanup()
  336. # Only the most recent fits after cleaning up
  337. self.assertEqual(7, cache._value_size)
  338. def test_keys(self):
  339. cache = lru_cache.LRUSizeCache(max_size=10)
  340. cache[1] = "a"
  341. cache[2] = "b"
  342. cache[3] = "cdef"
  343. self.assertEqual([1, 2, 3], sorted(cache.keys()))
  344. def test_resize_smaller(self):
  345. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
  346. cache[1] = "abc"
  347. cache[2] = "def"
  348. cache[3] = "ghi"
  349. cache[4] = "jkl"
  350. # Triggers a cleanup
  351. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  352. # Resize should also cleanup again
  353. cache.resize(max_size=6, after_cleanup_size=4)
  354. self.assertEqual([4], sorted(cache.keys()))
  355. # Adding should use the new max size
  356. cache[5] = "mno"
  357. self.assertEqual([4, 5], sorted(cache.keys()))
  358. cache[6] = "pqr"
  359. self.assertEqual([6], sorted(cache.keys()))
  360. def test_resize_larger(self):
  361. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
  362. cache[1] = "abc"
  363. cache[2] = "def"
  364. cache[3] = "ghi"
  365. cache[4] = "jkl"
  366. # Triggers a cleanup
  367. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  368. cache.resize(max_size=15, after_cleanup_size=12)
  369. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  370. cache[5] = "mno"
  371. cache[6] = "pqr"
  372. self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
  373. cache[7] = "stu"
  374. self.assertEqual([4, 5, 6, 7], sorted(cache.keys()))