"""Tests for the BackLinks derived view (SHARD-WP-0010 T2).""" from shard_wiki.adapters import FolderAdapter from shard_wiki.model import Identity from shard_wiki.union import UnionGraph from shard_wiki.views import build_backlinks def _shard(tmp_path, name, files): root = tmp_path / name for rel, text in files.items(): p = root / rel p.parent.mkdir(parents=True, exist_ok=True) p.write_text(text, encoding="utf-8") return FolderAdapter(name, root) def test_link_yields_backlink_with_provenance(tmp_path): u = UnionGraph("space") u.attach(_shard(tmp_path, "shardA", {"A.md": "see [[B]]", "B.md": "target"})) index = build_backlinks(u) assert index.sources("B") == frozenset({Identity("shardA", "A")}) (bl,) = index.to("B") assert bl.source_shard == "shardA" # entry carries source provenance def test_red_links_create_no_backlinks(tmp_path): u = UnionGraph("space") u.attach(_shard(tmp_path, "shardA", {"A.md": "see [[Ghost]]"})) index = build_backlinks(u) assert index.to("Ghost") == () # unresolved target → no backlink assert "Ghost" not in index.names() def test_chorus_target_aggregates_backlinks(tmp_path): # "Home" exists in two shards (a chorus); links to it from anywhere aggregate under one name. u = UnionGraph("space") u.attach(_shard(tmp_path, "shardA", {"Home.md": "A home", "A.md": "[[Home]]"})) u.attach(_shard(tmp_path, "shardB", {"Home.md": "B home", "B.md": "[[Home]]"})) index = build_backlinks(u) assert index.sources("Home") == frozenset( {Identity("shardA", "A"), Identity("shardB", "B")} ) def test_backlinks_span_shards(tmp_path): u = UnionGraph("space") u.attach(_shard(tmp_path, "shardA", {"Index.md": "x"})) u.attach(_shard(tmp_path, "shardB", {"B.md": "links [[Index]]"})) index = build_backlinks(u) assert index.sources("Index") == frozenset({Identity("shardB", "B")})