Files
python-cli-template/{{cookiecutter.project_slug}}/tests/test_internals.py
2026-02-14 11:47:18 +01:00

63 lines
2.0 KiB
Python

from __future__ import annotations
import pytest
from pydantic import ValidationError
from {{ cookiecutter.package_name }}.commands import format_greeting
from {{ cookiecutter.package_name }}.config import get_config, get_config_source
from {{ cookiecutter.package_name }}.config.paths import ENV_CONFIG_VAR, config_file_path
def test_env_config_override(tmp_path, monkeypatch) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text('[app]\ngreeting = "Hi"\n\n[database]\npath = "/tmp/app.db"\n')
monkeypatch.setenv(ENV_CONFIG_VAR, str(config_path))
settings = get_config()
assert settings.app.greeting == "Hi"
assert settings.database.path == "/tmp/app.db"
assert get_config_source() == config_path
def test_missing_env_config_raises(tmp_path, monkeypatch) -> None:
missing = tmp_path / "missing.toml"
monkeypatch.setenv(ENV_CONFIG_VAR, str(missing))
with pytest.raises(FileNotFoundError, match="Config file not found"):
get_config()
def test_xdg_default_config_is_loaded(monkeypatch) -> None:
path = config_file_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('[app]\ngreeting = "Hola"\n\n[database]\npath = "/tmp/default.db"\n')
monkeypatch.delenv(ENV_CONFIG_VAR, raising=False)
settings = get_config()
assert settings.app.greeting == "Hola"
assert settings.database.path == "/tmp/default.db"
assert get_config_source() == path
def test_unknown_key_raises_validation_error(tmp_path, monkeypatch) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text('unknown = "value"\n')
monkeypatch.setenv(ENV_CONFIG_VAR, str(config_path))
with pytest.raises(ValidationError):
get_config()
def test_settings_are_frozen() -> None:
settings = get_config()
with pytest.raises(ValidationError, match="frozen"):
settings.app.greeting = "Mutated"
def test_format_greeting() -> None:
assert format_greeting("Ada") == "Hello, Ada!"
assert format_greeting("Ada", greeting="Hi") == "Hi, Ada!"