83 lines
2.6 KiB
Python
83 lines
2.6 KiB
Python
"""Tests for mytoolkit.config.Config (get/set/remove/export + legacy migration).
|
|
|
|
MYTOOLKIT_HOME is pointed at a temp dir by conftest.py before imports, so
|
|
every Config() instance here operates on throwaway files.
|
|
"""
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from mytoolkit import config as config_mod
|
|
from mytoolkit.config import Config
|
|
|
|
|
|
@pytest.fixture()
|
|
def fresh_home(tmp_path, monkeypatch):
|
|
"""Give each test its own empty MYTOOLKIT_HOME."""
|
|
home = tmp_path / "home"
|
|
monkeypatch.setattr(config_mod, "CONFIG_PATH", home / "config.json")
|
|
monkeypatch.setattr(config_mod, "_LEGACY_ENV_PATH", home / "env.json")
|
|
monkeypatch.setattr(config_mod, "_LEGACY_MODULE_PATH", home / "module-config.json")
|
|
return home
|
|
|
|
|
|
def test_set_get_remove_roundtrip(fresh_home):
|
|
c = Config()
|
|
assert c.get("apikey_ark") is None
|
|
c.set("apikey_ark", "sk-test")
|
|
assert c.get("apikey_ark") == "sk-test"
|
|
# Persisted: a fresh instance sees the same value.
|
|
assert Config().get("apikey_ark") == "sk-test"
|
|
assert c.remove("apikey_ark") is True
|
|
assert c.remove("apikey_ark") is False
|
|
assert c.get("apikey_ark") is None
|
|
|
|
|
|
def test_get_all_returns_copy(fresh_home):
|
|
c = Config()
|
|
c.set("k", "v")
|
|
snapshot = c.get_all()
|
|
snapshot["k"] = "mutated"
|
|
assert c.get("k") == "v"
|
|
|
|
|
|
def test_export_prefix(fresh_home):
|
|
c = Config()
|
|
c.set("volc_appid", "123")
|
|
assert c.export() == {"MYCLI_VOLC_APPID": "123"}
|
|
|
|
|
|
def test_corrupt_config_falls_back_to_empty(fresh_home):
|
|
fresh_home.mkdir(parents=True)
|
|
(fresh_home / "config.json").write_text("{not json")
|
|
c = Config()
|
|
assert c.get_all() == {}
|
|
|
|
|
|
def test_legacy_env_json_migrated(fresh_home):
|
|
fresh_home.mkdir(parents=True)
|
|
(fresh_home / "env.json").write_text(
|
|
json.dumps({"vars": {"apikey_ark": "sk-old", "path_study": "/tmp/x"}})
|
|
)
|
|
c = Config()
|
|
assert c.get("apikey_ark") == "sk-old"
|
|
assert c.get("path_study") == "/tmp/x"
|
|
# env.json renamed out of the way so migration does not re-run.
|
|
assert not (fresh_home / "env.json").exists()
|
|
assert (fresh_home / "env.json.migrated").exists()
|
|
|
|
|
|
def test_legacy_env_merges_without_clobbering_existing_keys(fresh_home):
|
|
fresh_home.mkdir(parents=True)
|
|
(fresh_home / "config.json").write_text(
|
|
json.dumps({"keys": {"apikey_ark": "sk-new"}})
|
|
)
|
|
(fresh_home / "env.json").write_text(
|
|
json.dumps({"vars": {"apikey_ark": "sk-old", "extra": "e"}})
|
|
)
|
|
c = Config()
|
|
# Unknown legacy vars are merged in; known keys keep the existing mytoolkit value.
|
|
assert c.get("extra") == "e"
|
|
assert c.get("apikey_ark") == "sk-new"
|