"""Comprehensive tests for ``muse config`` — show / get / set. Coverage: - Unit: get_config_value, set_config_value, config_as_dict - Integration: CLI round-trips for show, get, set - E2E: full set→get→show workflow - Security: blocked namespaces, TOML injection, malformed keys - Format: --json / --format json output """ from __future__ import annotations import json import pathlib import pytest from muse.core.types import fake_id from muse.core.paths import config_toml_path, muse_dir from tests.cli_test_helper import CliRunner cli = None # argparse migration — CliRunner ignores this arg runner = CliRunner() # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _init_repo(tmp_path: pathlib.Path) -> tuple[pathlib.Path, str]: """Initialise a minimal .muse repo and return (root, repo_id).""" repo_id = fake_id("repo") dot_muse = muse_dir(tmp_path) dot_muse.mkdir() (dot_muse / "repo.json").write_text( json.dumps({"repo_id": repo_id, "domain": "midi", "default_branch": "main", "created_at": "2026-01-01T00:00:00+00:00"}) ) (dot_muse / "HEAD").write_text("ref: refs/heads/main") (dot_muse / "refs" / "heads").mkdir(parents=True) (dot_muse / "snapshots").mkdir() (dot_muse / "commits").mkdir() (dot_muse / "objects").mkdir() return tmp_path, repo_id def _env(root: pathlib.Path) -> Manifest: return {"MUSE_REPO_ROOT": str(root)} # --------------------------------------------------------------------------- # Parser flag tests # --------------------------------------------------------------------------- class TestRegisterFlags: def _parse(self, *args: str) -> "argparse.Namespace": import argparse from muse.cli.commands.config_cmd import register p = argparse.ArgumentParser() sub = p.add_subparsers() register(sub) return p.parse_args(["config", *args]) def test_get_default_json_out_is_false(self) -> None: ns = self._parse("get", "hub.url") assert ns.json_out is False def test_get_json_flag_sets_json_out(self) -> None: ns = self._parse("get", "hub.url", "--json") assert ns.json_out is True def test_get_j_shorthand_sets_json_out(self) -> None: ns = self._parse("get", "hub.url", "-j") assert ns.json_out is True def test_set_default_json_out_is_false(self) -> None: ns = self._parse("set", "hub.url", "https://musehub.ai") assert ns.json_out is False def test_set_json_flag_sets_json_out(self) -> None: ns = self._parse("set", "hub.url", "https://musehub.ai", "--json") assert ns.json_out is True def test_read_default_json_out_is_false(self) -> None: ns = self._parse("read") assert ns.json_out is False def test_read_json_flag_sets_json_out(self) -> None: ns = self._parse("read", "--json") assert ns.json_out is True def test_read_j_shorthand_sets_json_out(self) -> None: ns = self._parse("read", "-j") assert ns.json_out is True # --------------------------------------------------------------------------- # Unit tests — config helpers # --------------------------------------------------------------------------- class TestConfigValueHelpers: def test_set_user_handle_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError): set_config_value("user.handle", "Alice", root) def test_set_user_email_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError): set_config_value("user.email", "alice@example.com", root) def test_set_user_type_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError): set_config_value("user.type", "agent", root) def test_set_and_get_domain_key(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import get_config_value, set_config_value set_config_value("domain.ticks_per_beat", "480", root) assert get_config_value("domain.ticks_per_beat", root) == "480" def test_get_missing_hub_key_returns_none(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import get_config_value assert get_config_value("hub.url", root) is None def test_get_unknown_namespace_returns_none(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import get_config_value assert get_config_value("unknown.key", root) is None def test_set_blocked_auth_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError, match="muse auth keygen"): set_config_value("auth.anything", "secret", root) def test_set_blocked_remotes_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError, match="muse remote"): set_config_value("remotes.origin", "https://x.com", root) def test_set_unknown_namespace_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError): set_config_value("invalid.key", "value", root) def test_set_malformed_key_raises(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError): set_config_value("no-dot-key", "value", root) def test_config_as_dict_no_user_section(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import config_as_dict, set_hub_url set_hub_url("https://musehub.ai", root) d = config_as_dict(root) assert "user" not in d assert d.get("hub", {}).get("url") == "https://musehub.ai" def test_config_as_dict_empty_repo(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import config_as_dict d = config_as_dict(root) assert isinstance(d, dict) def test_set_hub_url_requires_https(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.cli.config import set_config_value with pytest.raises(ValueError, match="HTTPS"): set_config_value("hub.url", "http://insecure.example.com", root) # --------------------------------------------------------------------------- # Integration tests — CLI commands # --------------------------------------------------------------------------- class TestConfigCLI: def test_read_empty_config(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "read"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_read_json_empty(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 data = json.loads(result.output) assert isinstance(data, dict) def test_read_format_json(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 data = json.loads(result.output) assert isinstance(data, dict) def test_set_user_handle_blocked(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "user.handle", "Alice"], env=_env(root)) assert result.exit_code != 0 def test_set_then_get_hub_url(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "hub.url", "https://musehub.ai"], env=_env(root), catch_exceptions=False) result = runner.invoke(cli, ["config", "get", "hub.url"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "musehub.ai" in result.output def test_get_unset_key_fails(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "get", "hub.url"], env=_env(root)) assert result.exit_code != 0 def test_set_domain_key(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "domain.ticks_per_beat", "480"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_get_domain_key_after_set(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "domain.ticks_per_beat", "960"], env=_env(root)) result = runner.invoke(cli, ["config", "get", "domain.ticks_per_beat"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "960" in result.output def test_set_blocked_auth_fails(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "auth.anything", "secret"], env=_env(root)) assert result.exit_code != 0 def test_set_blocked_remotes_fails(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "remotes.origin", "https://x.com"], env=_env(root)) assert result.exit_code != 0 def test_set_http_hub_url_fails(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "hub.url", "http://insecure.example.com"], env=_env(root)) assert result.exit_code != 0 def test_set_https_hub_url_succeeds(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "hub.url", "https://musehub.ai"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_read_after_set_includes_value(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "domain.label", "Dave"], env=_env(root)) result = runner.invoke(cli, ["config", "read"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "Dave" in result.output def test_read_json_after_set(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "hub.url", "https://musehub.ai"], env=_env(root)) runner.invoke(cli, ["config", "set", "domain.ticks_per_beat", "480"], env=_env(root)) result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 envelope = json.loads(result.output) data = envelope.get("config", envelope) assert data.get("hub", {}).get("url") == "https://musehub.ai" assert data.get("domain", {}).get("ticks_per_beat") == "480" def test_multiple_sets_accumulate(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "hub.url", "https://musehub.ai"], env=_env(root)) runner.invoke(cli, ["config", "set", "domain.sample_rate", "44100"], env=_env(root)) runner.invoke(cli, ["config", "set", "domain.key", "val"], env=_env(root)) result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) envelope = json.loads(result.output) data = envelope.get("config", envelope) assert data["hub"]["url"] == "https://musehub.ai" assert data["domain"]["sample_rate"] == "44100" assert data["domain"]["key"] == "val" def test_set_overwrites_previous_value(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "domain.label", "Old"], env=_env(root)) runner.invoke(cli, ["config", "set", "domain.label", "New"], env=_env(root)) result = runner.invoke(cli, ["config", "get", "domain.label"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "New" in result.output def test_read_format_unknown_fails(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "read", "--format", "xml"], env=_env(root)) assert result.exit_code != 0 # --------------------------------------------------------------------------- # E2E tests # --------------------------------------------------------------------------- class TestConfigE2E: def test_full_agent_config_workflow(self, tmp_path: pathlib.Path) -> None: """Agent sets hub and domain config, then reads it back as JSON.""" root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "hub.url", "https://musehub.ai"], env=_env(root)) runner.invoke(cli, ["config", "set", "domain.ticks_per_beat", "960"], env=_env(root)) result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 envelope = json.loads(result.output) data = envelope.get("config", envelope) assert data["hub"]["url"] == "https://musehub.ai" assert data["domain"]["ticks_per_beat"] == "960" assert "user" not in data def test_config_persists_across_invocations(self, tmp_path: pathlib.Path) -> None: """Config written in one invocation is readable in a subsequent one.""" root, _ = _init_repo(tmp_path) runner.invoke(cli, ["config", "set", "domain.label", "persistent"], env=_env(root)) result = runner.invoke(cli, ["config", "get", "domain.label"], env=_env(root), catch_exceptions=False) assert "persistent" in result.output # --------------------------------------------------------------------------- # Security tests # --------------------------------------------------------------------------- class TestConfigSecurity: def test_toml_injection_in_domain_value_stored_safely(self, tmp_path: pathlib.Path) -> None: """TOML injection chars in a domain value do not break the config file.""" root, _ = _init_repo(tmp_path) injection = 'Alice"\n[injected]\nkey = "value' result = runner.invoke(cli, ["config", "set", "domain.label", injection], env=_env(root)) # Should either fail safely or store the value escaped if result.exit_code == 0: runner.invoke(cli, ["config", "get", "domain.label"], env=_env(root)) # If stored, round-trip must be stable — no config file corruption show_result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root)) assert show_result.exit_code == 0 data = json.loads(show_result.output) assert isinstance(data, dict) def test_no_credentials_in_json_output(self, tmp_path: pathlib.Path) -> None: """config read --json never leaks credentials even if they somehow end up in config.toml.""" root, _ = _init_repo(tmp_path) # Manually inject a fake token into config.toml config_toml_path(root).write_text('[auth]\ntoken = "super-secret"\n', encoding="utf-8") result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "super-secret" not in result.output def test_set_user_type_is_blocked(self, tmp_path: pathlib.Path) -> None: """user.type writes are blocked — identity.toml owns this namespace.""" root, _ = _init_repo(tmp_path) result = runner.invoke(cli, ["config", "set", "user.type", "robot"], env=_env(root)) assert result.exit_code != 0 # --------------------------------------------------------------------------- # Stress tests # --------------------------------------------------------------------------- class TestConfigStress: def test_many_domain_keys(self, tmp_path: pathlib.Path) -> None: """Setting 50 domain keys all survive a JSON round-trip.""" root, _ = _init_repo(tmp_path) keys = {f"domain.key_{i}": str(i) for i in range(50)} for k, v in keys.items(): r = runner.invoke(cli, ["config", "set", k, v], env=_env(root)) assert r.exit_code == 0 result = runner.invoke(cli, ["config", "read", "--json"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 envelope = json.loads(result.output) data = envelope.get("config", envelope) domain = data.get("domain", {}) for i in range(50): assert domain.get(f"key_{i}") == str(i) def test_overwrite_domain_key_many_times(self, tmp_path: pathlib.Path) -> None: """Repeated writes to the same key keep only the latest value.""" root, _ = _init_repo(tmp_path) for i in range(20): runner.invoke(cli, ["config", "set", "domain.counter", str(i)], env=_env(root)) result = runner.invoke(cli, ["config", "get", "domain.counter"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "19" in result.output