Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add settings module #1044

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
Ensure sessions are cleaned up when using settings
  • Loading branch information
soapy1 committed Jan 9, 2025
commit 972a3d8ac8c640b2e780172fbd184ba13765b12c
13 changes: 12 additions & 1 deletion conda-store-server/conda_store_server/_internal/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

from typing import Any, Dict
from typing import Any, Dict, Callable
import functools

from sqlalchemy.orm import Session
import pydantic
Expand All @@ -16,6 +17,15 @@ def __init__(self, db: Session, deployment_default: schema.Settings):
self.db = db
self.deployment_default = deployment_default.model_dump()

def _ensure_closed_session(func: Callable):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
self.db.close()
return result
return wrapper

@_ensure_closed_session
def set_settings(
self,
namespace: str = None,
Expand Down Expand Up @@ -65,6 +75,7 @@ def set_settings(

api.set_kvstore_key_values(self.db, prefix, data)

@_ensure_closed_session
def get_settings(
self, namespace: str = None, environment_name: str = None
) -> schema.Settings:
Expand Down
23 changes: 23 additions & 0 deletions conda-store-server/tests/_internal/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

from unittest import mock

import pytest

from conda_store_server import api
Expand Down Expand Up @@ -51,6 +53,27 @@ def settings(db) -> Settings:
)


def test_ensure_session_is_closed(settings: Settings):
# run a query against the db to start a transaction
settings.get_settings()
# ensure that the settings object cleans up it's transaction
assert settings.db.in_transaction() == False


@mock.patch("conda_store_server.api.get_kvstore_key_values")
def test_ensure_session_is_closed_on_error(mock_get_kvstore_key_values, settings: Settings):
mock_get_kvstore_key_values.side_effect = Exception

# run a query that will raise an exception
try:
settings.get_settings()
except:
pass

# ensure that the settings object cleans up it's transaction
assert settings.db.in_transaction() == False


def test_get_settings_default(settings: Settings):
test_settings = settings.get_settings()

Expand Down