|
15 | 15 |
|
16 | 16 | from unittest.mock import Mock
|
17 | 17 |
|
18 |
| -from synapse.util.caches.lrucache import LruCache |
| 18 | +from synapse.util.caches.lrucache import LruCache, setup_expire_lru_cache_entries |
19 | 19 | from synapse.util.caches.treecache import TreeCache
|
20 | 20 |
|
21 | 21 | from tests import unittest
|
@@ -260,3 +260,47 @@ def test_evict(self):
|
260 | 260 | self.assertEquals(cache["key3"], [3])
|
261 | 261 | self.assertEquals(cache["key4"], [4])
|
262 | 262 | self.assertEquals(cache["key5"], [5, 6])
|
| 263 | + |
| 264 | + |
| 265 | +class TimeEvictionTestCase(unittest.HomeserverTestCase): |
| 266 | + """Test that time based eviction works correctly.""" |
| 267 | + |
| 268 | + def default_config(self): |
| 269 | + config = super().default_config() |
| 270 | + |
| 271 | + config.setdefault("caches", {})["expiry_time"] = "30m" |
| 272 | + |
| 273 | + return config |
| 274 | + |
| 275 | + def test_evict(self): |
| 276 | + setup_expire_lru_cache_entries(self.hs) |
| 277 | + |
| 278 | + cache = LruCache(5, clock=self.hs.get_clock()) |
| 279 | + |
| 280 | + # Check that we evict entries we haven't accessed for 30 minutes. |
| 281 | + cache["key1"] = 1 |
| 282 | + cache["key2"] = 2 |
| 283 | + |
| 284 | + self.reactor.advance(20 * 60) |
| 285 | + |
| 286 | + self.assertEqual(cache.get("key1"), 1) |
| 287 | + |
| 288 | + self.reactor.advance(20 * 60) |
| 289 | + |
| 290 | + # We have only touched `key1` in the last 30m, so we expect that to |
| 291 | + # still be in the cache while `key2` should have been evicted. |
| 292 | + self.assertEqual(cache.get("key1"), 1) |
| 293 | + self.assertEqual(cache.get("key2"), None) |
| 294 | + |
| 295 | + # Check that re-adding an expired key works correctly. |
| 296 | + cache["key2"] = 3 |
| 297 | + self.assertEqual(cache.get("key2"), 3) |
| 298 | + |
| 299 | + self.reactor.advance(20 * 60) |
| 300 | + |
| 301 | + self.assertEqual(cache.get("key2"), 3) |
| 302 | + |
| 303 | + self.reactor.advance(20 * 60) |
| 304 | + |
| 305 | + self.assertEqual(cache.get("key1"), None) |
| 306 | + self.assertEqual(cache.get("key2"), 3) |
0 commit comments