Skip to content

Commit ce3b2ac

Browse files
authored
Merge pull request #113 from adityashirsatrao007/feature/112
feat: add config file with Settings class for database credentials
2 parents 65db919 + 48a2d3e commit ce3b2ac

4 files changed

Lines changed: 58 additions & 2 deletions

File tree

src/vetlog_buddy/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# (File deleted)

src/vetlog_buddy/shared/config.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,17 @@ class Config:
2828
env_file_encoding = "utf-8"
2929

3030

31-
settings = Settings()
31+
from functools import lru_cache
32+
33+
34+
@lru_cache
35+
def get_settings():
36+
"""
37+
Returns a cached instance of the Settings class.
38+
"""
39+
"""
40+
Returns a cached instance of Settings using lru_cache.
41+
This ensures that environment variables are read only once and
42+
repeated calls return the same Settings object.
43+
"""
44+
return Settings()

src/vetlog_buddy/shared/database.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
from urllib.parse import quote_plus
1515
from sqlmodel import Session, create_engine
1616

17-
from vetlog_buddy.shared.config import settings
17+
from vetlog_buddy.shared.config import get_settings
18+
19+
settings = get_settings()
1820

1921
database_url: str = f"mysql+mysqlconnector://{quote_plus(settings.db_user)}:{quote_plus(settings.db_password)}@{settings.db_host}/{settings.db_name}"
2022
engine = create_engine(database_url, echo=False, pool_pre_ping=True)

tests/unit/test_config.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import os
2+
from unittest.mock import patch
3+
4+
import pytest
5+
from pydantic import ValidationError
6+
7+
from vetlog_buddy.shared.config import Settings
8+
9+
10+
@pytest.fixture
11+
def mock_env_vars():
12+
with patch.dict(
13+
os.environ,
14+
{
15+
"DB_HOST": "localhost",
16+
"DB_NAME": "vetlog",
17+
"DB_USER": "vetlogUser",
18+
"DB_PASSWORD": "vetlogDB",
19+
},
20+
):
21+
yield
22+
23+
24+
def test_settings_loads_from_env(mock_env_vars):
25+
settings = Settings()
26+
assert settings.db_host == "localhost"
27+
assert settings.db_name == "vetlog"
28+
assert settings.db_user == "vetlogUser"
29+
assert settings.db_password == "vetlogDB"
30+
31+
32+
@pytest.fixture
33+
def clean_env():
34+
with patch.dict(os.environ, {}, clear=True):
35+
yield
36+
37+
38+
def test_settings_missing_required_vars(clean_env):
39+
with pytest.raises(ValidationError):
40+
Settings()

0 commit comments

Comments
 (0)