From 262dced25022c82b202c37f9ab36073aac8533c2 Mon Sep 17 00:00:00 2001 From: Sha Date: Thu, 13 Mar 2025 15:24:01 +0800 Subject: [PATCH] use mongodb auto expire index --- src/cachelib/mongodb.py | 2 ++ tests/test_mongodb_cache.py | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/cachelib/mongodb.py b/src/cachelib/mongodb.py index ac186423..e277fcc0 100644 --- a/src/cachelib/mongodb.py +++ b/src/cachelib/mongodb.py @@ -48,6 +48,8 @@ def __init__( } if "id" not in all_keys: self.client.create_index("id", unique=True) + if "expiration" not in all_keys: + self.client.create_index("expiration", expireAfterSeconds=0) self.key_prefix = key_prefix or "" self.collection = collection diff --git a/tests/test_mongodb_cache.py b/tests/test_mongodb_cache.py index 54aa32c9..bba453a3 100644 --- a/tests/test_mongodb_cache.py +++ b/tests/test_mongodb_cache.py @@ -1,3 +1,5 @@ +import time + import pytest from clear import ClearTests from common import CommonTests @@ -27,4 +29,17 @@ def _factory(self, *args, **kwargs): class TestMongoDbCache(CommonTests, ClearTests, HasTests): - pass + def test_auto_expire(self): + """Test that MongoDB's TTL index automatically expires cache entries.""" + cache = self.cache_factory() + # Set a cache entry with a short timeout + cache.set("auto_expire_key", "value", timeout=2) + + # Verify it exists + assert cache.get("auto_expire_key") == "value" + + # Wait for expiration (add buffer time for MongoDB TTL monitor) + time.sleep(5) + + # Verify it has expired + assert cache.get("auto_expire_key") is None