From 2eebc9cdc234544feb000877dc78714bda8d5871 Mon Sep 17 00:00:00 2001 From: 0x1026 <69076992+0x1026@users.noreply.github.com> Date: Wed, 4 Dec 2024 03:54:55 +0100 Subject: [PATCH] test(api): add unit tests for Settings validation and password handling --- api/src/config.py | 11 +++++----- api/tests/test_config.py | 47 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 api/tests/test_config.py diff --git a/api/src/config.py b/api/src/config.py index 9157cc7c..4800edbc 100644 --- a/api/src/config.py +++ b/api/src/config.py @@ -1,7 +1,5 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict import os - -from typing import Any - from pydantic import ( MariaDBDsn, computed_field, @@ -9,8 +7,7 @@ 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'): @@ -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() diff --git a/api/tests/test_config.py b/api/tests/test_config.py new file mode 100644 index 00000000..b25156e8 --- /dev/null +++ b/api/tests/test_config.py @@ -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" + )