a2f357b3d3
Nuova impostazione app_env (env APP_ENV, default "dev"). All'istanza di Settings, se app_env non è "dev"/"test" e SERVER_SECRET_KEY o DB_PASSWORD sono ancora il valore committato, RuntimeError che nomina la variabile. Dev e test continuano a partire senza .env: il default "dev" non fa mai scattare la guardia. Le parti frontend (flask_app/config.py) e deploy (docker-compose.yml) di questa issue sono degli altri lotti (B2, C2). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
51 lines
2.1 KiB
Python
51 lines
2.1 KiB
Python
"""Tests for Settings' production-secret guard (issue #33, backend part)."""
|
|
import pytest
|
|
|
|
from src.backend.config import Settings, _DEFAULT_DB_PASSWORD, _DEFAULT_SECRET_KEY
|
|
|
|
_REAL_SECRET_KEY = "a-real-generated-secret-key-not-the-default"
|
|
_REAL_DB_PASSWORD = "a-real-generated-db-password-not-the-default"
|
|
|
|
|
|
def _settings(**overrides) -> Settings:
|
|
"""Build a Settings instance without reading the real .env file or
|
|
inheriting stray SERVER_SECRET_KEY/DB_PASSWORD from the shell env."""
|
|
overrides.setdefault("server_secret_key", _DEFAULT_SECRET_KEY)
|
|
overrides.setdefault("db_password", _DEFAULT_DB_PASSWORD)
|
|
return Settings(_env_file=None, **overrides)
|
|
|
|
|
|
class TestProductionSecretGuard:
|
|
def test_dev_env_allows_default_secrets(self):
|
|
s = _settings(app_env="dev")
|
|
assert s.server_secret_key == _DEFAULT_SECRET_KEY
|
|
assert s.db_password == _DEFAULT_DB_PASSWORD
|
|
|
|
def test_test_env_allows_default_secrets(self):
|
|
s = _settings(app_env="test")
|
|
assert s.server_secret_key == _DEFAULT_SECRET_KEY
|
|
|
|
def test_production_env_rejects_default_secret_key(self):
|
|
with pytest.raises(RuntimeError, match="SERVER_SECRET_KEY"):
|
|
_settings(app_env="production", db_password=_REAL_DB_PASSWORD)
|
|
|
|
def test_production_env_rejects_default_db_password(self):
|
|
with pytest.raises(RuntimeError, match="DB_PASSWORD"):
|
|
_settings(app_env="production", server_secret_key=_REAL_SECRET_KEY)
|
|
|
|
def test_production_env_accepts_real_secrets(self):
|
|
s = _settings(
|
|
app_env="production",
|
|
server_secret_key=_REAL_SECRET_KEY,
|
|
db_password=_REAL_DB_PASSWORD,
|
|
)
|
|
assert s.app_env == "production"
|
|
|
|
def test_module_level_settings_instance_starts_without_env(self):
|
|
"""The already-instantiated `settings` (imported at process start)
|
|
must not have raised - this is what "tests/dev start without .env"
|
|
requires: APP_ENV defaults to "dev", so the guard never fires here."""
|
|
from src.backend.config import settings
|
|
|
|
assert settings.app_env == "dev"
|