ReMe/tests/unit/test_wikilink_utils.py
jinliyl a597d1a355
Some checks failed
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
CI and Release / Docker / Build and test / amd64 (push) Waiting to run
CI and Release / Docker / Build and test / arm64 (push) Waiting to run
CI and Release / Docker / Publish multi-platform tags (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Has been cancelled
refactor: simplify async tests and shared response rendering (#662)
2026-10-23 13:10:45 +08:00

339 lines
13 KiB
Python

"""Tests for wikilink helpers in ``reme.utils.wikilink_handler``.
Two pure async helpers used by file_move / file_delete:
* ``retarget_links(src, dst, scope?, dry_run?)`` — rewrite wikilink
targets across the workspace, using the file_graph's reverse index to
find inbound sources (no fs scan).
* ``find_inbound(target, scope?)`` — report inbound count without
rewriting.
Retarget only matches the literal full-path form ``[[topics/x.md]]``;
short ``[[x]]`` and no-ext ``[[topics/x]]`` are left alone by design.
"""
# pylint: disable=protected-access
from contextlib import chdir as temp_chdir
import tempfile
import warnings
from pathlib import Path
import pytest
from reme.components.file_store import LocalFileStore
from reme.schema import FileNode
from reme.utils.wikilink_handler import WikilinkHandler
warnings.filterwarnings("ignore", category=DeprecationWarning, module="jieba")
warnings.filterwarnings("ignore", category=DeprecationWarning, module="pkg_resources")
async def _store_with(files: dict[str, str]) -> LocalFileStore:
"""LocalFileStore seeded with (rel → content) files: written to disk
AND registered in the file_graph with wikilinks parsed from the body.
Without the parsed links the reverse-index lookup yields nothing and
retarget becomes a no-op.
"""
store = LocalFileStore(name="t", embedding_store="")
await store.start()
nodes: list[FileNode] = []
root = Path.cwd()
for rel, content in files.items():
abs_path = root / rel
abs_path.parent.mkdir(parents=True, exist_ok=True)
abs_path.write_text(content, encoding="utf-8")
nodes.append(
FileNode(
path=rel,
st_mtime=abs_path.stat().st_mtime,
links=WikilinkHandler.extract_links(content, rel),
),
)
if nodes:
await store.file_graph.upsert_nodes(nodes)
return store
async def _empty_store() -> LocalFileStore:
store = LocalFileStore(name="t", embedding_store="")
await store.start()
return store
@pytest.mark.asyncio
async def test_retarget_exact_full_path_match():
"""[[topics/Alice.md]] → [[people/Alice.md]]; non-matching links untouched."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with(
{
"note.md": "See [[topics/Alice.md]] and [[topics/Bob.md]].",
"people/Alice.md": "# Alice",
},
)
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert "error" not in payload
assert payload["links_changed"] == 1
assert payload["files_touched"] == 1
body = (root / "note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md]]" in body
assert "[[topics/Alice.md]]" not in body
assert "[[topics/Bob.md]]" in body
await store.close()
@pytest.mark.asyncio
async def test_retarget_short_and_no_ext_forms_ignored():
"""Short-form [[Alice]] and no-ext [[topics/Alice]] are NOT matched."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
body_in = "See [[Alice]] and [[topics/Alice]] but also [[topics/Alice.md]]."
store = await _store_with(
{
"note.md": body_in,
"people/Alice.md": "# Alice",
},
)
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 1 # only the full-path form
body = (root / "note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md]]" in body
assert "[[Alice]]" in body # short form untouched
assert "[[topics/Alice]]" in body # no-ext form untouched
await store.close()
@pytest.mark.asyncio
async def test_retarget_anchor_preserved():
"""`[[topics/Alice.md#intro]]` → `[[people/Alice.md#intro]]` (anchor kept verbatim)."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with({"note.md": "Jump to [[topics/Alice.md#intro]] please."})
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 1
body = (root / "note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md#intro]]" in body
await store.close()
@pytest.mark.asyncio
async def test_retarget_alias_preserved():
"""`[[topics/Alice.md|Display Name]]` → `[[people/Alice.md|Display Name]]`."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with({"note.md": "Meet [[topics/Alice.md|Alice the Architect]]."})
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 1
body = (root / "note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md|Alice the Architect]]" in body
await store.close()
@pytest.mark.asyncio
async def test_retarget_anchor_and_alias_together():
"""`[[A.md#h|disp]]` → `[[B.md#h|disp]]` keeps both suffixes."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with({"note.md": "See [[topics/Alice.md#bio|her bio]] now."})
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 1
body = (root / "note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md#bio|her bio]]" in body
await store.close()
@pytest.mark.asyncio
async def test_retarget_image_marker_preserved():
"""`![[topics/diagram.md]]` (embed) keeps its `!` prefix on rewrite."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with({"note.md": "Inline embed: ![[topics/diagram.md]] here."})
payload = await WikilinkHandler.retarget_links(store, src="topics/diagram.md", dst="diagrams/diagram.md")
assert payload["links_changed"] == 1
body = (root / "note.md").read_text(encoding="utf-8")
assert "![[diagrams/diagram.md]]" in body
await store.close()
@pytest.mark.asyncio
async def test_retarget_preserves_surrounding_relation_text():
"""Retargeting changes only the inner wikilink target."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
body_in = "colleague:: [[topics/Alice.md]]\n" + "She is the [负责:: [[topics/Alice.md]]] for the migration.\n"
store = await _store_with({"note.md": body_in})
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 2
body = (root / "note.md").read_text(encoding="utf-8")
assert "colleague:: [[people/Alice.md]]" in body
assert "[负责:: [[people/Alice.md]]]" in body
await store.close()
def test_markdown_links_are_ignored():
"""Only double-bracket wikilinks create graph edges or get rewritten."""
markdown_links = (
"[label](../wiki/example.md) "
"[label](../wiki/example.md#section) "
"[label](../wiki/example.md#L9-L10,L15-L20)"
)
original = f"{markdown_links} [[wiki/example.md#L9]]"
rewritten, count = WikilinkHandler.scan_and_rewrite(
original,
old="wiki/example.md",
new="archive/example.md",
)
assert [(link.target_path, link.target_anchor) for link in WikilinkHandler.extract_links(original, "note.md")] == [
("wiki/example.md", "L9"),
]
assert count == 1
assert rewritten == f"{markdown_links} [[archive/example.md#L9]]"
@pytest.mark.asyncio
async def test_retarget_multiple_files_aggregate_counts():
"""links_changed sums across files; by_file lists per-file counts."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _store_with(
{
"a.md": "[[topics/Alice.md]] then [[topics/Alice.md]]",
"sub/b.md": "[[topics/Alice.md]] and [[topics/Bob.md]]",
},
)
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="people/Alice.md")
assert payload["links_changed"] == 3
assert payload["files_touched"] == 2
by_file = {row["path"]: row["count"] for row in payload["by_file"]}
assert by_file == {"a.md": 2, "sub/b.md": 1}
await store.close()
@pytest.mark.asyncio
async def test_retarget_dry_run_does_not_write():
"""dry_run=True reports counts but leaves files on disk unchanged."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
original = "See [[topics/Alice.md]]."
store = await _store_with({"note.md": original})
payload = await WikilinkHandler.retarget_links(
store,
src="topics/Alice.md",
dst="people/Alice.md",
dry_run=True,
)
assert payload["dry_run"] is True
assert payload["links_changed"] == 1
assert payload["files_touched"] == 1
assert (root / "note.md").read_text(encoding="utf-8") == original
await store.close()
@pytest.mark.asyncio
async def test_retarget_scope_limits_sweep():
"""Files outside `scope` are not visited even if they contain matches."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
root = Path(tmp)
store = await _store_with(
{
"in_scope/note.md": "See [[topics/Alice.md]].",
"outside/note.md": "Also [[topics/Alice.md]].",
},
)
payload = await WikilinkHandler.retarget_links(
store,
src="topics/Alice.md",
dst="people/Alice.md",
scope="in_scope",
)
assert payload["links_changed"] == 1
assert payload["files_touched"] == 1
in_body = (root / "in_scope/note.md").read_text(encoding="utf-8")
out_body = (root / "outside/note.md").read_text(encoding="utf-8")
assert "[[people/Alice.md]]" in in_body
assert "[[topics/Alice.md]]" in out_body # untouched
await store.close()
@pytest.mark.asyncio
async def test_retarget_src_eq_dst_is_noop():
"""src == dst: no scan needed, returns zero counts."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _store_with({"note.md": "See [[topics/Alice.md]]."})
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst="topics/Alice.md")
assert payload["links_changed"] == 0
assert payload["files_touched"] == 0
await store.close()
@pytest.mark.asyncio
async def test_retarget_empty_src_or_dst_errors():
"""Empty src or dst produces an error payload."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _empty_store()
for kwargs in ({"src": "", "dst": "people/Alice.md"}, {"src": "topics/Alice.md", "dst": ""}):
payload = await WikilinkHandler.retarget_links(store, **kwargs)
assert "error" in payload, f"expected error for {kwargs}"
await store.close()
@pytest.mark.asyncio
async def test_retarget_dst_with_forbidden_chars_errors():
"""``dst`` containing ``[ ] # |`` or newline lands as an error payload."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _empty_store()
for bad in ["people/Alice#anchor", "people/Alice|alias", "p/[A].md", "p/A]]"]:
payload = await WikilinkHandler.retarget_links(store, src="topics/Alice.md", dst=bad)
assert "error" in payload, f"expected error for dst={bad!r}, got {payload}"
await store.close()
@pytest.mark.asyncio
async def test_retarget_absolute_path_rejected():
"""Absolute paths in src or dst are rejected (must be relative to the workspace)."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _empty_store()
for kwargs in (
{"src": "/abs/old.md", "dst": "people/Alice.md"},
{"src": "topics/Alice.md", "dst": "/abs/new.md"},
):
payload = await WikilinkHandler.retarget_links(store, **kwargs)
assert "error" in payload, f"expected error for {kwargs}"
await store.close()
@pytest.mark.asyncio
async def test_find_inbound_counts_references():
"""find_inbound reports per-file counts and excludes self-references."""
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
store = await _store_with(
{
"a.md": "[[topics/Alice.md]] and [[topics/Alice.md]] again",
"b.md": "see [[topics/Alice.md]]",
"topics/Alice.md": "self-ref [[topics/Alice.md]] should not count",
},
)
payload = await WikilinkHandler.find_inbound(store, target="topics/Alice.md")
assert payload["files_touched"] == 2
assert payload["links_total"] == 3
by_file = {row["path"]: row["count"] for row in payload["by_file"]}
assert by_file == {"a.md": 2, "b.md": 1}
await store.close()