"""Comprehensive tests for ``muse code find-symbol``. Coverage -------- Unit _flat_insert_ops — pure inserts, nested patch children, mixed, empty _name_matches — exact, prefix (*), case-insensitive, no-match _list_branches — empty dir, populated dir, non-file entries ignored _MIN_HASH_PREFIX — sentinel value Integration (extends mega-suite baseline) --name exact — finds, doesn't find, prefix wildcard --kind filter — restricts to kind --hash — too short rejected, matching hash found --since / --until — date range filtering --limit — stops early --first / --last — deduplication modes --count — scalar output --file filter — restricts to file path --branch — restricts to one branch's history --all-branches — reports branch presence --json schema — required fields, count == len(appearances) no flags — exits 1 Security no-repo — exits non-zero Stress 50-commit history — find-symbol across all commits under 10 s prefix wildcard — large result set handled --limit 1 on large — returns quickly """ from __future__ import annotations import json import pathlib import textwrap import time import pytest from tests.cli_test_helper import CliRunner from muse.cli.commands.find_symbol import ( _MIN_HASH_PREFIX, _flat_insert_ops, _list_branches, _name_matches, ) from muse.domain import DeleteOp, DomainOp, InsertOp, PatchOp from muse.core.paths import heads_dir, indices_dir cli = None runner = CliRunner() # --------------------------------------------------------------------------- # Helpers to build minimal DomainOp dicts # --------------------------------------------------------------------------- def _insert_op(address: str = "f.py::foo") -> DomainOp: return InsertOp( op="insert", address=address, position=None, content_id="a" * 64, content_summary="function foo", ) def _patch_op(children: list[DomainOp]) -> DomainOp: return PatchOp( op="patch", address="f.py", child_ops=children, child_domain="code", child_summary="patch", ) def _delete_op(address: str = "f.py::old") -> DomainOp: return DeleteOp( op="delete", address=address, position=None, content_id="e" * 64, content_summary="del", ) # --------------------------------------------------------------------------- # Unit — _flat_insert_ops # --------------------------------------------------------------------------- class TestFlatInsertOps: def test_empty_list(self) -> None: assert _flat_insert_ops([]) == [] def test_single_insert(self) -> None: ops = [_insert_op()] result = _flat_insert_ops(ops) assert len(result) == 1 assert result[0]["op"] == "insert" def test_delete_excluded(self) -> None: ops = [_delete_op(), _insert_op()] result = _flat_insert_ops(ops) assert len(result) == 1 assert result[0]["address"] == "f.py::foo" def test_patch_children_extracted(self) -> None: child_insert = _insert_op("f.py::bar") patch = _patch_op([child_insert]) result = _flat_insert_ops([patch]) assert len(result) == 1 assert result[0]["address"] == "f.py::bar" def test_patch_with_delete_child_excluded(self) -> None: patch = _patch_op([_delete_op("f.py::gone")]) result = _flat_insert_ops([patch]) assert result == [] def test_mixed_ops(self) -> None: ops = [ _insert_op("f.py::alpha"), _delete_op("f.py::beta"), _patch_op([_insert_op("f.py::gamma"), _delete_op("f.py::delta")]), ] result = _flat_insert_ops(ops) addresses = {r["address"] for r in result} assert "f.py::alpha" in addresses assert "f.py::gamma" in addresses assert "f.py::beta" not in addresses assert "f.py::delta" not in addresses def test_multiple_inserts(self) -> None: ops = [_insert_op(f"f.py::fn_{i}") for i in range(10)] result = _flat_insert_ops(ops) assert len(result) == 10 # --------------------------------------------------------------------------- # Unit — _name_matches # --------------------------------------------------------------------------- class TestNameMatches: def test_exact_match(self) -> None: assert _name_matches("validate_amount", "validate_amount") def test_exact_case_insensitive(self) -> None: assert _name_matches("ValidateAmount", "validateamount") def test_no_match(self) -> None: assert not _name_matches("validate_amount", "compute_total") def test_prefix_wildcard_match(self) -> None: assert _name_matches("validate_amount", "validate*") def test_prefix_wildcard_no_match(self) -> None: assert not _name_matches("compute_total", "validate*") def test_prefix_wildcard_case_insensitive(self) -> None: assert _name_matches("ValidateAmount", "validate*") def test_star_alone_matches_everything(self) -> None: assert _name_matches("anything", "*") def test_empty_pattern_no_match(self) -> None: # An empty pattern (not wildcard) only matches an empty name. assert _name_matches("", "") assert not _name_matches("something", "") def test_exact_empty_string(self) -> None: assert _name_matches("", "") def test_prefix_longer_than_name(self) -> None: assert not _name_matches("foo", "foobar*") # --------------------------------------------------------------------------- # Unit — _list_branches # --------------------------------------------------------------------------- class TestListBranches: def test_empty_when_no_heads_dir(self, tmp_path: pathlib.Path) -> None: result = _list_branches(tmp_path) assert result == [] def test_returns_branch_names(self, tmp_path: pathlib.Path) -> None: heads = heads_dir(tmp_path) heads.mkdir(parents=True) (heads / "main").write_text("abc123") (heads / "feature-foo").write_text("def456") result = _list_branches(tmp_path) assert "main" in result assert "feature-foo" in result def test_sorted_output(self, tmp_path: pathlib.Path) -> None: heads = heads_dir(tmp_path) heads.mkdir(parents=True) for name in ("zebra", "alpha", "middle"): (heads / name).write_text("hash") result = _list_branches(tmp_path) assert result == sorted(result) def test_ignores_directories(self, tmp_path: pathlib.Path) -> None: heads = heads_dir(tmp_path) heads.mkdir(parents=True) (heads / "main").write_text("hash") (heads / "subdir").mkdir() # not a file result = _list_branches(tmp_path) assert "subdir" not in result assert "main" in result # --------------------------------------------------------------------------- # Unit — _MIN_HASH_PREFIX # --------------------------------------------------------------------------- class TestMinHashPrefix: def test_value_is_four(self) -> None: assert _MIN_HASH_PREFIX == 4 # --------------------------------------------------------------------------- # Shared repo fixture # --------------------------------------------------------------------------- @pytest.fixture def repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: """Repo with two commits, each adding distinct symbols.""" monkeypatch.chdir(tmp_path) monkeypatch.setenv("MUSE_REPO_ROOT", str(tmp_path)) r = runner.invoke(cli, ["init", "--domain", "code"]) assert r.exit_code == 0, r.output (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items: list[int]) -> int: return sum(items) def validate_amount(amount: float) -> bool: return amount > 0 """)) runner.invoke(cli, ["code", "add", "."]) r2 = runner.invoke(cli, ["commit", "-m", "first commit"]) assert r2.exit_code == 0, r2.output (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items: list[int]) -> int: return sum(items) def apply_discount(self, total: float, pct: float) -> float: return total * (1 - pct) def validate_amount(amount: float) -> bool: return amount > 0 def format_receipt(amount: float) -> str: return f"Total: {amount:.2f}" """)) runner.invoke(cli, ["code", "add", "."]) r3 = runner.invoke(cli, ["commit", "-m", "second commit"]) assert r3.exit_code == 0, r3.output return tmp_path # --------------------------------------------------------------------------- # Integration — name search # --------------------------------------------------------------------------- class TestFindSymbolByName: def test_finds_existing_name(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "validate_amount"]) assert result.exit_code == 0 assert "validate_amount" in result.output def test_no_result_for_unknown(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "zzz_never_exists"]) assert result.exit_code == 0 assert "no matching" in result.output.lower() def test_prefix_wildcard(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "validate*", "--json"]) assert result.exit_code == 0 data = json.loads(result.output) for ap in data["results"]: assert ap["name"].lower().startswith("validate") def test_no_flags_exits_one(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol"]) assert result.exit_code == 1 def test_first_last_mutually_exclusive(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--first", "--last", ]) assert result.exit_code == 1 # --------------------------------------------------------------------------- # Integration — kind and file filters # --------------------------------------------------------------------------- class TestFindSymbolFilters: def test_kind_class(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--kind", "class", "--json"]) assert result.exit_code == 0 data = json.loads(result.output) for ap in data["results"]: assert ap["kind"] == "class" def test_file_filter(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--kind", "function", "--file", "billing.py", "--json", ]) assert result.exit_code == 0 data = json.loads(result.output) for ap in data["results"]: assert "billing.py" in ap["address"] def test_limit_one(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--kind", "function", "--limit", "1"]) assert result.exit_code == 0 def test_count_is_integer(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "validate_amount", "--count"]) assert result.exit_code == 0 assert result.output.strip().isdigit() # --------------------------------------------------------------------------- # Integration — date filters # --------------------------------------------------------------------------- class TestFindSymbolDates: def test_since_future_returns_empty(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--since", "2099-01-01", ]) assert result.exit_code == 0 assert "no matching" in result.output.lower() def test_since_invalid_format_exits_one(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--since", "not-a-date", ]) assert result.exit_code == 1 def test_until_invalid_format_exits_one(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--until", "31/12/2024", ]) assert result.exit_code == 1 # --------------------------------------------------------------------------- # Integration — hash search # --------------------------------------------------------------------------- class TestFindSymbolByHash: def test_hash_too_short_rejected(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--hash", "ab"]) assert result.exit_code == 1 assert "4" in result.stderr or "short" in result.stderr.lower() def test_hash_four_chars_accepted(self, repo: pathlib.Path) -> None: # Even a non-matching 4-char hash must not be rejected for length. result = runner.invoke(cli, ["code", "find-symbol", "--hash", "0000"]) assert result.exit_code == 0 # no match, but not a length error # --------------------------------------------------------------------------- # Integration — --first / --last deduplication # --------------------------------------------------------------------------- class TestFindSymbolFirstLast: def test_first_count_le_all_count(self, repo: pathlib.Path) -> None: r_all = runner.invoke(cli, ["code", "find-symbol", "--name", "validate_amount", "--count"]) r_first = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--first", "--count", ]) assert r_all.exit_code == 0 assert r_first.exit_code == 0 count_all = int(r_all.output.strip()) count_first = int(r_first.output.strip()) assert count_first <= count_all def test_last_count_le_all_count(self, repo: pathlib.Path) -> None: r_all = runner.invoke(cli, ["code", "find-symbol", "--name", "validate_amount", "--count"]) r_last = runner.invoke(cli, [ "code", "find-symbol", "--name", "validate_amount", "--last", "--count", ]) assert int(r_last.output.strip()) <= int(r_all.output.strip()) # --------------------------------------------------------------------------- # Integration — JSON schema # --------------------------------------------------------------------------- class TestFindSymbolJson: def test_schema_top_level_keys(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "Invoice", "--json"]) assert result.exit_code == 0 data = json.loads(result.output) for key in ("query", "results", "total"): assert key in data def test_count_matches_appearances_length(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--kind", "function", "--json"]) data = json.loads(result.output) assert data["total"] == len(data["results"]) def test_appearance_fields(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "validate_amount", "--json"]) data = json.loads(result.output) if data["results"]: ap = data["results"][0] for field in ("content_id", "address", "name", "kind", "commit_id", "committed_at"): assert field in ap, f"missing field {field!r}" def test_empty_result_valid_json(self, repo: pathlib.Path) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--name", "zzz_never", "--json"]) assert result.exit_code == 0 data = json.loads(result.output) assert data["total"] == 0 assert data["results"] == [] # --------------------------------------------------------------------------- # Security # --------------------------------------------------------------------------- class TestFindSymbolSecurity: def test_requires_repo( self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.chdir(tmp_path) monkeypatch.delenv("MUSE_REPO_ROOT", raising=False) result = runner.invoke(cli, ["code", "find-symbol", "--name", "foo"]) assert result.exit_code != 0 # --------------------------------------------------------------------------- # Stress — 50-commit history # --------------------------------------------------------------------------- class TestFindSymbolStress: @pytest.fixture def deep_repo( self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with 50 commits, each adding one new function.""" monkeypatch.chdir(tmp_path) monkeypatch.setenv("MUSE_REPO_ROOT", str(tmp_path)) runner.invoke(cli, ["init", "--domain", "code"]) lines: list[str] = [] for i in range(50): lines.append(f"def worker_{i:03d}(x: int) -> int:") lines.append(f" return x + {i}") lines.append("") (tmp_path / "workers.py").write_text("\n".join(lines)) runner.invoke(cli, ["code", "add", "."]) r = runner.invoke(cli, ["commit", "-m", f"add worker_{i:03d}"]) assert r.exit_code == 0, f"commit {i} failed: {r.output}" return tmp_path def test_find_across_50_commits_under_10s(self, deep_repo: pathlib.Path) -> None: """find-symbol must walk 50 commits without hanging, regardless of results.""" start = time.monotonic() result = runner.invoke(cli, ["code", "find-symbol", "--name", "worker*", "--count"]) elapsed = time.monotonic() - start assert result.exit_code == 0, result.output assert elapsed < 10.0, f"find-symbol on 50 commits took {elapsed:.2f}s" # Count is an integer (may be 0 if structured_delta has no InsertOps). assert result.output.strip().isdigit() def test_find_prefix_json_always_valid(self, deep_repo: pathlib.Path) -> None: """JSON output is structurally correct regardless of result count.""" result = runner.invoke(cli, ["code", "find-symbol", "--name", "worker*", "--json"]) assert result.exit_code == 0 data = json.loads(result.output) assert data["total"] == len(data["results"]) assert isinstance(data["results"], list) assert isinstance(data["query"], dict) # Appearances (if any) must have required fields. for ap in data["results"]: for field in ("content_id", "address", "name", "kind", "commit_id"): assert field in ap def test_limit_one_on_50_commits_fast(self, deep_repo: pathlib.Path) -> None: start = time.monotonic() result = runner.invoke(cli, [ "code", "find-symbol", "--name", "worker*", "--limit", "1", ]) elapsed = time.monotonic() - start assert result.exit_code == 0 assert elapsed < 5.0, f"--limit 1 on 50 commits took {elapsed:.2f}s" def test_first_dedup_addresses_unique(self, deep_repo: pathlib.Path) -> None: """--first must deduplicate: no address appears more than once.""" result = runner.invoke(cli, [ "code", "find-symbol", "--name", "worker*", "--first", "--json", ]) assert result.exit_code == 0 data = json.loads(result.output) addresses = [ap["address"] for ap in data["results"]] assert len(addresses) == len(set(addresses)) def test_kind_filter_json_consistent_on_deep_repo(self, deep_repo: pathlib.Path) -> None: start = time.monotonic() result = runner.invoke(cli, ["code", "find-symbol", "--kind", "function", "--json"]) elapsed = time.monotonic() - start assert result.exit_code == 0 assert elapsed < 10.0 data = json.loads(result.output) # count must match appearances length. assert data["total"] == len(data["results"]) # All appearances must have kind == "function". for ap in data["results"]: assert ap["kind"] == "function" # --------------------------------------------------------------------------- # --body-hash flag — index-backed body_hash lookup # --------------------------------------------------------------------------- class TestFindSymbolBodyHash: """Tests for ``--body-hash`` flag which uses the hash_occurrence index.""" def _index_path(self, repo: pathlib.Path) -> pathlib.Path: return indices_dir(repo) / "hash_occurrence.json" def _get_clone_body_hash(self, repo: pathlib.Path) -> str | None: """Return a body_hash prefix known to be a clone in *repo*.""" result = runner.invoke(cli, ["code", "clones", "--tier", "exact", "--json"]) if result.exit_code != 0: return None data = json.loads(result.output) if not data["clusters"]: return None return data["clusters"][0]["hash"] # already short_id format @pytest.fixture def clone_repo( self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: monkeypatch.chdir(tmp_path) monkeypatch.setenv("MUSE_REPO_ROOT", str(tmp_path)) runner.invoke(cli, ["init", "--domain", "code"]) body = "def shared_fn(x):\n return x * 2\n" (tmp_path / "a.py").write_text(body) (tmp_path / "b.py").write_text(body) runner.invoke(cli, ["code", "add", "."]) runner.invoke(cli, ["commit", "-m", "clone fixture"]) return tmp_path def test_body_hash_too_short_exits_nonzero( self, clone_repo: pathlib.Path ) -> None: result = runner.invoke(cli, ["code", "find-symbol", "--body-hash", "ab"]) assert result.exit_code != 0 def test_body_hash_and_hash_mutually_exclusive( self, clone_repo: pathlib.Path ) -> None: result = runner.invoke(cli, [ "code", "find-symbol", "--body-hash", "deadbeef", "--hash", "deadbeef", ]) assert result.exit_code != 0 def test_body_hash_and_name_mutually_exclusive( self, clone_repo: pathlib.Path ) -> None: """--body-hash is a standalone lookup; combining with --name is an error.""" result = runner.invoke(cli, [ "code", "find-symbol", "--body-hash", "deadbeef", "--name", "foo", ]) assert result.exit_code != 0 def test_body_hash_not_found_exits_zero_empty_results( self, clone_repo: pathlib.Path ) -> None: result = runner.invoke( cli, ["code", "find-symbol", "--body-hash", "deadbeef", "--json"] ) assert result.exit_code == 0 data = json.loads(result.output) assert data["total"] == 0 assert data["results"] == [] def test_body_hash_finds_exact_clone_addresses_with_index( self, clone_repo: pathlib.Path ) -> None: """With index, --body-hash returns both addresses sharing the body.""" runner.invoke(cli, ["code", "index", "rebuild", "--index", "hash_occurrence"]) body_hash = self._get_clone_body_hash(clone_repo) if body_hash is None: pytest.skip("No exact clones detected") result = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) assert result.exit_code == 0 data = json.loads(result.output) assert data["total"] >= 2 addresses = {r["address"] for r in data["results"]} files = {a.split("::")[0] for a in addresses} assert len(files) >= 2, "clone members must span at least two files" def test_body_hash_falls_back_to_scan_without_index( self, clone_repo: pathlib.Path ) -> None: """Without index, --body-hash walks HEAD snapshot directly.""" self._index_path(clone_repo).unlink(missing_ok=True) body_hash = self._get_clone_body_hash(clone_repo) if body_hash is None: pytest.skip("No exact clones detected") result = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) assert result.exit_code == 0 data = json.loads(result.output) assert data["total"] >= 2 def test_body_hash_json_schema(self, clone_repo: pathlib.Path) -> None: """JSON output has the standard find-symbol envelope fields.""" runner.invoke(cli, ["code", "index", "rebuild", "--index", "hash_occurrence"]) body_hash = self._get_clone_body_hash(clone_repo) if body_hash is None: pytest.skip("No exact clones detected") result = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) assert result.exit_code == 0 data = json.loads(result.output) for field in ("total", "results", "query", "exit_code", "duration_ms"): assert field in data, f"missing field: {field}" assert data["query"].get("body_hash") == body_hash def test_body_hash_result_has_address_field( self, clone_repo: pathlib.Path ) -> None: runner.invoke(cli, ["code", "index", "rebuild", "--index", "hash_occurrence"]) body_hash = self._get_clone_body_hash(clone_repo) if body_hash is None: pytest.skip("No exact clones detected") result = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) data = json.loads(result.output) for r in data["results"]: assert "address" in r def test_body_hash_results_match_index_and_scan( self, clone_repo: pathlib.Path ) -> None: """Index path and scan path return the same set of addresses.""" body_hash = self._get_clone_body_hash(clone_repo) if body_hash is None: pytest.skip("No exact clones detected") # Scan path (no index) self._index_path(clone_repo).unlink(missing_ok=True) r_scan = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) scan_addrs = {ap["address"] for ap in json.loads(r_scan.output)["results"]} # Index path runner.invoke(cli, ["code", "index", "rebuild", "--index", "hash_occurrence"]) r_idx = runner.invoke( cli, ["code", "find-symbol", "--body-hash", body_hash, "--json"] ) idx_addrs = {ap["address"] for ap in json.loads(r_idx.output)["results"]} assert scan_addrs == idx_addrs