221 lines
9.9 KiB
Python
221 lines
9.9 KiB
Python
#!/usr/bin/env python3
|
|
import json
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
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 (
|
|
NoteState, State, create_note, find_existing_symlink, find_hd_root,
|
|
register_note, resolve_or_create_note, tag_from_cwd,
|
|
)
|
|
|
|
PASS = []
|
|
FAIL = []
|
|
|
|
|
|
def check(name, cond, detail=""):
|
|
if cond:
|
|
PASS.append(name)
|
|
else:
|
|
FAIL.append((name, detail))
|
|
print(f"FAIL: {name} {detail}")
|
|
|
|
|
|
class FakeNewNoteServer:
|
|
"""Just enough of HedgeDoc's POST /new to test create_note(): accept the
|
|
body as the note's content, mint an id, redirect to /<id> -- mirrors
|
|
lib/web/note/util.js's newNote() exactly (always redirects, id in
|
|
Location, no JSON response)."""
|
|
|
|
def __init__(self, port):
|
|
self.port = port
|
|
self.notes = {}
|
|
self._counter = 0
|
|
self.last_content_type = None
|
|
|
|
def app(environ, start_response):
|
|
request = Request(environ)
|
|
if request.path == "/new" and request.method == "POST":
|
|
self._counter += 1
|
|
note_id = f"minted-{self._counter}"
|
|
body = request.get_data(as_text=True)
|
|
self.last_content_type = request.headers.get("Content-Type")
|
|
self.notes[note_id] = body
|
|
resp = Response(status=302, headers={"Location": f"/{note_id}"})
|
|
return resp(environ, start_response)
|
|
if request.path.endswith("/download"):
|
|
nid = request.path.split("/")[1]
|
|
resp = Response(self.notes.get(nid, ""), mimetype="text/markdown")
|
|
return resp(environ, start_response)
|
|
return Response("not found", status=404)(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 main():
|
|
tmpdir = Path(tempfile.mkdtemp(prefix="hd-create-test-"))
|
|
root = tmpdir / "notes"
|
|
(root / ".hd" / "notes").mkdir(parents=True)
|
|
|
|
try:
|
|
# --- find_hd_root: climbs up, git-style ---
|
|
# Use a directory OUTSIDE the tag dirs for the climbing test, so the
|
|
# temporary nesting doesn't make 'radio' itself look broken to the
|
|
# freshness check that later tests depend on.
|
|
deep = root / "climbtest" / "sub"
|
|
deep.mkdir(parents=True)
|
|
check("finds root from a nested cwd", find_hd_root(deep) == root.resolve())
|
|
check("finds root from root itself", find_hd_root(root) == root.resolve())
|
|
outside = tmpdir / "elsewhere"
|
|
outside.mkdir()
|
|
check("returns None with no .hd anywhere above", find_hd_root(outside) is None)
|
|
|
|
# --- tag_from_cwd ---
|
|
(root / "radio").mkdir(exist_ok=True)
|
|
check("root itself -> untagged, no error", tag_from_cwd(root, root) == (None, None))
|
|
tag, err = tag_from_cwd(root, root / "radio")
|
|
check("one level -> that tag, no error", tag == "radio" and err is None, (tag, err))
|
|
tag2, err2 = tag_from_cwd(root, root / "climbtest" / "sub")
|
|
check("two levels -> error, not a compound tag", tag2 is None and err2 is not None, (tag2, err2))
|
|
check("nesting error names the offending path", "nested" in err2 and "climbtest" in err2, err2)
|
|
tag3, err3 = tag_from_cwd(root, root / ".hd")
|
|
check("inside .hd -> refused", tag3 is None and err3 is not None, (tag3, err3))
|
|
outside_tag, outside_err = tag_from_cwd(root, outside)
|
|
check("outside root entirely -> error", outside_tag is None and outside_err is not None)
|
|
|
|
# --- create_note against a fake /new ---
|
|
port = free_port()
|
|
server = FakeNewNoteServer(port)
|
|
server.start()
|
|
time.sleep(0.2)
|
|
|
|
note_id, initial_text = create_note(f"http://127.0.0.1:{port}", "session=1", "My New Note", ["radio"])
|
|
check("create_note returns the minted id", note_id == "minted-1", note_id)
|
|
check("initial content has a frontmatter block", initial_text.startswith("---\n"), initial_text)
|
|
check("initial content has the right title", "title: My New Note" in initial_text, initial_text)
|
|
check("initial content has the right tag", "tags: radio" in initial_text, initial_text)
|
|
check("server actually received that content", server.notes["minted-1"] == initial_text)
|
|
|
|
note_id2, text2 = create_note(f"http://127.0.0.1:{port}", "session=1", "Untagged Note", [])
|
|
check("untagged create_note has no tags line", "tags:" not in text2, text2)
|
|
|
|
# --- register_note: local cache + symlink, no network ---
|
|
state = State()
|
|
ns = register_note(root, state, note_id, "My New Note", ["radio"], initial_text)
|
|
check("register_note returns matching NoteState", ns.title == "My New Note" and ns.tags == ["radio"])
|
|
check("cache file written", (root / ".hd" / "notes" / f"{note_id}.md").read_text() == initial_text)
|
|
check("symlink created in the right tag dir", (root / "radio" / "My New Note").is_symlink())
|
|
check("state updated in-memory", note_id in state.notes)
|
|
|
|
# --- find_existing_symlink ---
|
|
found = find_existing_symlink(root, "radio", "My New Note")
|
|
check("find_existing_symlink finds the one we just made", found == note_id, found)
|
|
check("find_existing_symlink returns None for a name that isn't there",
|
|
find_existing_symlink(root, "radio", "Nope") is None)
|
|
check("find_existing_symlink returns None for the wrong tag",
|
|
find_existing_symlink(root, "personal", "My New Note") is None)
|
|
|
|
server.stop()
|
|
|
|
# --- resolve_or_create_note: full flow, open-vs-create ---
|
|
port2 = free_port()
|
|
server2 = FakeNewNoteServer(port2)
|
|
server2.start()
|
|
time.sleep(0.2)
|
|
url2 = f"http://127.0.0.1:{port2}"
|
|
|
|
radio_dir = root / "radio"
|
|
note_id_a, created_a = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1")
|
|
check("first call creates a new note", created_a is True)
|
|
check("new symlink exists after creation", (radio_dir / "Fresh Project").is_symlink())
|
|
|
|
note_id_b, created_b = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1")
|
|
check("second call with the same name opens, doesn't create", created_b is False)
|
|
check("second call resolves to the SAME note id", note_id_b == note_id_a, (note_id_a, note_id_b))
|
|
check("only one POST /new happened on the server", len(server2.notes) == 1, server2.notes)
|
|
|
|
# --- resolve_or_create_note refuses in a too-deep directory ---
|
|
too_deep = root / "climbtest" / "sub"
|
|
try:
|
|
resolve_or_create_note(root, too_deep, "Whatever", url2, "session=1")
|
|
check("refuses to create in a nested directory", False, "did not raise")
|
|
except ValueError as exc:
|
|
check("refuses to create in a nested directory", True)
|
|
check("refusal message explains why", "nested" in str(exc), str(exc))
|
|
|
|
# --- the fresh target-directory check gates CREATION specifically ---
|
|
broken_dir = root / "brokentag"
|
|
(broken_dir / "accidental_subdir").mkdir(parents=True)
|
|
try:
|
|
resolve_or_create_note(root, broken_dir, "Should Not Exist", url2, "session=1")
|
|
check("refuses to create in a directory containing a subdirectory", False, "did not raise")
|
|
except ValueError as exc:
|
|
check("refuses to create in a directory containing a subdirectory", True)
|
|
check("refusal names the offending subdirectory",
|
|
"accidental_subdir" in str(exc), str(exc))
|
|
check("nothing was created on the server by the refused call",
|
|
len(server2.notes) == 1, server2.notes)
|
|
|
|
# ...but OPENING an existing note in that same messy directory still works,
|
|
# since that adds nothing new to an already-unreconcilable directory.
|
|
note_id_c, created_c = resolve_or_create_note(root, radio_dir, "Openable", url2, "session=1")
|
|
(broken_dir / "Openable").symlink_to(
|
|
os.path.relpath(root / ".hd" / "notes" / f"{note_id_c}.md", broken_dir))
|
|
note_id_d, created_d = resolve_or_create_note(root, broken_dir, "Openable", url2, "session=1")
|
|
check("opening an existing note in a messy directory is still allowed",
|
|
created_d is False and note_id_d == note_id_c, (note_id_c, note_id_d, created_d))
|
|
|
|
server2.stop()
|
|
|
|
# --- 'Name.md' resolves to the SAME note as 'Name' (the bug Joakim hit) ---
|
|
port4 = free_port()
|
|
server4 = FakeNewNoteServer(port4)
|
|
server4.start()
|
|
time.sleep(0.2)
|
|
url4 = f"http://127.0.0.1:{port4}"
|
|
radio_dir2 = root / "radio2"
|
|
radio_dir2.mkdir(parents=True)
|
|
|
|
id_by_name, created_by_name = resolve_or_create_note(root, radio_dir2, "Masten", url4, "session=1")
|
|
check("'Masten' creates a note", created_by_name is True)
|
|
id_by_md, created_by_md = resolve_or_create_note(root, radio_dir2, "Masten.md", url4, "session=1")
|
|
check("'Masten.md' opens the SAME note 'Masten' created, doesn't create a second",
|
|
created_by_md is False and id_by_md == id_by_name, (id_by_name, id_by_md, created_by_md))
|
|
check("only one POST /new happened despite two different spellings",
|
|
len(server4.notes) == 1, server4.notes)
|
|
server4.stop()
|
|
|
|
finally:
|
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
|
|
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
|
return 0 if not FAIL else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|