Skip to content

Commit

Permalink
fix: factor out mongodb close logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jvansanten committed Nov 28, 2024
1 parent 1d33fae commit 8b2ddb9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
18 changes: 10 additions & 8 deletions ampel/core/AmpelDB.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,15 @@ def __init__(self, **kwargs) -> None:
):
raise UnknownDatabase(f"Database(s) with prefix {self.prefix} do not exist")

def close(self) -> None:
for mc in self.mongo_clients.values():
mc.close()
self.mongo_collections.clear()
self.mongo_clients.clear()
# deleting the attribute resets cached_property
for attr in ("col_trace_ids", "col_conf_ids", "trace_ids", "conf_ids"):
with suppress(AttributeError):
delattr(self, attr)

@cached_property
def col_trace_ids(self) -> Collection:
Expand Down Expand Up @@ -466,14 +475,7 @@ def drop_all_databases(self) -> None:
for db in self.databases:
pym_db = self._get_pymongo_db(db.name, role=db.role.w)
pym_db.client.drop_database(pym_db.name)
self.mongo_collections.clear()
for mc in self.mongo_clients.values():
mc.close()
self.mongo_clients.clear()
# deleting the attribute resets cached_property
for attr in ("col_trace_ids", "col_conf_ids", "trace_ids", "conf_ids"):
with suppress(AttributeError):
delattr(self, attr)
self.close()


def add_trace_id(self, trace_id: int, arg: dict[str, Any]) -> None:
Expand Down
7 changes: 5 additions & 2 deletions ampel/test/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def mongod(pytestconfig):
"NetworkSettings"
]["Ports"]["27017/tcp"][0]["HostPort"]
# wait for startup
list(pymongo.MongoClient(port=int(port)).list_databases())
with pymongo.MongoClient(port=int(port)) as client:
list(client.list_databases())
yield f"mongodb://localhost:{port}"
finally:
...
Expand Down Expand Up @@ -100,11 +101,13 @@ def mock_context(_patch_mongo, testing_config: PosixPath):

@pytest.fixture
def integration_context(mongod, testing_config: PosixPath):
return DevAmpelContext.load(
ctx = DevAmpelContext.load(
config=str(testing_config),
purge_db=True,
custom_conf={"resource.mongo": mongod},
)
yield ctx
ctx.db.close()


# metafixture as suggested in https://github.com/pytest-dev/pytest/issues/349#issuecomment-189370273
Expand Down

0 comments on commit 8b2ddb9

Please sign in to comment.