diff --git a/src/cachelib/mongodb.py b/src/cachelib/mongodb.py index a7b19f7..d56bf20 100644 --- a/src/cachelib/mongodb.py +++ b/src/cachelib/mongodb.py @@ -49,7 +49,7 @@ 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") + 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 20ce063..85afd95 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 @@ -28,4 +30,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