test_lru_cache.py 16 KB

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