Skip to content

Commit 41e3c29

Browse files
committed
fix tests for real mongodb
1 parent 3bc5a0c commit 41e3c29

File tree

3 files changed

+42
-19
lines changed

3 files changed

+42
-19
lines changed

optimade/server/create_app.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,11 @@ def insert_index_data(
137137
from optimade.server.routers.utils import get_providers, mongo_id_for_database
138138

139139
links_coll = entry_collections["links"]
140+
141+
if links_coll.collection.estimated_document_count() > 0:
142+
LOGGER.info("Skipping index links insert: links collection already populated.")
143+
return
144+
140145
LOGGER.debug("Loading index links...")
141146
with open(config.index_links_path) as f:
142147
data = json.load(f)

optimade/server/entry_collections/mongo.py

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import atexit
12
from typing import Any
23

34
from pymongo.errors import ExecutionTimeout
@@ -10,27 +11,49 @@
1011
from optimade.server.mappers import BaseResourceMapper
1112
from optimade.server.query_params import EntryListingQueryParams, SingleEntryQueryParams
1213

14+
_CLIENTS: dict[tuple[str, str], Any] = {}
15+
16+
17+
def _close_all_clients(log: bool = True):
18+
for (backend, uri), client in list(_CLIENTS.items()):
19+
try:
20+
client.close()
21+
if log:
22+
LOGGER.debug(f"Closed MongoClient for {backend} {uri}")
23+
except Exception as exc:
24+
if log:
25+
LOGGER.warning(f"Failed closing MongoClient {backend} {uri}: {exc}")
26+
finally:
27+
_CLIENTS.pop((backend, uri), None)
28+
29+
30+
atexit.register(lambda: _close_all_clients(log=False))
31+
1332

1433
def get_mongo_client(config: ServerConfig):
15-
if config.database_backend.value == "mongodb":
16-
from pymongo import MongoClient, version_tuple
34+
"""Return a cached MongoClient for (backend, uri), creating it if necessary."""
35+
backend = config.database_backend.value
36+
uri = config.mongo_uri
37+
key = (backend, uri)
1738

18-
if version_tuple[0] < 4:
19-
LOGGER.warning(
20-
"Support for pymongo<=3 (and thus MongoDB v3) is deprecated and will be "
21-
"removed in the next minor release."
22-
)
39+
if key in _CLIENTS:
40+
return _CLIENTS[key]
2341

24-
LOGGER.info("Using: Real MongoDB (pymongo)")
42+
if backend == "mongodb":
43+
from pymongo import MongoClient
2544

26-
elif config.database_backend.value == "mongomock":
45+
LOGGER.info(f"Using: Real MongoDB (pymongo) @ {uri}")
46+
client = MongoClient(uri)
47+
elif backend == "mongomock":
2748
from mongomock import MongoClient
2849

29-
LOGGER.info("Using: Mock MongoDB (mongomock)")
50+
LOGGER.info(f"Using: Mock MongoDB (mongomock) @ {uri}")
51+
client = MongoClient(uri)
52+
else:
53+
raise ValueError(f"Unsupported backend {backend}")
3054

31-
if config.database_backend.value in ("mongomock", "mongodb"):
32-
CLIENT = MongoClient(config.mongo_uri)
33-
return CLIENT
55+
_CLIENTS[key] = client
56+
return client
3457

3558

3659
class MongoCollection(EntryCollection):

tests/server/entry_collections/test_indexes.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,9 @@ def test_indexes_are_created_where_appropriate(client):
1111
"""
1212
import pymongo.errors
1313

14-
from optimade.server.config import ServerConfig
15-
from optimade.server.create_app import create_app
1614
from optimade.server.query_params import EntryListingQueryParams
1715

18-
# get default config
19-
config = ServerConfig()
20-
# create the app, which also inserts the test data and sets up entry collections
21-
app = create_app(config)
16+
app = client.app
2217

2318
entry_collections = app.state.entry_collections
2419

0 commit comments

Comments
 (0)