@@ -107,14 +107,46 @@ def _get_cachier_db_mongo_client():
107107)
108108
109109
110+ # Global registry to track all MongoDB clients created during tests
111+ _mongo_clients = []
112+
113+
114+ def cleanup_all_mongo_clients ():
115+ """Clean up all MongoDB clients to prevent ResourceWarning."""
116+ import contextlib
117+ import sys
118+
119+ global _mongo_clients
120+
121+ # Close all tracked clients
122+ for client in _mongo_clients :
123+ with contextlib .suppress (Exception ):
124+ client .close ()
125+
126+ # Clear the list
127+ _mongo_clients .clear ()
128+
129+ # Clean up any mongetter functions with clients
130+ current_module = sys .modules [__name__ ]
131+ for attr_name in dir (current_module ):
132+ attr = getattr (current_module , attr_name )
133+ if callable (attr ) and hasattr (attr , "client" ):
134+ with contextlib .suppress (Exception ):
135+ if hasattr (attr .client , "close" ):
136+ attr .client .close ()
137+ delattr (attr , "client" )
138+
139+
110140def _test_mongetter ():
111141 if not hasattr (_test_mongetter , "client" ):
112142 if str (CFG .mget (CfgKey .TEST_VS_DOCKERIZED_MONGO )).lower () == "true" :
113143 print ("Using live MongoDB instance for testing." )
114144 _test_mongetter .client = _get_cachier_db_mongo_client ()
145+ _mongo_clients .append (_test_mongetter .client )
115146 else :
116147 print ("Using in-memory MongoDB instance for testing." )
117148 _test_mongetter .client = InMemoryMongoClient ()
149+ _mongo_clients .append (_test_mongetter .client )
118150 db_obj = _test_mongetter .client ["cachier_test" ]
119151 if _COLLECTION_NAME not in db_obj .list_collection_names ():
120152 db_obj .create_collection (_COLLECTION_NAME )
@@ -137,17 +169,29 @@ def _custom_mongetter():
137169 ):
138170 print ("Using live MongoDB instance for testing." )
139171 _custom_mongetter .client = _get_cachier_db_mongo_client ()
172+ _mongo_clients .append (_custom_mongetter .client )
140173 else :
141174 print ("Using in-memory MongoDB instance for testing." )
142175 _custom_mongetter .client = InMemoryMongoClient ()
176+ _mongo_clients .append (_custom_mongetter .client )
143177 db_obj = _custom_mongetter .client ["cachier_test" ]
144178 if _COLLECTION_NAME not in db_obj .list_collection_names ():
145179 db_obj .create_collection (collection_name )
146180 return db_obj [collection_name ]
147181
182+ # Store the mongetter function for cleanup
183+ _custom_mongetter ._collection_name = collection_name
148184 return _custom_mongetter
149185
150186
187+ @pytest .fixture (autouse = True )
188+ def mongo_cleanup ():
189+ """Ensure MongoDB clients are cleaned up after each test."""
190+ yield
191+ # Clean up after test
192+ cleanup_all_mongo_clients ()
193+
194+
151195# === Mongo core tests ===
152196
153197
0 commit comments