"""config-dir resolution + config-dir/.env loading (REQ-048/010 CHG-20260609-01).""" from __future__ import annotations import os import pytest from trex_core.runtime.config import _load_dotenv, resolve_config_toml _K = "TREX_TEST_RESOLVE_KEY" @pytest.fixture(autouse=True) def _clean(monkeypatch): monkeypatch.delenv(_K, raising=False) # --- resolve_config_toml (REQ-048 AC-7/8) ---------------------------------- # def test_resolve_name_default_dir(): assert resolve_config_toml("test") == os.path.join("config", "test.toml") def test_resolve_appends_toml(): assert resolve_config_toml("test.toml") == os.path.join("config", "test.toml") def test_resolve_with_config_path(): assert resolve_config_toml("prod", "/etc/trex") == os.path.join("/etc/trex", "prod.toml") def test_resolve_path_form_passthrough(): # AC-8: a slash-bearing value is an explicit path (backward-compat). assert resolve_config_toml("config/test.toml") == "config/test.toml" assert resolve_config_toml("config/test.toml", "/etc/trex") == "config/test.toml" # --- _load_dotenv config-dir resolution (REQ-010 AC-6/7) ------------------- # def test_dotenv_loaded_from_config_dir_cwd_independent(tmp_path, monkeypatch): cfgdir = tmp_path / "cfg" cfgdir.mkdir() (cfgdir / ".env").write_text(f"{_K}=from_config_dir\n") toml = str(cfgdir / "inst.toml") # chdir somewhere with no .env to prove CWD-independence. other = tmp_path / "elsewhere" other.mkdir() monkeypatch.chdir(other) _load_dotenv(toml) assert os.environ[_K] == "from_config_dir" def test_dotenv_env_file_wins(tmp_path, monkeypatch): cfgdir = tmp_path / "cfg" cfgdir.mkdir() (cfgdir / ".env").write_text(f"{_K}=from_config_dir\n") explicit = tmp_path / "explicit.env" explicit.write_text(f"{_K}=from_env_file\n") monkeypatch.chdir(tmp_path) _load_dotenv(str(cfgdir / "inst.toml"), env_file=str(explicit)) assert os.environ[_K] == "from_env_file" def test_dotenv_os_env_takes_precedence(tmp_path, monkeypatch): cfgdir = tmp_path / "cfg" cfgdir.mkdir() (cfgdir / ".env").write_text(f"{_K}=from_config_dir\n") monkeypatch.setenv(_K, "from_os_env") _load_dotenv(str(cfgdir / "inst.toml")) assert os.environ[_K] == "from_os_env" # override=False def test_dotenv_absent_is_noop(tmp_path): # config dir has no .env -> no crash, key stays unset. _load_dotenv(str(tmp_path / "inst.toml")) assert _K not in os.environ # --- CLI --config-path instance routing (REQ-048 AC-9) --------------------- # def test_cli_resolve_instance_honors_config_path(tmp_path): from types import SimpleNamespace from trex_core.runtime.cli import _resolve_instance cfgdir = tmp_path / "cfg" cfgdir.mkdir() (cfgdir / "inst.toml").write_text('instance_key = "inst-xyz"\n') args = SimpleNamespace(instance=None, config="inst", config_path=str(cfgdir)) assert _resolve_instance(args) == "inst-xyz"