test_lru_cache.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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.assertFalse('foo' in cache)
  38. self.assertRaises(KeyError, cache.__getitem__, 'foo')
  39. cache['foo'] = 'bar'
  40. self.assertEqual('bar', cache['foo'])
  41. self.assertTrue('foo' in cache)
  42. self.assertFalse('bar' in 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.assertFalse(None in 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.assertFalse('foo' in cache)
  69. self.assertTrue('baz' in 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.assertFalse('foo' in 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')],
  94. cleanup_called)
  95. def test_cleanup_on_replace(self):
  96. """Replacing an object should cleanup the old value."""
  97. cleanup_called = []
  98. def cleanup_func(key, val):
  99. cleanup_called.append((key, val))
  100. cache = lru_cache.LRUCache(max_cache=2)
  101. cache.add(1, 10, cleanup=cleanup_func)
  102. cache.add(2, 20, cleanup=cleanup_func)
  103. cache.add(2, 25, cleanup=cleanup_func)
  104. self.assertEqual([(2, 20)], cleanup_called)
  105. self.assertEqual(25, cache[2])
  106. # Even __setitem__ should make sure cleanup() is called
  107. cache[2] = 26
  108. self.assertEqual([(2, 20), (2, 25)], cleanup_called)
  109. def test_len(self):
  110. cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
  111. cache[1] = 10
  112. cache[2] = 20
  113. cache[3] = 30
  114. cache[4] = 40
  115. self.assertEqual(4, len(cache))
  116. cache[5] = 50
  117. cache[6] = 60
  118. cache[7] = 70
  119. cache[8] = 80
  120. self.assertEqual(8, len(cache))
  121. cache[1] = 15 # replacement
  122. self.assertEqual(8, len(cache))
  123. cache[9] = 90
  124. cache[10] = 100
  125. cache[11] = 110
  126. # We hit the max
  127. self.assertEqual(10, len(cache))
  128. self.assertEqual([11, 10, 9, 1, 8, 7, 6, 5, 4, 3],
  129. [n.key for n in cache._walk_lru()])
  130. def test_cleanup_shrinks_to_after_clean_count(self):
  131. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3)
  132. cache.add(1, 10)
  133. cache.add(2, 20)
  134. cache.add(3, 25)
  135. cache.add(4, 30)
  136. cache.add(5, 35)
  137. self.assertEqual(5, len(cache))
  138. # This will bump us over the max, which causes us to shrink down to
  139. # after_cleanup_cache size
  140. cache.add(6, 40)
  141. self.assertEqual(3, len(cache))
  142. def test_after_cleanup_larger_than_max(self):
  143. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10)
  144. self.assertEqual(5, cache._after_cleanup_count)
  145. def test_after_cleanup_none(self):
  146. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=None)
  147. # By default _after_cleanup_size is 80% of the normal size
  148. self.assertEqual(4, cache._after_cleanup_count)
  149. def test_cleanup_2(self):
  150. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
  151. # Add these in order
  152. cache.add(1, 10)
  153. cache.add(2, 20)
  154. cache.add(3, 25)
  155. cache.add(4, 30)
  156. cache.add(5, 35)
  157. self.assertEqual(5, len(cache))
  158. # Force a compaction
  159. cache.cleanup()
  160. self.assertEqual(2, len(cache))
  161. def test_preserve_last_access_order(self):
  162. cache = lru_cache.LRUCache(max_cache=5)
  163. # Add these in order
  164. cache.add(1, 10)
  165. cache.add(2, 20)
  166. cache.add(3, 25)
  167. cache.add(4, 30)
  168. cache.add(5, 35)
  169. self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()])
  170. # Now access some randomly
  171. cache[2]
  172. cache[5]
  173. cache[3]
  174. cache[2]
  175. self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()])
  176. def test_get(self):
  177. cache = lru_cache.LRUCache(max_cache=5)
  178. cache.add(1, 10)
  179. cache.add(2, 20)
  180. self.assertEqual(20, cache.get(2))
  181. self.assertEqual(None, cache.get(3))
  182. obj = object()
  183. self.assertTrue(obj is cache.get(3, obj))
  184. self.assertEqual([2, 1], [n.key for n in cache._walk_lru()])
  185. self.assertEqual(10, cache.get(1))
  186. self.assertEqual([1, 2], [n.key for n in cache._walk_lru()])
  187. def test_keys(self):
  188. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
  189. cache[1] = 2
  190. cache[2] = 3
  191. cache[3] = 4
  192. self.assertEqual([1, 2, 3], sorted(cache.keys()))
  193. cache[4] = 5
  194. cache[5] = 6
  195. cache[6] = 7
  196. self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
  197. def test_resize_smaller(self):
  198. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
  199. cache[1] = 2
  200. cache[2] = 3
  201. cache[3] = 4
  202. cache[4] = 5
  203. cache[5] = 6
  204. self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
  205. cache[6] = 7
  206. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  207. # Now resize to something smaller, which triggers a cleanup
  208. cache.resize(max_cache=3, after_cleanup_count=2)
  209. self.assertEqual([5, 6], sorted(cache.keys()))
  210. # Adding something will use the new size
  211. cache[7] = 8
  212. self.assertEqual([5, 6, 7], sorted(cache.keys()))
  213. cache[8] = 9
  214. self.assertEqual([7, 8], sorted(cache.keys()))
  215. def test_resize_larger(self):
  216. cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
  217. cache[1] = 2
  218. cache[2] = 3
  219. cache[3] = 4
  220. cache[4] = 5
  221. cache[5] = 6
  222. self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
  223. cache[6] = 7
  224. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  225. cache.resize(max_cache=8, after_cleanup_count=6)
  226. self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
  227. cache[7] = 8
  228. cache[8] = 9
  229. cache[9] = 10
  230. cache[10] = 11
  231. self.assertEqual([3, 4, 5, 6, 7, 8, 9, 10], sorted(cache.keys()))
  232. cache[11] = 12 # triggers cleanup back to new after_cleanup_count
  233. self.assertEqual([6, 7, 8, 9, 10, 11], sorted(cache.keys()))
  234. class TestLRUSizeCache(TestCase):
  235. def test_basic_init(self):
  236. cache = lru_cache.LRUSizeCache()
  237. self.assertEqual(2048, cache._max_cache)
  238. self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size)
  239. self.assertEqual(0, cache._value_size)
  240. def test_add__null_key(self):
  241. cache = lru_cache.LRUSizeCache()
  242. self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
  243. def test_add_tracks_size(self):
  244. cache = lru_cache.LRUSizeCache()
  245. self.assertEqual(0, cache._value_size)
  246. cache.add('my key', 'my value text')
  247. self.assertEqual(13, cache._value_size)
  248. def test_remove_tracks_size(self):
  249. cache = lru_cache.LRUSizeCache()
  250. self.assertEqual(0, cache._value_size)
  251. cache.add('my key', 'my value text')
  252. self.assertEqual(13, cache._value_size)
  253. node = cache._cache['my key']
  254. cache._remove_node(node)
  255. self.assertEqual(0, cache._value_size)
  256. def test_no_add_over_size(self):
  257. """Adding a large value may not be cached at all."""
  258. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
  259. self.assertEqual(0, cache._value_size)
  260. self.assertEqual({}, cache.items())
  261. cache.add('test', 'key')
  262. self.assertEqual(3, cache._value_size)
  263. self.assertEqual({'test': 'key'}, cache.items())
  264. cache.add('test2', 'key that is too big')
  265. self.assertEqual(3, cache._value_size)
  266. self.assertEqual({'test': 'key'}, cache.items())
  267. # If we would add a key, only to cleanup and remove all cached entries,
  268. # then obviously that value should not be stored
  269. cache.add('test3', 'bigkey')
  270. self.assertEqual(3, cache._value_size)
  271. self.assertEqual({'test': 'key'}, cache.items())
  272. cache.add('test4', 'bikey')
  273. self.assertEqual(3, cache._value_size)
  274. self.assertEqual({'test': 'key'}, cache.items())
  275. def test_no_add_over_size_cleanup(self):
  276. """If a large value is not cached, we will call cleanup right away."""
  277. cleanup_calls = []
  278. def cleanup(key, value):
  279. cleanup_calls.append((key, value))
  280. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
  281. self.assertEqual(0, cache._value_size)
  282. self.assertEqual({}, cache.items())
  283. cache.add('test', 'key that is too big', cleanup=cleanup)
  284. # key was not added
  285. self.assertEqual(0, cache._value_size)
  286. self.assertEqual({}, cache.items())
  287. # and cleanup was called
  288. self.assertEqual([('test', 'key that is too big')], cleanup_calls)
  289. def test_adding_clears_cache_based_on_size(self):
  290. """The cache is cleared in LRU order until small enough"""
  291. cache = lru_cache.LRUSizeCache(max_size=20)
  292. cache.add('key1', 'value') # 5 chars
  293. cache.add('key2', 'value2') # 6 chars
  294. cache.add('key3', 'value23') # 7 chars
  295. self.assertEqual(5+6+7, cache._value_size)
  296. cache['key2'] # reference key2 so it gets a newer reference time
  297. cache.add('key4', 'value234') # 8 chars, over limit
  298. # We have to remove 2 keys to get back under limit
  299. self.assertEqual(6+8, cache._value_size)
  300. self.assertEqual({'key2': 'value2', 'key4': 'value234'},
  301. 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(max_size=20, after_cleanup_size=10,
  317. compute_size=size_of_list)
  318. cache.add('key1', ['val', 'ue']) # 5 chars
  319. cache.add('key2', ['val', 'ue2']) # 6 chars
  320. cache.add('key3', ['val', 'ue23']) # 7 chars
  321. self.assertEqual(5+6+7, cache._value_size)
  322. cache['key2'] # reference key2 so it gets a newer reference time
  323. cache.add('key4', ['value', '234']) # 8 chars, over limit
  324. # We have to remove 3 keys to get back under limit
  325. self.assertEqual(8, cache._value_size)
  326. self.assertEqual({'key4': ['value', '234']}, cache.items())
  327. def test_cleanup(self):
  328. cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
  329. # Add these in order
  330. cache.add('key1', 'value') # 5 chars
  331. cache.add('key2', 'value2') # 6 chars
  332. cache.add('key3', 'value23') # 7 chars
  333. self.assertEqual(5+6+7, cache._value_size)
  334. cache.cleanup()
  335. # Only the most recent fits after cleaning up
  336. self.assertEqual(7, cache._value_size)
  337. def test_keys(self):
  338. cache = lru_cache.LRUSizeCache(max_size=10)
  339. cache[1] = 'a'
  340. cache[2] = 'b'
  341. cache[3] = 'cdef'
  342. self.assertEqual([1, 2, 3], sorted(cache.keys()))
  343. def test_resize_smaller(self):
  344. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
  345. cache[1] = 'abc'
  346. cache[2] = 'def'
  347. cache[3] = 'ghi'
  348. cache[4] = 'jkl'
  349. # Triggers a cleanup
  350. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  351. # Resize should also cleanup again
  352. cache.resize(max_size=6, after_cleanup_size=4)
  353. self.assertEqual([4], sorted(cache.keys()))
  354. # Adding should use the new max size
  355. cache[5] = 'mno'
  356. self.assertEqual([4, 5], sorted(cache.keys()))
  357. cache[6] = 'pqr'
  358. self.assertEqual([6], sorted(cache.keys()))
  359. def test_resize_larger(self):
  360. cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
  361. cache[1] = 'abc'
  362. cache[2] = 'def'
  363. cache[3] = 'ghi'
  364. cache[4] = 'jkl'
  365. # Triggers a cleanup
  366. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  367. cache.resize(max_size=15, after_cleanup_size=12)
  368. self.assertEqual([2, 3, 4], sorted(cache.keys()))
  369. cache[5] = 'mno'
  370. cache[6] = 'pqr'
  371. self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
  372. cache[7] = 'stu'
  373. self.assertEqual([4, 5, 6, 7], sorted(cache.keys()))