From 8bf41a8b315bee8c5f12c2c91f18b2322c209080 Mon Sep 17 00:00:00 2001 From: sha Date: Wed, 31 May 2023 22:16:46 +0800 Subject: [PATCH] test mongodb cache index --- src/cachelib/mongodb.py | 7 ++++++- tests/test_mongodb_cache.py | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/cachelib/mongodb.py b/src/cachelib/mongodb.py index 684a57bd..ac186423 100644 --- a/src/cachelib/mongodb.py +++ b/src/cachelib/mongodb.py @@ -41,8 +41,13 @@ def __init__( if client is None or isinstance(client, str): client = pymongo.MongoClient(host=client) - client.ensure_index([("id", pymongo.ASCENDING)]) self.client = client[db][collection] + index_info = self.client.index_information() + all_keys = { + subkey[0] for value in index_info.values() for subkey in value["key"] + } + if "id" not in all_keys: + self.client.create_index("id", unique=True) self.key_prefix = key_prefix or "" self.collection = collection diff --git a/tests/test_mongodb_cache.py b/tests/test_mongodb_cache.py index e53ba448..54aa32c9 100644 --- a/tests/test_mongodb_cache.py +++ b/tests/test_mongodb_cache.py @@ -14,6 +14,11 @@ def _factory(self, *args, **kwargs): kwargs["key_prefix"] = "prefix" rc = request.param(*args, **kwargs) + index_info = rc.client.index_information() + all_keys = { + subkey[0] for value in index_info.values() for subkey in value["key"] + } + assert "id" in all_keys, "Failed to create index on 'id' field" rc.clear() return rc