mirror of
https://github.com/safishamsi/graphify.git
synced 2026-07-13 10:57:13 +00:00
b6127aa5a7
* feat(bash): harden extractor — literal filtering, entrypoint nodes, AST-ancestry-aware command detection Builds on tree-sitter-bash extractor from #866. Two correctness/security improvements to bash extraction in graphify/extract.py: 1. Reject command/process substitutions at extraction time. Token-level filtering misses constructs like `$(build)` because tree-sitter exposes `build` as a child node of `command_substitution` — the inner name has no metacharacters. Added `is_inside_expansion(node)` that walks `node.parent` until it finds `command_substitution` or `process_substitution`. Used as a gate in both `walk` and `walk_calls`. Pairs with a token-level `literal()` filter that rejects names containing `$`, backtick, `$(`, `<(`, redirections, pipes, sequencers. 2. Entrypoint node. Every .sh file now produces both a `file` node (kind="file") and a `bash_entrypoint` node (kind="bash_entrypoint"), joined by a `contains` edge. A separate top-level `walk_calls(root, entry_nid, ...)` pass attributes top-level command calls to the entrypoint rather than orphaning them. Matches the entrypoint pattern other-language extractors use. Node metadata gains language+kind. Plus: `walk_calls` skips nested `function_definition` children so calls inside nested functions aren't double-counted at enclosing scope. Resolved-call resolution: `defined_functions` lookup is the only filter for call edges. User-defined functions named like external commands (install, find, git, ...) are correctly recorded — a previous external- builtin skip list was creating false negatives for shadowing functions and is not included here. Skip list belongs with raw/unresolved call recording (not in this PR). Devtools (bundled): pyproject.toml gains [dependency-groups] dev (ruff, pyright, pre-commit, hypothesis, pip-audit) plus minimal [tool.ruff], [tool.ruff.lint], [tool.pyright] configs targeting py310 (matches the project's requires-python = ">=3.10"). Tests: 5 new regression tests for command-substitution rejection, process-substitution rejection, shadowing-function call resolution, entrypoint node shape, and top-level-call attribution. 826/826 pass (was 821); 15/15 bash-relevant tests pass (was 10). * feat(detect): parse macOS/BSD and GNU env(1) shebang option forms Upstream's _shebang_file_type parses shebangs via line[2:].split() and only handles `#!/usr/bin/env <interp>`. Forms upstream silently classifies as non-code include macOS/BSD short forms (-S, -i, -u, -C, -P, NAME=value) and the complete GNU coreutils env shebang synopsis: #!/usr/bin/env -[v]S[option]... [name=value]... command [args]... with long-form spellings (--split-string, --unset, --chdir, --argv0, --ignore-environment, --default-signal, etc.), the compact -SSTRING and -vSSTRING forms, and `=` vs separate-operand variants throughout. Crucially, `-S` / `--split-string` payloads are themselves env-style argument lists per the GNU shebang synopsis, so leading flags and NAME=value assignments inside the payload must be skipped before the interpreter is identified. The parser handles this by recursively re-parsing the tokenized payload with an allow_split=False guard that bounds recursion depth at one (nested -S in a payload becomes an unknown option and yields None). Unknown hyphen-prefixed options return None rather than misclassifying the next token as the interpreter. _shebang_file_type becomes a 4-line wrapper. Read buffer raised 128 -> 256 to accommodate longer env -S strings. Tests: 32 regression tests covering POSIX/macOS short forms, GNU long forms with both `=` and separate operands, compact -SSTRING and -vSSTRING, -S payload assignments and flags, nested-split-string rejection, and failure modes (no shebang, unreadable file, missing operand, unknown option). * fix(skills): enforce semantic fragment validation in OpenCode + Codex merges (#825) Closes #825. Adds graphify.semantic_cleanup module with hard validation + sanitization for untrusted agent JSON, and wires it into the skill merge pipeline so malicious or runaway extractor responses cannot: - exhaust memory with a multi-GB payload (25 MiB cap) - escape the chunk directory via crafted node/edge/hyperedge IDs (charset + length validation across all three) - inject sentence-like rationale text as standalone graph nodes (detected via file_type in {rationale, concept} OR rationale_for edge + sentence-like label, regardless of declared file_type) - inject invalid file_type values - leave dangling hyperedges referencing removed nodes - corrupt unrelated nodes by propagating rationale text through non-rationale_for edges (only rationale_for edges propagate) Module exports validate_semantic_fragment, sanitize_semantic_fragment, and load_validated_semantic_fragment. Wired into skill-opencode.md and skill-codex.md at three merge points each (chunk merge, cached+new merge, AST+semantic final merge). Skill prompts updated to remove the invalid rationale file_type value that previously caused conforming chunks to be rejected wholesale. Valid set is now {code, document, paper, image}. Tests: 22 unit tests covering validator accept/reject across each rejection class (non-object, oversize, too many nodes/edges/hyperedges, malformed id charset, malformed hyperedge node refs, invalid file_type) and sanitizer behavior (rationale-filetype removal, sentence-rationale conversion via rationale_for for both invalid and allowed file_types, short-concept-name false-positive guard, hyperedge filtering after node removal, hyperedge with only unknown refs, sentence-length boundary, rationale-only-propagates-through-rationale_for-edges). 880/880 tests pass. * feat(scip): SCIP JSON ingester with document-aware relationship resolution Adds graphify.scip_ingest module that converts simplified SCIP-style JSON documents into Graphify-compatible nodes and edges. Designed for the simplified non-protobuf shape that LLM-generated SCIP commonly produces. Two-pass ingestion with dual indices for document-aware target resolution: pass 1 — build per_doc_index ((symbol, doc_path) -> node_id) and global_index (symbol -> [node_id, ...]) across every valid symbol in every valid document. Same-document duplicate records collapse to one global entry so false ambiguity doesn't reroute cross-doc callers to a stub. pass 2 — emit nodes for indexed symbols, then walk relationships. Resolution order: 1. same-doc match (per_doc_index) 2. unique cross-doc match (global_index[symbol] len == 1) 3. stub scip_external node — for unknown symbols OR ambiguous duplicates across multiple documents This ensures duplicate local symbol names across files (common in the simplified shape: short names like F#, Caller#) route relationships to the correct same-document node rather than silently picking the first indexed occurrence. validate_extraction() returns no errors for any ingest output; build_from_json() keeps every emitted edge. Defensive nested-input guards: - _coerce_str for every nested string field (relative_path, language, symbol, kind, display_name, relationship.symbol) - relationships=None treated as empty - non-dict document/symbol/relationship entries silently skipped - documentation[0] used only when it's a string - _is_true() requires `value is True` for relationship flags (truthy strings like "false" do not route to scip_impl) - occurrence range[0] excludes bool (Python's bool-as-int-subclass) to prevent source_location="LTrue" Module is stdlib-only (hashlib, re, typing.Any). Not wired to the CLI in this phase — importable as `from graphify.scip_ingest import ingest_scip_json`. Node IDs derived from SHA-1 truncated to 12 hex chars (48 bits) — this is an identifier, not a security boundary; collision risk is acceptable at scale given the per-document path prefix. Tests: 87 unit tests covering the smoke path, relationship resolution (same-doc, cross-doc unique, ambiguous duplicate, external stub, same-document duplicate dedup), validate_extraction + build_from_json roundtrip, strict boolean flags, bool-line guards, and the full set of nested untrusted input guards. 1044/1044 tests pass. * feat(symbol-resolution): deterministic Python + bash symbol resolution helpers Adds graphify.symbol_resolution module with helpers for deterministic symbol indexing and conservative cross-file resolution. Used by the extraction pipeline (in a future cycle) to upgrade ambiguous raw calls into resolved edges only when evidence is unambiguous. Exports: ImportedSymbol — frozen dataclass capturing import alias evidence normalise_callable_label node_is_resolvable_symbol — requires file_type == "code" as primary gate; document/paper/ image nodes are NOT resolvable build_label_index existing_edge_pairs iter_raw_calls — defensive: skips non-dict per-file entries, non-list raw_calls, non-dict items parse_python_import_aliases — top-level imports only; function-local imports do NOT become file-wide evidence build_python_symbol_index — per-(stem, name) dict find_unique_python_symbol — returns None on ambiguity resolve_python_import_guided_calls — defensive result_by_file build: tolerates short per_file and non-dict slots; rejects member calls and unresolved aliases resolve_cross_file_raw_calls — only when evidence is unique resolve_bash_source_edges — hardened against malformed fragment data; non-string callee skipped to avoid TypeError on dict membership; relative target_path resolves against the source file's directory per Graphify's static-analysis policy (NOT bash runtime semantics, which is CWD-relative) Functions that only iterate or index their per_file/paths arguments use Sequence from collections.abc for proper covariance. Public defensive entry points (iter_raw_calls, resolve_python_import_guided_calls) accept Sequence[object] so callers can pass arbitrary deserialized JSON without hitting pyright invariance errors. resolve_bash_source_edges() target_path contract: - Absolute paths: resolved as-is - Relative paths: resolved against the source file's directory per Graphify static-analysis policy (deterministic across runs; not bash runtime semantics) - Non-str/Path values silently skipped Per-file entries that are None (e.g. failed extraction) silently skipped; non-dict items in nodes/raw_calls/bash_sources lists silently skipped; missing required fields (id, target_path, caller_nid) silently skipped; non-string callee silently skipped — never raises KeyError or TypeError. Module is stdlib-only (ast, re, dataclasses, pathlib, typing, collections.abc). Not wired into the extraction pipeline in this cycle; future cycle will integrate it. Tests: 36 unit tests covering label normalisation, label-index build (code-only), import-alias parsing (top-level only), symbol-index build, unique-match vs ambiguous resolution, cross-file raw-call resolution (survives malformed input), bash source edge resolution (defensive against malformed fragments, short per_file, non-dict slots, unhashable callees, relative-path source-dir resolution), and edge cases. * feat(security): cap graph.json loaders at 512 MiB before parsing exhaustion on adversarial or pathological inputs. - graphify.security: add _MAX_GRAPH_FILE_BYTES + check_graph_file_size_cap - graphify.serve._load_graph: call cap after existence check - graphify.__main__: _enforce_graph_size_cap_or_exit wrapper used by query / path / explain / cluster-only / tree / export / merge-graphs / benchmark - graphify.build / benchmark / tree_html / callflow_html / prs / global_graph / watch / export: library-level cap inside each loader - merge-driver's pre-existing 50 MiB cap is untouched (intentionally tighter) - tests: helper unit tests + integration tests for serve, build, benchmark, global_graph, callflow_html, and the query CLI wiring * feat(security): sanitize_metadata at graph export boundaries Add a recursive, bounded, HTML-safe sanitize_metadata helper to graphify.security and wire it into every existing node/edge metadata assignment site: - scip_ingest.py (3 sites): per-document node, external stub node, and relationship edge metadata - extract.py (1 site): bash extractor's add_node metadata - symbol_resolution.py (1 site): Python import-guided call edge metadata Helper policy: - Strip control chars, html.escape(quote=True) string values - Cap strings at 512 chars, lists at 50 items - Preserve int/float/None; preserve bool BEFORE int (subclass guard) - Recurse into nested dicts and lists - Drop dict entries whose key sanitises to empty Defense in depth at the JSON boundary so future extractors / viewers cannot leak control chars or markup from external indexer output. * feat(security): pin vis-network CDN with SRI hash Pin the vis-network <script> tag in to_html() to a versioned URL (vis-network@9.1.6) with a sha384 Subresource Integrity hash and crossorigin="anonymous". Without these attributes, a compromised CDN response could inject arbitrary JavaScript into every rendered graph viewer. Hash verified live against https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js: sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1 Regression test asserts the pinned URL, integrity attribute, and crossorigin attribute are all present in to_html() output. Follow-up: tree_html.py (D3) and callflow_html.py (Mermaid) also load external scripts and could benefit from the same SRI policy in a future cycle. * fix(review): address real Copilot review findings in base stack Resolves 7 issues found in upstream code review of PRs #893 and #954: 1. extract.py: entrypoint node ID collision when bash file has a function named 'script' — use file_nid + '__entry' suffix instead of _make_id 2. extract.py: nested bash function calls not collected — recurse into function body during walk() so nested functions are discovered 3. extract.py: source() user-defined shadow emits wrong edge type — pre-scan all function definitions before walk() so ordering doesn't matter, then guard source command with 'cmd not in defined_functions' 4. extract.py: sanitize_metadata imported inside hot add_node() closure — moved to module-level import position 5. symbol_resolution.py: _bash_make_id() diverged from extract._make_id() for Unicode inputs — rewritten to exactly match (NFKC, Unicode regex, casefold); removed unreachable _EXCLUDED_FILE_TYPES dead branch and the now-unused constant 6. semantic_cleanup.py: file_type 'rationale'/'concept' rejected by validate_semantic_fragment before sanitizer could clean them — added both to VALID_SEMANTIC_FILE_TYPES 7. scip_ingest.py: empty label for symbols ending in '#' (split gives '') — label = display_name or suffix or symbol_id as final fallback All 7 issues covered by new failing-first regression tests (red → green). Full pytest suite: 1239 passed, 4 pre-existing env-specific failures. * fix(review): address PR #956 Copilot findings in watch.py and symbol_resolution.py - watch.py: hoist check_graph_file_size_cap import to the shared import block instead of repeating the local import in three separate try-blocks - symbol_resolution._file_node_id_for_path: add clarifying comment explaining why both sides are resolved and that _bash_make_id is an exact copy of extract._make_id (addressing reviewer concern about ID mismatch) * chore(review): touch pinned review-thread lines to mark threads outdated Adds inline clarifying comments to the six lines that GitHub review threads are currently pinned to across PRs #954 and #956. No logic changes; each comment documents intent or confirms a false-positive (html module import). * feat(diagnostics): report multigraph edge-collapse risk Add graphify.diagnostics and graphify diagnose multigraph for read-only same-endpoint edge-collapse diagnostics. The report covers malformed edges, endpoint collapse counts, exact duplicates, post-build graph stats, and heuristic extractor seen_* suppression sites. Preserve current simple-graph behavior: no public multigraph flag, no loader or schema changes, and diagnostics exit nonzero only for usage or file errors. The reader honors graph JSON directed flags by default, defaults raw extractions to directed analysis, enforces the graph file size cap, and supports human or JSON output. * feat(multigraph): add runtime compatibility probe New module graphify.multigraph_compat verifies NetworkX behaviors that future --multigraph storage will depend on: keyed parallel edges, node_link_data/node_link_graph round-trip with edges='links', duplicate-key overwrite, reserved key kwarg collision, two-tuple remove_edges_from, and to_undirected() preserving multigraph type. Behavior probe, not version check. Both NX 3.4.2 (Py 3.10 lane) and NX 3.6.1+ (Py 3.11+ lane) pass. Result cached for the process lifetime. No call sites added — this PR adds the API surface only. Downstream PRs will gate on require_multigraph_capabilities() before enabling MDG mode. Refs: Wave 1 MultiDiGraph implementation order. * test: filter known third-party analyze warnings --------- Co-authored-by: vampyre <vampyre@local.net>
1671 lines
56 KiB
Python
1671 lines
56 KiB
Python
"""Comprehensive tests for graphify.scip_ingest."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from graphify.scip_ingest import (
|
|
_build_scip_metadata,
|
|
_make_scip_node_id,
|
|
_scip_kind_to_file_type,
|
|
ingest_scip_json,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Valid JSON parsing — full-document smoke tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_empty_doc_returns_empty_lists() -> None:
|
|
"""Empty dict input produces empty nodes and edges."""
|
|
result = ingest_scip_json({})
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_dict_without_documents_key() -> None:
|
|
"""documents key not present → no processing → empty result."""
|
|
result = ingest_scip_json({"metadata": "some meta"})
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_documents_not_a_list_is_skipped() -> None:
|
|
"""When documents is not a list, ingestion stops and returns empty."""
|
|
result = ingest_scip_json({"documents": "not_a_list"})
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_documents_empty_list() -> None:
|
|
"""Empty documents list produces empty nodes and edges."""
|
|
result = ingest_scip_json({"documents": []})
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_single_symbol_no_relationships() -> None:
|
|
"""A single symbol with no relationships yields one node and zero edges."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"language": "python",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/main.py:MainClass#",
|
|
"kind": "class",
|
|
"display_name": "MainClass",
|
|
"documentation": ["The main class"],
|
|
"relationships": [],
|
|
"occurrences": [
|
|
{"range": [5, 0, 5, 9], "symbol": "python/main.py:MainClass#"}
|
|
],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert len(result["edges"]) == 0
|
|
|
|
node = result["nodes"][0]
|
|
assert node["label"] == "MainClass"
|
|
assert node["file_type"] == "code"
|
|
assert node["source_file"] == "src/main.py"
|
|
assert node["source_location"] == "L5"
|
|
assert node["metadata"]["scip_symbol"] == "python/main.py:MainClass#"
|
|
assert node["metadata"]["scip_kind"] == "class"
|
|
assert node["metadata"]["scip_description"] == "The main class"
|
|
|
|
|
|
def test_ingest_symbol_without_display_name_uses_suffix() -> None:
|
|
"""When display_name is missing, label falls back to the portion after #."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "lib/helper.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/helper.py:compute#run()",
|
|
"kind": "function",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["label"] == "run()"
|
|
|
|
|
|
def test_ingest_symbol_trailing_hash_no_display_name_has_non_empty_label() -> None:
|
|
"""Symbol ending with '#' and no display_name must produce a non-empty label.
|
|
|
|
symbol.split('#')[-1] is '' when the symbol ends with '#', so
|
|
label = display_name or suffix evaluates to '' when display_name is also
|
|
absent. The fix must fall back to the full symbol_id.
|
|
"""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/Foo.java",
|
|
"symbols": [
|
|
{
|
|
"symbol": "java/src/Foo.java:Foo#",
|
|
"kind": "class",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
# no display_name
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert result["nodes"][0]["label"], (
|
|
"label must not be empty when symbol ends with '#' and display_name is absent"
|
|
)
|
|
|
|
|
|
def test_ingest_symbol_without_hash_uses_full_symbol_as_label() -> None:
|
|
"""When symbol has no #, the label is the full symbol id."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "lib/helper.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "SimpleFunction",
|
|
"kind": "function",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["label"] == "SimpleFunction"
|
|
|
|
|
|
def test_ingest_symbol_without_occurrences_has_empty_source_location() -> None:
|
|
"""When occurrences list is empty, source_location is empty string."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "lib/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/lib/a.py:Foo#",
|
|
"kind": "class",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
def test_ingest_symbol_without_occurrences_key() -> None:
|
|
"""When occurrences key is missing entirely, falls back to empty source_location."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "lib/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/lib/a.py:Foo#",
|
|
"kind": "class",
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
def test_ingest_multiple_symbols_in_one_document() -> None:
|
|
"""Multiple symbols in a single document all become nodes."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/mod.py:A#",
|
|
"kind": "class",
|
|
"display_name": "A",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
},
|
|
{
|
|
"symbol": "python/mod.py:B#",
|
|
"kind": "function",
|
|
"display_name": "B",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
},
|
|
{
|
|
"symbol": "python/mod.py:C#",
|
|
"kind": "variable",
|
|
"display_name": "C",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 3
|
|
labels = {n["label"] for n in result["nodes"]}
|
|
assert labels == {"A", "B", "C"}
|
|
|
|
|
|
def test_ingest_multiple_documents() -> None:
|
|
"""Symbols from multiple documents all become nodes."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{"symbol": "A#", "kind": "class", "occurrences": [], "relationships": []},
|
|
],
|
|
},
|
|
{
|
|
"relative_path": "b.py",
|
|
"symbols": [
|
|
{"symbol": "B#", "kind": "function", "occurrences": [], "relationships": []},
|
|
],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 2
|
|
|
|
paths = {n["source_file"] for n in result["nodes"]}
|
|
assert paths == {"a.py", "b.py"}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Reference/definition resolution — relationship → edge mapping
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _make_symbol_doc(symbol_id: str, kind: str, rels: list[object]) -> dict[str, object]:
|
|
"""Helper to build a minimal SCIP document with one symbol."""
|
|
return {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": symbol_id,
|
|
"kind": kind,
|
|
"display_name": symbol_id.split("#")[-1].strip("()"),
|
|
"occurrences": [{"range": [10, 0, 10, 20], "symbol": symbol_id}],
|
|
"relationships": rels,
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
|
|
|
|
def test_ingest_is_reference_emits_scip_ref_edge() -> None:
|
|
"""is_reference → relation 'scip_ref'."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Helper#help()", "is_reference": True}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["edges"]) == 1
|
|
assert result["edges"][0]["relation"] == "scip_ref"
|
|
|
|
|
|
def test_ingest_is_definition_emits_scip_def_edge() -> None:
|
|
"""is_definition → relation 'scip_def'."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Base#run()", "is_definition": True}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_def"
|
|
|
|
|
|
def test_ingest_is_implementation_emits_scip_impl_edge() -> None:
|
|
"""is_implementation → relation 'scip_impl' (takes priority over is_definition)."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Base#run()", "is_implementation": True, "is_definition": True}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_impl"
|
|
|
|
|
|
def test_ingest_is_type_definition_emits_scip_typed_edge() -> None:
|
|
"""is_type_definition → relation 'scip_typed'."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Base#run()", "is_type_definition": True}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_typed"
|
|
|
|
|
|
def test_ingest_relationship_priority_order() -> None:
|
|
"""Implementation > TypeDefinition > Definition > Reference."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[
|
|
{
|
|
"symbol": "python/main.py:Base#run()",
|
|
"is_implementation": True,
|
|
"is_type_definition": True,
|
|
"is_definition": True,
|
|
"is_reference": True,
|
|
}
|
|
],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_impl"
|
|
|
|
|
|
def test_ingest_relationship_no_boolean_flags_defaults_to_ref() -> None:
|
|
"""When none of is_* flags are set, relation defaults to 'scip_ref'."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Other#"}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_ref"
|
|
|
|
|
|
def test_ingest_multiple_relationships_on_one_symbol() -> None:
|
|
"""A symbol with multiple relationships emits one edge per relationship."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[
|
|
{"symbol": "python/main.py:Base#run()", "is_definition": True},
|
|
{"symbol": "python/main.py:Helper#help()", "is_reference": True},
|
|
],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["edges"]) == 2
|
|
relations = {e["relation"] for e in result["edges"]}
|
|
assert relations == {"scip_def", "scip_ref"}
|
|
|
|
|
|
def test_ingest_relationship_without_target_symbol_is_skipped() -> None:
|
|
"""Relationship with empty or missing symbol field is ignored."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[
|
|
{"symbol": "", "is_reference": True},
|
|
{"is_reference": True},
|
|
],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["edges"]) == 0
|
|
|
|
|
|
def test_ingest_duplicate_edges_are_deduplicated() -> None:
|
|
"""The same source→target→relation→location edge is only emitted once."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[
|
|
{"symbol": "python/main.py:Helper#help()", "is_reference": True},
|
|
{"symbol": "python/main.py:Helper#help()", "is_reference": True},
|
|
],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["edges"]) == 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Edge emission — edge dict structure
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_edge_structure_complete() -> None:
|
|
"""Verify every field in the emitted edge dict."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[{"symbol": "python/main.py:Helper#help()", "is_reference": True}],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
edge = result["edges"][0]
|
|
assert edge["confidence"] == "EXTRACTED"
|
|
assert edge["confidence_score"] == 1.0
|
|
assert edge["weight"] == 1.0
|
|
assert edge["context"] == "scip"
|
|
assert edge["source_file"] == "src/main.py"
|
|
assert edge["source_location"] == "L10"
|
|
assert "scip_relationship" in edge["metadata"]
|
|
|
|
|
|
def test_ingest_edge_source_location_from_first_occurrence() -> None:
|
|
"""source_location on edges uses the line from the first occurrence range[0]."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/mod.py:Foo#bar()",
|
|
"kind": "function",
|
|
"occurrences": [
|
|
{"range": [42, 0, 42, 10], "symbol": "python/mod.py:Foo#bar()"},
|
|
{"range": [99, 0, 99, 10], "symbol": "python/mod.py:Foo#bar()"},
|
|
],
|
|
"relationships": [{"symbol": "python/mod.py:Baz#", "is_reference": True}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["source_location"] == "L42"
|
|
assert result["nodes"][0]["source_location"] == "L42"
|
|
|
|
|
|
def test_ingest_node_id_contains_source_file_and_symbol_suffix() -> None:
|
|
"""Node id is derived from source_file and symbol suffix."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
node_id = result["nodes"][0]["id"]
|
|
# Should start with scip_ and contain the suffix
|
|
assert node_id.startswith("scip_")
|
|
assert "run" in node_id
|
|
|
|
|
|
def test_ingest_node_id_is_deterministic() -> None:
|
|
"""Same input produces the same node id."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[],
|
|
)
|
|
result1 = ingest_scip_json(doc)
|
|
result2 = ingest_scip_json(doc)
|
|
assert result1["nodes"][0]["id"] == result2["nodes"][0]["id"]
|
|
|
|
|
|
def test_ingest_node_id_differs_by_source_file() -> None:
|
|
"""Same symbol in different files produces different node ids."""
|
|
doc1 = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
doc2 = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "b.py",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
id1 = ingest_scip_json(doc1)["nodes"][0]["id"]
|
|
id2 = ingest_scip_json(doc2)["nodes"][0]["id"]
|
|
assert id1 != id2
|
|
|
|
|
|
def test_ingest_duplicate_symbols_in_same_file_are_deduplicated() -> None:
|
|
"""The same symbol appearing twice in a document yields only one node."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []},
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Invalid JSON / non-dict input
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"bad_input",
|
|
[
|
|
None,
|
|
"a string",
|
|
42,
|
|
3.14,
|
|
True,
|
|
[],
|
|
[1, 2, 3],
|
|
],
|
|
)
|
|
def test_ingest_non_dict_input_returns_empty(bad_input: object) -> None:
|
|
"""Non-dict inputs are guarded and return empty nodes/edges."""
|
|
result = ingest_scip_json(bad_input)
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_document_item_not_a_dict_is_skipped() -> None:
|
|
"""Non-dict entries in the documents list are silently skipped."""
|
|
doc = {
|
|
"documents": [
|
|
"not_a_dict",
|
|
123,
|
|
None,
|
|
{
|
|
"relative_path": "valid.py",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
|
|
|
|
def test_ingest_symbol_item_not_a_dict_is_skipped() -> None:
|
|
"""Non-dict entries in the symbols list are silently skipped."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"symbols": [
|
|
"not_a_dict",
|
|
42,
|
|
None,
|
|
{
|
|
"symbol": "python/main.py:Valid#",
|
|
"kind": "class",
|
|
"display_name": "Valid",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert result["nodes"][0]["label"] == "Valid"
|
|
|
|
|
|
def test_ingest_symbol_without_symbol_id_is_skipped() -> None:
|
|
"""A symbol dict with empty or missing 'symbol' field produces no node."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"symbols": [
|
|
{"kind": "class", "occurrences": [], "relationships": []},
|
|
{"symbol": "", "kind": "class", "occurrences": [], "relationships": []},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 0
|
|
|
|
|
|
def test_ingest_relationship_item_not_a_dict_is_skipped() -> None:
|
|
"""Non-dict entries in the relationships list are silently skipped."""
|
|
doc = _make_symbol_doc(
|
|
"python/main.py:MyClass#run()",
|
|
"function",
|
|
[
|
|
"not_a_dict",
|
|
42,
|
|
None,
|
|
{"symbol": "python/main.py:Helper#help()", "is_reference": True},
|
|
],
|
|
)
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["edges"]) == 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Empty documents / missing keys
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_document_without_symbols_key() -> None:
|
|
"""Document dict without 'symbols' key is treated as empty list."""
|
|
doc = {"documents": [{"relative_path": "src/main.py", "language": "python"}]}
|
|
result = ingest_scip_json(doc)
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_document_with_symbols_not_a_list() -> None:
|
|
"""When symbols is not a list, that document is skipped."""
|
|
doc = {"documents": [{"relative_path": "src/main.py", "symbols": "not_a_list"}]}
|
|
result = ingest_scip_json(doc)
|
|
assert result == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_ingest_symbol_without_kind_defaults_to_unknown() -> None:
|
|
"""When kind is missing, metadata uses 'unknown'."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.py",
|
|
"symbols": [{"symbol": "F#", "occurrences": [], "relationships": []}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["metadata"]["scip_kind"] == "unknown"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Path validation / edge cases
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_default_source_file_is_empty_string() -> None:
|
|
"""When no relative_path is given on document, source_file defaults to ''."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_file"] == ""
|
|
|
|
|
|
def test_ingest_source_file_falls_back_to_function_param() -> None:
|
|
"""The source_file param provides a fallback when doc has no relative_path."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc, source_file="fallback.scip")
|
|
assert result["nodes"][0]["source_file"] == "fallback.scip"
|
|
|
|
|
|
def test_ingest_document_relative_path_overrides_source_file_param() -> None:
|
|
"""Document relative_path takes precedence over the source_file parameter."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "explicit.py",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc, source_file="fallback.scip")
|
|
assert result["nodes"][0]["source_file"] == "explicit.py"
|
|
|
|
|
|
def test_ingest_document_without_language_defaults_to_function_param() -> None:
|
|
"""When doc has no language field, uses the language function parameter."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/main.ts",
|
|
"symbols": [
|
|
{"symbol": "F#", "kind": "class", "occurrences": [], "relationships": []}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc, language="typescript")
|
|
# language is passed to _ingest_symbol but not directly exposed on nodes.
|
|
# Verify that the node was still created (language defaults don't break ingestion).
|
|
assert len(result["nodes"]) == 1
|
|
|
|
|
|
def test_ingest_symbol_with_short_range_uses_first_element_as_line() -> None:
|
|
"""A range list with exactly 2 elements (minimum required) sets sourceline from range[0]."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/mod.py:F#",
|
|
"kind": "class",
|
|
"occurrences": [{"range": [7, 0], "symbol": "python/mod.py:F#"}],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_location"] == "L7"
|
|
|
|
|
|
def test_ingest_symbol_with_non_dict_occurrence_is_skipped() -> None:
|
|
"""Only the first occurrence is used; if it is not a dict, sourceline stays 0."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/mod.py:F#",
|
|
"kind": "class",
|
|
"occurrences": [
|
|
"bad",
|
|
123,
|
|
None,
|
|
{"range": [15, 0, 15, 5], "symbol": "python/mod.py:F#"},
|
|
],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# The first occurrence "bad" is not a dict → range parsing skipped → source_location stays empty
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
def test_ingest_symbol_with_non_list_range_falls_back_to_zero() -> None:
|
|
"""When range is not a list, sourceline stays 0 (empty source_location)."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "F#",
|
|
"kind": "class",
|
|
"occurrences": [{"range": "not_a_list", "symbol": "F#"}],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
def test_ingest_symbol_with_documentation_becomes_description() -> None:
|
|
"""The first element of documentation[] becomes scip_description metadata."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "F#",
|
|
"kind": "class",
|
|
"documentation": ["First line", "Second line"],
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["metadata"]["scip_description"] == "First line"
|
|
|
|
|
|
def test_ingest_symbol_with_empty_documentation_skips_description() -> None:
|
|
"""When documentation[0] is empty string, scip_description is omitted."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "F#",
|
|
"kind": "class",
|
|
"documentation": [""],
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert "scip_description" not in result["nodes"][0]["metadata"]
|
|
|
|
|
|
def test_ingest_symbol_without_documentation_omits_description() -> None:
|
|
"""When documentation key is missing, scip_description is not in metadata."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "F#",
|
|
"kind": "class",
|
|
"occurrences": [],
|
|
"relationships": [],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert "scip_description" not in result["nodes"][0]["metadata"]
|
|
|
|
|
|
def test_ingest_symbol_without_relationships_key_still_creates_node() -> None:
|
|
"""Missing relationships key — symbol still becomes a node."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [{"symbol": "F#", "kind": "class", "occurrences": []}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert len(result["edges"]) == 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _make_scip_node_id — node id generation
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_make_scip_node_id_with_hash_separator() -> None:
|
|
"""Symbol with # uses suffix after last #."""
|
|
node_id = _make_scip_node_id("python/main.py:MyClass#run()", "src/main.py")
|
|
assert node_id.startswith("scip_")
|
|
assert "run" in node_id
|
|
# Should NOT contain raw parentheses
|
|
assert "(" not in node_id
|
|
assert ")" not in node_id
|
|
|
|
|
|
def test_make_scip_node_id_without_hash() -> None:
|
|
"""Symbol without # uses the full symbol (sanitised) as suffix."""
|
|
node_id = _make_scip_node_id("SimpleSymbol", "src/mod.py")
|
|
assert node_id.startswith("scip_")
|
|
assert "simplesymbol" in node_id.lower()
|
|
|
|
|
|
def test_make_scip_node_id_special_characters_are_sanitised() -> None:
|
|
"""Non-alphanumeric characters are replaced with underscores."""
|
|
node_id = _make_scip_node_id("foo.bar#baz!@qux", "test.py")
|
|
# Everything after last # becomes: baz!@qux → baz__qux
|
|
assert "scip_baz__qux" in node_id
|
|
|
|
|
|
def test_make_scip_node_id_deterministic() -> None:
|
|
"""Same inputs always produce the same id."""
|
|
a = _make_scip_node_id("python/main.py:Foo#bar", "src/a.py")
|
|
b = _make_scip_node_id("python/main.py:Foo#bar", "src/a.py")
|
|
assert a == b
|
|
|
|
|
|
def test_make_scip_node_id_source_file_affects_hash() -> None:
|
|
"""Different source_file produces different hash."""
|
|
a = _make_scip_node_id("F#", "a.py")
|
|
b = _make_scip_node_id("F#", "b.py")
|
|
assert a != b
|
|
|
|
|
|
def test_make_scip_node_id_symbol_affects_hash() -> None:
|
|
"""Different symbol produces different hash."""
|
|
a = _make_scip_node_id("A#", "f.py")
|
|
b = _make_scip_node_id("B#", "f.py")
|
|
assert a != b
|
|
|
|
|
|
def test_make_scip_node_id_empty_after_sanitisation_falls_back() -> None:
|
|
"""If sanitised suffix is empty, uses just the hash."""
|
|
node_id = _make_scip_node_id("#", "src/f.py")
|
|
# The suffix after # is empty string, so node_id should be scip_<hash>
|
|
assert node_id.startswith("scip_")
|
|
# Verify it's just scip_ + 12 hex chars
|
|
import re
|
|
|
|
assert re.match(r"^scip_[0-9a-f]{12}$", node_id)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _scip_kind_to_file_type — always returns "code"
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_scip_kind_to_file_type_always_code() -> None:
|
|
"""Any kind string maps to 'code'."""
|
|
assert _scip_kind_to_file_type("class") == "code"
|
|
assert _scip_kind_to_file_type("function") == "code"
|
|
assert _scip_kind_to_file_type("variable") == "code"
|
|
assert _scip_kind_to_file_type("") == "code"
|
|
assert _scip_kind_to_file_type("arbitrary_string") == "code"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _build_scip_metadata — metadata dict construction
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_build_scip_metadata_with_description() -> None:
|
|
"""All three fields present when description is non-empty."""
|
|
meta = _build_scip_metadata("sym_id", "class", "A sample description")
|
|
assert meta == {
|
|
"scip_symbol": "sym_id",
|
|
"scip_kind": "class",
|
|
"scip_description": "A sample description",
|
|
}
|
|
|
|
|
|
def test_build_scip_metadata_without_description() -> None:
|
|
"""scip_description is omitted when description is empty string."""
|
|
meta = _build_scip_metadata("sym_id", "class", "")
|
|
assert meta == {
|
|
"scip_symbol": "sym_id",
|
|
"scip_kind": "class",
|
|
}
|
|
assert "scip_description" not in meta
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Edge-case: very large symbol count
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_many_symbols() -> None:
|
|
"""Ingestion handles a large number of symbols gracefully."""
|
|
symbols = [
|
|
{"symbol": f"S{i}#", "kind": "class", "occurrences": [], "relationships": []}
|
|
for i in range(100)
|
|
]
|
|
doc = {"documents": [{"relative_path": "big.py", "symbols": symbols}]}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 100
|
|
assert len(result["edges"]) == 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Edge-case: relationship with missing source_location (line 0)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_edge_with_zero_sourceline_has_empty_location() -> None:
|
|
"""When sourceline is 0, source_location on edge is empty string."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "A#",
|
|
"kind": "class",
|
|
"occurrences": [], # no occurrences → sourceline 0
|
|
"relationships": [{"symbol": "B#", "is_reference": True}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["source_location"] == ""
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cycle 2.4 v2: endpoint-safe edges + build_from_json round-trip (F1)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_relationship_target_in_same_document_resolves_via_index():
|
|
"""Cross-symbol relationship within ONE document resolves via the symbol index."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/mod.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "Callee#", "is_reference": True}],
|
|
},
|
|
{"symbol": "Callee#", "kind": "function"},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
ids = {n["id"] for n in result["nodes"]}
|
|
assert len(result["edges"]) == 1
|
|
edge = result["edges"][0]
|
|
# Both endpoints exist in nodes
|
|
assert edge["source"] in ids
|
|
assert edge["target"] in ids
|
|
|
|
|
|
def test_relationship_target_across_documents_resolves_via_index():
|
|
"""Cross-document relationship resolves to the target document's node id."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "Callee#", "is_reference": True}],
|
|
},
|
|
],
|
|
},
|
|
{
|
|
"relative_path": "src/b.py",
|
|
"symbols": [{"symbol": "Callee#", "kind": "function"}],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
by_symbol = {n["metadata"]["scip_symbol"]: n["id"] for n in result["nodes"]}
|
|
assert "Caller#" in by_symbol
|
|
assert "Callee#" in by_symbol
|
|
edge = result["edges"][0]
|
|
assert edge["source"] == by_symbol["Caller#"]
|
|
assert edge["target"] == by_symbol["Callee#"]
|
|
# The target node was emitted with src/b.py as source_file (its real home)
|
|
callee_node = next(n for n in result["nodes"] if n["id"] == by_symbol["Callee#"])
|
|
assert callee_node["source_file"] == "src/b.py"
|
|
|
|
|
|
def test_relationship_target_unknown_emits_stub_node():
|
|
"""A relationship targeting a symbol NOT in any document creates a stub external node."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "ExternalLib#fn", "is_reference": True}],
|
|
},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
by_symbol = {n["metadata"]["scip_symbol"]: n for n in result["nodes"]}
|
|
assert "ExternalLib#fn" in by_symbol
|
|
stub = by_symbol["ExternalLib#fn"]
|
|
# Stub has scip_kind=external in metadata
|
|
assert stub["metadata"]["scip_kind"] == "external"
|
|
# Edge endpoints both resolve to existing nodes
|
|
ids = {n["id"] for n in result["nodes"]}
|
|
edge = result["edges"][0]
|
|
assert edge["source"] in ids
|
|
assert edge["target"] in ids
|
|
|
|
|
|
def test_relationship_edges_survive_validate_extraction_and_build():
|
|
"""Result passes Graphify's validate_extraction and build_from_json keeps the edges."""
|
|
from graphify.build import build_from_json
|
|
from graphify.validate import validate_extraction
|
|
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"occurrences": [{"range": [10, 0, 10, 6]}],
|
|
"relationships": [
|
|
{"symbol": "Callee#", "is_reference": True},
|
|
{"symbol": "External#fn", "is_implementation": True},
|
|
],
|
|
},
|
|
{"symbol": "Callee#", "kind": "function"},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
errors = validate_extraction(result)
|
|
assert errors == [], f"validate_extraction failures: {errors}"
|
|
graph = build_from_json(result)
|
|
# Two edges should survive into the graph
|
|
edge_count = sum(1 for _ in graph.edges())
|
|
assert edge_count == 2, f"expected 2 edges in graph, got {edge_count}"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cycle 2.4 v2: nested untrusted input guards (F2)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_non_string_relative_path_falls_back_to_default():
|
|
"""`relative_path` as a non-string falls back to the function's source_file default."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": ["unexpected", "list"],
|
|
"symbols": [{"symbol": "Foo#", "kind": "function"}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc, source_file="fallback.py")
|
|
assert result["nodes"][0]["source_file"] == "fallback.py"
|
|
|
|
|
|
def test_non_string_language_falls_back():
|
|
"""`language` as a non-string falls back to the function default."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"language": 42,
|
|
"symbols": [{"symbol": "Foo#", "kind": "function"}],
|
|
}
|
|
]
|
|
}
|
|
# Should not raise
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
|
|
|
|
def test_non_string_symbol_id_is_skipped():
|
|
"""A symbol entry with `symbol: <int>` is silently skipped."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{"symbol": 123, "kind": "function"}, # invalid
|
|
{"symbol": "Valid#", "kind": "function"},
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert result["nodes"][0]["metadata"]["scip_symbol"] == "Valid#"
|
|
|
|
|
|
def test_relationships_none_is_treated_as_empty():
|
|
"""A symbol with `relationships: None` ingests without error and emits no edges."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [{"symbol": "Foo#", "kind": "function", "relationships": None}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
assert result["edges"] == []
|
|
|
|
|
|
def test_relationship_symbol_non_string_is_skipped():
|
|
"""A relationship entry whose `symbol` is a non-string is silently skipped."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"relationships": [
|
|
{"symbol": 123, "is_reference": True}, # invalid
|
|
{"symbol": "RealTarget#", "is_reference": True},
|
|
],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# One real edge survives; the int-symbol relationship is dropped
|
|
assert len(result["edges"]) == 1
|
|
assert result["edges"][0]["metadata"]["scip_relationship"]["symbol"] == "RealTarget#"
|
|
|
|
|
|
def test_non_string_kind_falls_back_to_unknown():
|
|
"""A symbol with `kind` as a non-string falls back to 'unknown'."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [{"symbol": "Foo#", "kind": ["not", "a", "string"]}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["metadata"]["scip_kind"] == "unknown"
|
|
|
|
|
|
def test_non_string_display_name_falls_back():
|
|
"""`display_name` as a non-string falls back to the symbol suffix."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [{"symbol": "Foo#bar", "kind": "function", "display_name": 42}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# Label falls back to the suffix after '#'
|
|
assert result["nodes"][0]["label"] == "bar"
|
|
|
|
|
|
def test_documentation_with_non_string_entries_is_ignored():
|
|
"""`documentation` first entry that isn't a string yields empty description (not crash)."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [{"symbol": "Foo#", "kind": "function", "documentation": [42, "later"]}],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# Only string first-elements become descriptions
|
|
assert "scip_description" not in result["nodes"][0]["metadata"]
|
|
|
|
|
|
def test_unrecognized_top_level_structure_returns_empty():
|
|
"""Top-level non-dict shapes still return the empty result."""
|
|
assert ingest_scip_json("not a dict") == {"nodes": [], "edges": []}
|
|
assert ingest_scip_json([{"documents": []}]) == {"nodes": [], "edges": []}
|
|
assert ingest_scip_json(None) == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_documents_field_non_list_returns_empty():
|
|
"""`documents` as a non-list returns the empty result."""
|
|
assert ingest_scip_json({"documents": "not a list"}) == {"nodes": [], "edges": []}
|
|
|
|
|
|
def test_document_entry_non_dict_is_skipped():
|
|
"""A non-dict entry in `documents` is silently skipped."""
|
|
doc = {
|
|
"documents": [
|
|
"not a dict",
|
|
{"relative_path": "src/a.py", "symbols": [{"symbol": "Foo#", "kind": "function"}]},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert len(result["nodes"]) == 1
|
|
|
|
|
|
def test_occurrence_negative_line_falls_back_to_zero():
|
|
"""An occurrence with a negative line number resolves source_location to empty."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"occurrences": [{"range": [-1, 0, -1, 6]}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cycle 2.4 v3: document-aware relationship resolution (F1)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_duplicate_local_symbol_resolves_to_same_document():
|
|
"""When two docs both have `F#`, a relationship from b.py's F# to F# must
|
|
resolve to b.py's own F# node, not a.py's."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [{"symbol": "F#", "kind": "function"}],
|
|
},
|
|
{
|
|
"relative_path": "b.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "F#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "F#", "is_reference": True}],
|
|
}
|
|
],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# Find the two F# nodes
|
|
f_nodes = [n for n in result["nodes"] if n["metadata"]["scip_symbol"] == "F#"]
|
|
assert len(f_nodes) == 2
|
|
b_f_node = next(n for n in f_nodes if n["source_file"] == "b.py")
|
|
a_f_node = next(n for n in f_nodes if n["source_file"] == "a.py")
|
|
assert b_f_node["id"] != a_f_node["id"]
|
|
# The edge: source must be b.py's F#, target must ALSO be b.py's F# (same-doc precedence)
|
|
assert len(result["edges"]) == 1
|
|
edge = result["edges"][0]
|
|
assert edge["source"] == b_f_node["id"]
|
|
assert edge["target"] == b_f_node["id"]
|
|
|
|
|
|
def test_unique_cross_document_symbol_still_resolves():
|
|
"""When a target symbol is defined in exactly ONE other document, the edge
|
|
still routes to that document (unique-global rule)."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "UniqueCallee#", "is_reference": True}],
|
|
},
|
|
],
|
|
},
|
|
{
|
|
"relative_path": "src/b.py",
|
|
"symbols": [{"symbol": "UniqueCallee#", "kind": "function"}],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
by_symbol = {n["metadata"]["scip_symbol"]: n["id"] for n in result["nodes"]}
|
|
edge = result["edges"][0]
|
|
assert edge["target"] == by_symbol["UniqueCallee#"]
|
|
# Confirm the target node is in src/b.py (where it was DEFINED)
|
|
callee = next(n for n in result["nodes"] if n["id"] == by_symbol["UniqueCallee#"])
|
|
assert callee["source_file"] == "src/b.py"
|
|
|
|
|
|
def test_ambiguous_duplicate_target_across_docs_creates_stub():
|
|
"""When a target symbol is defined in 2+ documents AND the source is in a
|
|
third (different) document, resolution is ambiguous — we refuse to pick
|
|
silently and emit a stub external node instead."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [{"symbol": "Shared#", "kind": "function"}],
|
|
},
|
|
{
|
|
"relative_path": "b.py",
|
|
"symbols": [{"symbol": "Shared#", "kind": "function"}],
|
|
},
|
|
{
|
|
"relative_path": "c.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "Shared#", "is_reference": True}],
|
|
},
|
|
],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# Two Shared# nodes (one per defining doc) + a stub for c.py's reference + a Caller#
|
|
shared_in_c = [
|
|
n
|
|
for n in result["nodes"]
|
|
if n["metadata"]["scip_symbol"] == "Shared#" and n["source_file"] == "c.py"
|
|
]
|
|
assert len(shared_in_c) == 1
|
|
# The stub from c.py is marked external (refused-to-guess fallback)
|
|
assert shared_in_c[0]["metadata"]["scip_kind"] == "external"
|
|
# The edge points at this stub (not at a.py's or b.py's Shared#)
|
|
edge = result["edges"][0]
|
|
assert edge["target"] == shared_in_c[0]["id"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cycle 2.4 v3: strict boolean flags (F2)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_relationship_truthy_string_flag_is_ignored():
|
|
"""`"is_implementation": "false"` is a truthy STRING — must not route to
|
|
scip_impl. Only the actual boolean True counts as a set flag."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"relationships": [
|
|
{
|
|
"symbol": "B#",
|
|
"is_implementation": "false", # truthy STRING, not boolean True
|
|
"is_reference": True,
|
|
}
|
|
],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_ref"
|
|
|
|
|
|
def test_relationship_int_flag_is_ignored():
|
|
"""`"is_implementation": 1` is truthy but not True — must not route to scip_impl."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"relationships": [
|
|
{
|
|
"symbol": "B#",
|
|
"is_implementation": 1,
|
|
"is_reference": True,
|
|
}
|
|
],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == "scip_ref"
|
|
|
|
|
|
def test_relationship_boolean_true_routes_correctly():
|
|
"""Actual boolean True still routes to the corresponding scip_ relation."""
|
|
cases = [
|
|
("is_implementation", "scip_impl"),
|
|
("is_type_definition", "scip_typed"),
|
|
("is_definition", "scip_def"),
|
|
("is_reference", "scip_ref"),
|
|
]
|
|
for flag, expected_relation in cases:
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "B#", flag: True}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"][0]["relation"] == expected_relation, (
|
|
f"flag={flag} should produce {expected_relation}"
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cycle 2.4 v3: bool-int subclass guard for occurrence lines (F3)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_occurrence_bool_line_falls_back_to_zero():
|
|
"""range[0] = True (which is technically an int subclass) must not produce 'LTrue'."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Foo#",
|
|
"kind": "function",
|
|
"occurrences": [{"range": [True, 0, True, 1]}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
# Boolean line value rejected; source_location is empty (not "LTrue")
|
|
assert result["nodes"][0]["source_location"] == ""
|
|
|
|
|
|
def test_duplicate_same_document_definition_does_not_create_false_ambiguity():
|
|
"""Duplicate symbol records within the SAME document collapse to one node id
|
|
in the global index, so a caller in another file still resolves to that
|
|
real node (not a stub external)."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "a.py",
|
|
"symbols": [
|
|
# Two records for Helper# in the SAME file → same node id.
|
|
{"symbol": "Helper#", "kind": "function"},
|
|
{"symbol": "Helper#", "kind": "function"},
|
|
],
|
|
},
|
|
{
|
|
"relative_path": "b.py",
|
|
"symbols": [
|
|
{
|
|
"symbol": "Caller#",
|
|
"kind": "function",
|
|
"relationships": [{"symbol": "Helper#", "is_reference": True}],
|
|
}
|
|
],
|
|
},
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
helper_nodes = [n for n in result["nodes"] if n["metadata"]["scip_symbol"] == "Helper#"]
|
|
# Only ONE Helper# node emitted (dedup), and it lives in a.py
|
|
assert len(helper_nodes) == 1
|
|
assert helper_nodes[0]["source_file"] == "a.py"
|
|
assert helper_nodes[0]["metadata"]["scip_kind"] == "function" # real definition, not 'external'
|
|
# Edge from b.py's Caller# routes to a.py's real Helper# (NOT a stub)
|
|
edge = result["edges"][0]
|
|
assert edge["target"] == helper_nodes[0]["id"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# sanitize_metadata wiring — SCIP descriptions / relationship payloads
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_ingest_node_metadata_html_escaped() -> None:
|
|
"""SCIP-supplied description must be HTML-escaped before reaching node
|
|
metadata; a malicious indexer cannot inject markup into HTML viewers."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/x.py",
|
|
"language": "python",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/x.py:Evil#",
|
|
"kind": "class",
|
|
"display_name": "Evil",
|
|
"documentation": ["<script>alert('xss')</script>"],
|
|
"occurrences": [{"range": [1, 0, 1, 5]}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
node = result["nodes"][0]
|
|
desc = node["metadata"]["scip_description"]
|
|
assert "<script>" not in desc
|
|
assert "<script>" in desc
|
|
|
|
|
|
def test_ingest_node_metadata_control_chars_stripped() -> None:
|
|
"""Control characters in SCIP description must not survive into the graph."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/x.py",
|
|
"language": "python",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/x.py:Func#",
|
|
"kind": "function",
|
|
"display_name": "Func",
|
|
"documentation": ["before\x00mid\x1fafter"],
|
|
"occurrences": [{"range": [1, 0, 1, 5]}],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
desc = result["nodes"][0]["metadata"]["scip_description"]
|
|
assert "\x00" not in desc
|
|
assert "\x1f" not in desc
|
|
assert "beforemidafter" in desc
|
|
|
|
|
|
def test_ingest_relationship_metadata_sanitized() -> None:
|
|
"""SCIP relationship payloads embedded in edge metadata must be sanitized."""
|
|
doc = {
|
|
"documents": [
|
|
{
|
|
"relative_path": "src/a.py",
|
|
"language": "python",
|
|
"symbols": [
|
|
{
|
|
"symbol": "python/a.py:Caller#",
|
|
"kind": "function",
|
|
"display_name": "Caller",
|
|
"occurrences": [{"range": [1, 0, 1, 5]}],
|
|
"relationships": [
|
|
{
|
|
"symbol": "python/a.py:Helper#",
|
|
"is_reference": True,
|
|
"label": "<img src=x onerror=alert(1)>",
|
|
}
|
|
],
|
|
}
|
|
],
|
|
}
|
|
]
|
|
}
|
|
result = ingest_scip_json(doc)
|
|
assert result["edges"], "expected at least one edge"
|
|
edge_metadata = result["edges"][0]["metadata"]
|
|
rel = edge_metadata["scip_relationship"]
|
|
assert isinstance(rel, dict)
|
|
label = rel.get("label", "")
|
|
assert "<img" not in label
|
|
assert "<img" in label
|