test_env_resolution.py 1.46 KB
from pathlib import Path

from services.shared.config.base import (
    resolve_env_file_candidates,
    resolve_explicit_env_path,
    resolve_preferred_env_file,
)


def test_resolve_env_file_candidates_keep_local_override_last(tmp_path: Path):
    project_root = tmp_path / "repo"
    project_root.mkdir()
    cwd = project_root / "apps" / "web_api"
    cwd.mkdir(parents=True)

    candidates = resolve_env_file_candidates(cwd=cwd, project_root=project_root)

    assert candidates == (
        project_root / ".env",
        project_root / ".env.local",
        cwd / ".env",
        cwd / ".env.local",
    )


def test_resolve_preferred_env_file_prefers_existing_local_override(tmp_path: Path):
    project_root = tmp_path / "repo"
    project_root.mkdir()
    (project_root / ".env").write_text("HOST=0.0.0.0\n", encoding="utf-8")
    (project_root / ".env.local").write_text("HOST=127.0.0.1\n", encoding="utf-8")

    candidates = resolve_env_file_candidates(cwd=project_root, project_root=project_root)

    assert resolve_preferred_env_file(candidates) == project_root / ".env.local"


def test_resolve_explicit_env_path_prefers_project_file_when_present(tmp_path: Path):
    project_root = tmp_path / "repo"
    project_root.mkdir()
    cwd = project_root / "scripts"
    cwd.mkdir()
    target = project_root / ".env.local"
    target.write_text("HOST=127.0.0.1\n", encoding="utf-8")

    assert resolve_explicit_env_path(".env.local", cwd=cwd, project_root=project_root) == target