File size: 1,949 Bytes
ea8c728 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import importlib
import os
import sys
from types import ModuleType
from pathlib import Path
import pytest
def _clear_shinka_modules() -> None:
for module_name in list(sys.modules):
if module_name == "shinka" or module_name.startswith("shinka."):
sys.modules.pop(module_name, None)
def _snapshot_shinka_modules() -> dict[str, ModuleType]:
return {
module_name: module
for module_name, module in sys.modules.items()
if module_name == "shinka" or module_name.startswith("shinka.")
}
def _restore_shinka_modules(snapshot: dict[str, ModuleType]) -> None:
_clear_shinka_modules()
sys.modules.update(snapshot)
def test_import_shinka_loads_dotenv_from_launch_directory(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
env_key = "SHINKA_TEST_IMPORT_KEY"
monkeypatch.delenv(env_key, raising=False)
monkeypatch.chdir(tmp_path)
(tmp_path / ".env").write_text(f"{env_key}=from-launch-dir\n", encoding="utf-8")
module_snapshot = _snapshot_shinka_modules()
try:
_clear_shinka_modules()
importlib.import_module("shinka")
assert os.getenv(env_key) == "from-launch-dir"
finally:
_restore_shinka_modules(module_snapshot)
def test_load_shinka_dotenv_prefers_launch_directory_over_package_env(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
from shinka.env import load_shinka_dotenv
env_key = "SHINKA_TEST_PRIORITY_KEY"
package_root = tmp_path / "package-root"
launch_dir = tmp_path / "launch-dir"
package_root.mkdir()
launch_dir.mkdir()
(package_root / ".env").write_text(f"{env_key}=from-package\n", encoding="utf-8")
(launch_dir / ".env").write_text(f"{env_key}=from-launch-dir\n", encoding="utf-8")
monkeypatch.delenv(env_key, raising=False)
load_shinka_dotenv(package_root=package_root, cwd=launch_dir)
assert os.getenv(env_key) == "from-launch-dir"
|