Files
fiona-assistant/tests/test_housekeeping.py
T
2026-10-02 11:33:55 +02:00

295 lines
12 KiB
Python

"""Tests for fiona-assistant housekeeping (SPEC 4.8, 7.2).
Generated by AI/LLM: 2026-09-30 - housekeeping routine tests.
"""
from __future__ import annotations
import hashlib
import json
import shutil
from pathlib import Path
from unittest.mock import patch
import pytest
from fiona.__main__ import main
from fiona.wiki.housekeeping import (
STEP_NAMES,
format_housekeeping_report,
housekeeping_main,
run_housekeeping,
)
from fiona.wiki.wiki import get_llm_wiki_source_path
def _page(path: Path, name: str, version: str = "1.0.0", extra: str = "",
body: str = "") -> None:
"""Write a small markdown page with frontmatter at path."""
path.parent.mkdir(parents=True, exist_ok=True)
text = f"---\nname: {name}\nversion: {version}\n{extra}---\n\n# {name.capitalize()}\n"
path.write_text(text + (f"\n{body}" if body else ""), encoding="utf-8")
@pytest.fixture
def hk_wiki(tmp_path, monkeypatch):
"""A clean two-page wiki and a template that matches it."""
template = tmp_path / "template"
wiki = tmp_path / "wiki"
settings = get_llm_wiki_source_path() / "fiona-settings.json"
for root in (template, wiki):
root.mkdir()
shutil.copy2(settings, root / "fiona-settings.json")
_page(root / "AGENTS.md", "agents", "2.0.0", body="See [index](./wiki/index.md).\n")
_page(root / "wiki" / "index.md", "index", body="See [a](./a.md).\n")
_page(wiki / "wiki" / "a.md", "a", body="Back to [index](./index.md).\n")
monkeypatch.setattr(
"fiona.wiki.update_manager.get_llm_wiki_source_path", lambda: template
)
return wiki
def _step(results: dict, name: str) -> dict:
"""Return the named step from a housekeeping result."""
return next(step for step in results["steps"] if step["name"] == name)
def _hashes(root: Path) -> dict:
"""Map every file under root to its SHA-256."""
return {
path: hashlib.sha256(path.read_bytes()).hexdigest()
for path in root.rglob("*") if path.is_file()
}
class TestRunHousekeeping:
"""Tests for the housekeeping steps (SPEC 7.2)."""
def test_steps_run_in_order(self, hk_wiki):
results = run_housekeeping(hk_wiki)
assert [step["name"] for step in results["steps"]] == list(STEP_NAMES)
assert STEP_NAMES == ("check-update", "merge", "ingest", "sanity", "graph")
def test_clean_wiki_passes(self, hk_wiki):
results = run_housekeeping(hk_wiki)
assert results["passed"] is True
assert {step["status"] for step in results["steps"]} == {"PASS"}
def test_conflict_is_warn_and_writes_nothing(self, hk_wiki):
"""SPEC 7.2.2: check-update reports conflicts without writing."""
_page(hk_wiki / "AGENTS.md", "agents", "1.0.0", body="See [index](./wiki/index.md).\n")
step = _step(run_housekeeping(hk_wiki), "check-update")
assert step["status"] == "WARN"
assert step["summary"] == "0 update(s), 1 conflict(s), 0 addition(s)"
assert "conflict: AGENTS.md -> AGENTS-update.md" in step["details"]
assert step["next"] == [
"Ask the user, then run fiona-assistant wiki update --dry-run and wiki update --yes."
]
assert not (hk_wiki / "AGENTS-update.md").exists()
def test_pending_update_file_fails_merge(self, hk_wiki):
"""SPEC 7.2.3: every *-update.md waits for a merge."""
_page(hk_wiki / "wiki" / "schema-update.md", "schema", "1.5.0")
_page(hk_wiki / "orphan-update.md", "orphan")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["status"] == "FAIL"
assert step["summary"] == "2 update file(s) wait for a merge"
(hk_wiki / "fiona-settings-update.json").write_text("{}\n", encoding="utf-8")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["status"] == "FAIL"
assert step["summary"] == "3 update file(s) wait for a merge"
assert "wiki/schema-update.md -> wiki/schema.md (target missing)" in step["details"]
assert "orphan-update.md -> orphan.md (target missing)" in step["details"]
assert "fiona-settings-update.json -> fiona-settings.json" in step["details"]
assert any("1.5.0" in action and "wiki/schema-update.md" in action
for action in step["next"])
def test_merge_detail_without_missing_target(self, hk_wiki):
_page(hk_wiki / "AGENTS-update.md", "agents", "3.0.0")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["details"] == ["AGENTS-update.md -> AGENTS.md"]
def test_update_file_without_version_names_template_version(self, hk_wiki):
(hk_wiki / "AGENTS-update.md").write_text("# no frontmatter\n", encoding="utf-8")
step = _step(run_housekeeping(hk_wiki), "merge")
assert "at least the template version" in step["next"][0]
def test_corefiles_record_is_not_a_merge_candidate(self, hk_wiki):
"""SPEC 7.2.3: corefiles.json is not an update file to merge."""
(hk_wiki / "corefiles.json").write_text("{}\n", encoding="utf-8")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["status"] == "PASS"
assert step["details"] == []
def test_ignored_update_file_is_not_a_merge_candidate(self, hk_wiki):
"""SPEC 7.2.3: a path in update.ignore_files is not merged."""
settings_path = hk_wiki / "fiona-settings.json"
settings = json.loads(settings_path.read_text(encoding="utf-8"))
settings["fiona"]["wiki"]["update"]["ignore_files"].append("notes-update.md")
settings_path.write_text(json.dumps(settings), encoding="utf-8")
(hk_wiki / "notes-update.md").write_text("# notes\n", encoding="utf-8")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["status"] == "PASS"
assert step["details"] == []
def test_read_only_zones_are_not_scanned_for_update_files(self, hk_wiki):
_page(hk_wiki / "raw" / "note-update.md", "note")
_page(hk_wiki / "personal" / "note-update.md", "note")
step = _step(run_housekeeping(hk_wiki), "merge")
assert step["status"] == "PASS"
def test_raw_page_is_ingest_warn(self, hk_wiki):
"""SPEC 7.2.4: pages at status: raw wait for a refine."""
_page(hk_wiki / "wiki" / "sources" / "s.md", "s", extra="status: raw\n",
body="From [index](../index.md).\n")
step = _step(run_housekeeping(hk_wiki), "ingest")
assert step["status"] == "WARN"
assert step["details"] == ["wiki/sources/s.md"]
assert step["next"] == ["Refine each raw page, then set status: refined."]
def test_dead_link_fails_sanity(self, hk_wiki):
"""SPEC 7.2.5: a sanity violation is FAIL with the report lines."""
_page(hk_wiki / "wiki" / "a.md", "a", body="See [gone](./gone.md).\n")
step = _step(run_housekeeping(hk_wiki), "sanity")
assert step["status"] == "FAIL"
assert step["summary"] == "1 violation(s) in 1 check(s)"
assert any("a.md" in line for line in step["details"])
def test_graph_written_and_orphans_warned(self, hk_wiki):
"""SPEC 7.2.6: the graph lands at the wiki root; orphans warn."""
_page(hk_wiki / "wiki" / "lonely.md", "lonely")
_page(hk_wiki / "wiki" / "lonely-update.md", "lonely")
step = _step(run_housekeeping(hk_wiki), "graph")
assert (hk_wiki / "wiki_graph.html").is_file()
assert step["status"] == "WARN"
assert step["summary"].startswith("wrote wiki_graph.html (")
assert step["details"] == ["orphan: wiki/lonely.md"]
def test_graph_error_is_fail(self, hk_wiki):
with patch("fiona.wiki.housekeeping.wiki_graph_main", return_value=1):
step = _step(run_housekeeping(hk_wiki), "graph")
assert step["status"] == "FAIL"
def test_every_step_runs_after_a_failure(self, hk_wiki):
"""SPEC 7.2.1: merge and sanity fail, graph still runs."""
_page(hk_wiki / "AGENTS-update.md", "agents", "3.0.0")
_page(hk_wiki / "wiki" / "a.md", "a", body="See [gone](./gone.md).\n")
results = run_housekeeping(hk_wiki)
assert _step(results, "merge")["status"] == "FAIL"
assert _step(results, "sanity")["status"] == "FAIL"
assert (hk_wiki / "wiki_graph.html").is_file()
assert results["passed"] is False
def test_only_graph_is_written(self, hk_wiki):
"""SPEC 7.2.7: housekeeping changes nothing but wiki_graph.html."""
_page(hk_wiki / "AGENTS.md", "agents", "1.0.0", body="See [index](./wiki/index.md).\n")
before = _hashes(hk_wiki)
run_housekeeping(hk_wiki)
after = _hashes(hk_wiki)
after.pop(hk_wiki / "wiki_graph.html")
assert after == before
def test_missing_directory_raises(self, tmp_path):
with pytest.raises(FileNotFoundError, match="Directory not found"):
run_housekeeping(tmp_path / "nope")
def test_non_wiki_raises(self, tmp_path):
with pytest.raises(NotADirectoryError, match="not an llm-wiki directory"):
run_housekeeping(tmp_path)
class TestHousekeepingReport:
"""Tests for the human and JSON output (SPEC 4.8, 7.2.8)."""
def test_human_report_passes(self, hk_wiki):
report = format_housekeeping_report(run_housekeeping(hk_wiki))
assert report.startswith(f"Housekeeping Report\nTARGET: {hk_wiki.resolve()}\n")
assert "[PASS] merge: 0 update file(s) wait for a merge" in report
assert "Next steps:" not in report
assert report.endswith("HOUSEKEEPING PASSED")
def test_human_report_fails_with_next_steps(self, hk_wiki):
_page(hk_wiki / "AGENTS-update.md", "agents", "3.0.0")
report = format_housekeeping_report(run_housekeeping(hk_wiki))
assert "[FAIL] merge: 1 update file(s) wait for a merge" in report
assert " - AGENTS-update.md -> AGENTS.md" in report
assert "Next steps:\n - Merge AGENTS-update.md into AGENTS.md" in report
assert report.endswith("HOUSEKEEPING FAILED - 1 step(s) need attention: merge")
def test_next_steps_have_no_repeats(self):
results = {
"target": Path("/w"),
"passed": True,
"steps": [
{"name": "a", "status": "WARN", "summary": "s", "details": [], "next": ["x"]},
{"name": "b", "status": "WARN", "summary": "s", "details": [], "next": ["x"]},
],
}
assert format_housekeeping_report(results).count(" - x") == 1
def test_json_warn_only_passes(self, hk_wiki, capsys):
_page(hk_wiki / "wiki" / "lonely.md", "lonely")
code = housekeeping_main(str(hk_wiki), json_output=True)
output = json.loads(capsys.readouterr().out)
assert code == 0
assert output["passed"] is True
assert output["target"] == str(hk_wiki.resolve())
assert _step(output, "graph")["status"] == "WARN"
def test_main_exits_1_on_fail(self, hk_wiki, capsys):
_page(hk_wiki / "AGENTS-update.md", "agents", "3.0.0")
assert housekeeping_main(str(hk_wiki)) == 1
assert "HOUSEKEEPING FAILED" in capsys.readouterr().out
def test_main_reports_non_wiki(self, tmp_path, capsys):
assert housekeeping_main(str(tmp_path)) == 1
assert "is not an llm-wiki directory" in capsys.readouterr().err
class TestHousekeepingCli:
"""Tests for the fiona-assistant housekeeping command."""
def test_cli_dispatches(self, hk_wiki, capsys):
argv = ["fiona-assistant", "housekeeping", str(hk_wiki), "--json"]
with patch("sys.argv", argv), pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
assert json.loads(capsys.readouterr().out)["passed"] is True