Skip to content

Commit

Permalink
test(api): add unit tests for Settings validation and password handling
Browse files Browse the repository at this point in the history
  • Loading branch information
0x1026 committed Dec 4, 2024
1 parent c159683 commit 2eebc9c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
11 changes: 5 additions & 6 deletions api/src/config.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
from pydantic_settings import BaseSettings, SettingsConfigDict
import os

from typing import Any

from pydantic import (
MariaDBDsn,
computed_field,
field_validator,
model_validator,
)
from pydantic_core import MultiHostUrl
from pydantic_settings import BaseSettings, SettingsConfigDict

from typing import Any

class Settings(BaseSettings):
if os.path.exists('/run/secrets'):
Expand Down Expand Up @@ -58,4 +55,6 @@ def SQLALCHEMY_DATABASE_URI(self) -> MariaDBDsn:
path=self.MARIADB_DB,
)

settings = Settings()
# instantiate the settings object if i'm not testing (APP_ENV is set to test)
if os.environ.get("APP_ENV") != "test":
settings = Settings()
47 changes: 47 additions & 0 deletions api/tests/test_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import pytest
from pydantic import ValidationError
from src.config import Settings

def test_settings_with_password():
settings = Settings(
MARIADB_SERVER="localhost",
MARIADB_USER="user",
MARIADB_PASSWORD="password",
MARIADB_DB="test_db",
SENTRY_DSN="http://example.com"
)
assert settings.MARIADB_PASSWORD == "password"
assert str(settings.SQLALCHEMY_DATABASE_URI) == "mysql+pymysql://user:password@localhost:3306/test_db"

def test_settings_with_password_file(tmp_path):
password_file = tmp_path / "password.txt"
password_file.write_text("file_password")

settings = Settings(
MARIADB_SERVER="localhost",
MARIADB_USER="user",
MARIADB_PASSWORD_FILE=str(password_file),
MARIADB_DB="test_db",
SENTRY_DSN="http://example.com"
)
assert settings.MARIADB_PASSWORD_FILE == "file_password"
assert str(settings.SQLALCHEMY_DATABASE_URI) == "mysql+pymysql://user:file_password@localhost:3306/test_db"

def test_settings_missing_password():
with pytest.raises(ValidationError):
Settings(
MARIADB_SERVER="localhost",
MARIADB_USER="user",
MARIADB_DB="test_db",
SENTRY_DSN="http://example.com"
)

def test_password_file_does_not_exist():
with pytest.raises(ValueError, match="Password file /non/existent/path does not exist."):
Settings(
MARIADB_SERVER="localhost",
MARIADB_USER="user",
MARIADB_PASSWORD_FILE="/non/existent/path",
MARIADB_DB="test_db",
SENTRY_DSN="http://example.com"
)

0 comments on commit 2eebc9c

Please sign in to comment.