first commit
This commit is contained in:
245
hd-cli/test_hd_core.py
Normal file
245
hd-cli/test_hd_core.py
Normal file
@@ -0,0 +1,245 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
from hd_core import HedgeDocSource, State, reconcile
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class FakeHistoryServer:
|
||||
"""Serves /history and /<id>/download from an in-memory dict this test
|
||||
mutates directly between reconcile() calls, so each call sees the state
|
||||
as it stood at that moment -- like a real server changing between syncs.
|
||||
Each note dict may include "time" (default 0) -- tests bump it whenever
|
||||
they simulate a real edit, mirroring how /history's own `time` field
|
||||
actually moves on the real server; download_count tracks /download hits
|
||||
so tests can assert the skip-fetch-when-unchanged optimization fires."""
|
||||
|
||||
def __init__(self, port):
|
||||
self.notes = {} # id -> {"title":..., "tags":[...], "content":..., "time": int}
|
||||
self.port = port
|
||||
self.download_count = {} # id -> number of /download requests served
|
||||
|
||||
def app(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/history":
|
||||
history = [
|
||||
{"id": nid, "text": n["title"], "tags": n["tags"], "time": n.get("time", 0)}
|
||||
for nid, n in self.notes.items()
|
||||
]
|
||||
resp = Response(json.dumps({"history": history}), mimetype="application/json")
|
||||
elif request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
n = self.notes.get(nid)
|
||||
self.download_count[nid] = self.download_count.get(nid, 0) + 1
|
||||
if n is None:
|
||||
resp = Response("not found", status=404)
|
||||
else:
|
||||
resp = Response(n["content"], mimetype="text/markdown")
|
||||
else:
|
||||
resp = Response("not found", status=404)
|
||||
return resp(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, app, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def listing(root: Path, tag: str):
|
||||
d = root / tag
|
||||
if not d.exists():
|
||||
return {}
|
||||
return {p.name: p.resolve() for p in d.iterdir() if p.is_symlink()}
|
||||
|
||||
|
||||
def main():
|
||||
port = free_port()
|
||||
server = FakeHistoryServer(port)
|
||||
server.start()
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
(hd_dir / "notes").mkdir(parents=True)
|
||||
source = HedgeDocSource(f"http://127.0.0.1:{port}", cookie="test=1")
|
||||
state = State()
|
||||
|
||||
try:
|
||||
# --- 1. Two notes, one shared tag, one exclusive tag each ---
|
||||
server.notes["id1"] = {"title": "Radio Log", "tags": ["radio", "work"], "content": "# Radio Log\ncontent A", "time": 1}
|
||||
server.notes["id2"] = {"title": "Grocery List", "tags": ["personal"], "content": "# Grocery List\nmilk", "time": 1}
|
||||
server.notes["id3"] = {"title": "Scratch", "tags": [], "content": "just some notes", "time": 1}
|
||||
|
||||
r1 = reconcile(root, source, state)
|
||||
check("initial: 3 notes updated", len(r1.notes_updated) == 3, r1.notes_updated)
|
||||
check("radio/ has Radio Log", "Radio Log" in listing(root, "radio"))
|
||||
check("work/ has Radio Log", "Radio Log" in listing(root, "work"))
|
||||
check("personal/ has Grocery List", "Grocery List" in listing(root, "personal"))
|
||||
check("untagged/ has Scratch", "Scratch" in listing(root, "untagged"))
|
||||
check("cache file id1 has right content",
|
||||
(hd_dir / "notes" / "id1.md").read_text() == "# Radio Log\ncontent A")
|
||||
check("radio/Radio Log resolves to id1.md",
|
||||
listing(root, "radio")["Radio Log"] == (hd_dir / "notes" / "id1.md").resolve())
|
||||
check("initial: each note fetched exactly once",
|
||||
server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count)
|
||||
|
||||
# --- 2. Idempotent re-run: nothing changed, and /download is never
|
||||
# called again since /history's `time` field didn't move ---
|
||||
r2 = reconcile(root, source, state)
|
||||
check("idempotent: no notes updated", r2.notes_updated == [], r2.notes_updated)
|
||||
check("idempotent: no symlinks created", r2.symlinks_created == [], r2.symlinks_created)
|
||||
check("idempotent: no symlinks removed", r2.symlinks_removed == [], r2.symlinks_removed)
|
||||
check("idempotent: no re-fetch when time is unchanged",
|
||||
server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count)
|
||||
|
||||
# --- 3. Retag: id1 loses 'work', gains 'reference' (a real retag
|
||||
# edits the note's frontmatter, so /history's time moves too) ---
|
||||
server.notes["id1"]["tags"] = ["radio", "reference"]
|
||||
server.notes["id1"]["time"] = 2
|
||||
r3 = reconcile(root, source, state)
|
||||
check("retag: id1 marked updated", "id1" in r3.notes_updated)
|
||||
check("retag: work/ no longer has Radio Log", "Radio Log" not in listing(root, "work"))
|
||||
check("retag: reference/ has Radio Log", "Radio Log" in listing(root, "reference"))
|
||||
check("retag: radio/ still has Radio Log", "Radio Log" in listing(root, "radio"))
|
||||
|
||||
# --- 4. Note becomes fully untagged ---
|
||||
server.notes["id2"]["tags"] = []
|
||||
server.notes["id2"]["time"] = 2
|
||||
r4 = reconcile(root, source, state)
|
||||
check("untag: personal/ no longer has Grocery List", "Grocery List" not in listing(root, "personal"))
|
||||
check("untag: untagged/ has Grocery List", "Grocery List" in listing(root, "untagged"))
|
||||
|
||||
# --- 5. Title change: symlink renamed, id mapping preserved ---
|
||||
server.notes["id1"]["title"] = "Ham Radio Log"
|
||||
server.notes["id1"]["time"] = 3
|
||||
r5 = reconcile(root, source, state)
|
||||
check("rename: old name gone from radio/", "Radio Log" not in listing(root, "radio"))
|
||||
check("rename: new name present in radio/", "Ham Radio Log" in listing(root, "radio"))
|
||||
check("rename: still resolves to id1.md",
|
||||
listing(root, "radio")["Ham Radio Log"] == (hd_dir / "notes" / "id1.md").resolve())
|
||||
check("rename: reference/ also renamed", "Ham Radio Log" in listing(root, "reference"))
|
||||
|
||||
# --- 6. Filename collision: two notes, same title, same tag ---
|
||||
server.notes["id4"] = {"title": "Ham Radio Log", "tags": ["radio"], "content": "different note, same title", "time": 1}
|
||||
r6 = reconcile(root, source, state)
|
||||
radio_files = listing(root, "radio")
|
||||
check("collision: both variants present", len(radio_files) == 2, radio_files)
|
||||
check("collision: deduped name uses id suffix",
|
||||
any(name.startswith("Ham Radio Log-") for name in radio_files))
|
||||
|
||||
# --- 7. Content update without title/tag change: cache refreshes, symlink name stable ---
|
||||
old_name = state.notes["id1"].symlinks["radio"]
|
||||
server.notes["id1"]["content"] = "# Ham Radio Log\nupdated content"
|
||||
server.notes["id1"]["time"] = 4
|
||||
r7 = reconcile(root, source, state)
|
||||
check("content update: id1 flagged updated", "id1" in r7.notes_updated)
|
||||
check("content update: symlink name unchanged", state.notes["id1"].symlinks["radio"] == old_name)
|
||||
check("content update: cache file reflects new content",
|
||||
(hd_dir / "notes" / "id1.md").read_text() == "# Ham Radio Log\nupdated content")
|
||||
check("content update: id1 was actually re-fetched (time moved)",
|
||||
server.download_count["id1"] == 4, server.download_count)
|
||||
|
||||
# --- 8. Note deleted server-side: pruned locally ---
|
||||
del server.notes["id3"]
|
||||
r8 = reconcile(root, source, state)
|
||||
check("deletion: id3 in notes_removed", "id3" in r8.notes_removed)
|
||||
check("deletion: untagged/Scratch gone", "Scratch" not in listing(root, "untagged"))
|
||||
check("deletion: cache file gone", not (hd_dir / "notes" / "id3.md").exists())
|
||||
check("deletion: state no longer tracks id3", "id3" not in state.notes)
|
||||
|
||||
# --- 9. Re-persist state through JSON round-trip and re-sync: still idempotent ---
|
||||
state.save(hd_dir)
|
||||
state2 = State.load(hd_dir)
|
||||
r9 = reconcile(root, source, state2)
|
||||
check("post-reload idempotent: no updates", r9.notes_updated == [], r9.notes_updated)
|
||||
check("post-reload idempotent: no symlink churn",
|
||||
not r9.symlinks_created and not r9.symlinks_removed,
|
||||
(r9.symlinks_created, r9.symlinks_removed))
|
||||
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
test_update_note_cache()
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
def test_update_note_cache():
|
||||
"""hd_core.update_note_cache: refreshes the local cache + hash after an
|
||||
hd-joe edit session, without touching title/tags/symlinks, and is a
|
||||
safe no-op for a note state.json doesn't know about yet."""
|
||||
import shutil, tempfile
|
||||
from hd_core import NoteState, State, content_hash, update_note_cache
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
(hd_dir / "notes").mkdir(parents=True)
|
||||
try:
|
||||
old_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nold content"
|
||||
(hd_dir / "notes" / "n1.md").write_text(old_text)
|
||||
state = State()
|
||||
state.notes["n1"] = NoteState(
|
||||
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
|
||||
content_hash=content_hash(old_text),
|
||||
)
|
||||
state.save(hd_dir)
|
||||
|
||||
new_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nAllt är korrekt!\nedited at EOF"
|
||||
updated = update_note_cache(root, "n1", new_text)
|
||||
check("update_note_cache returns True for a known note", updated is True)
|
||||
check("cache file reflects the new content",
|
||||
(hd_dir / "notes" / "n1.md").read_text() == new_text)
|
||||
|
||||
reloaded = State.load(hd_dir)
|
||||
check("content_hash updated in state.json",
|
||||
reloaded.notes["n1"].content_hash == content_hash(new_text))
|
||||
check("title untouched", reloaded.notes["n1"].title == "Masten")
|
||||
check("tags untouched", reloaded.notes["n1"].tags == ["sl6cv"])
|
||||
check("symlinks untouched", reloaded.notes["n1"].symlinks == {"sl6cv": "Masten"})
|
||||
|
||||
# Unknown note id (opened via explicit url+note-id, never synced) -- safe no-op
|
||||
result = update_note_cache(root, "never-seen-before", "whatever")
|
||||
check("update_note_cache returns False for an unknown note", result is False)
|
||||
check("no stray cache file created for the unknown note",
|
||||
not (hd_dir / "notes" / "never-seen-before.md").exists())
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user