diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f94f17..831e368 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,10 +81,31 @@ jobs: for i in $(seq 1 30); do curl -sf "http://127.0.0.1:$FORMTOOLS_PORT/api/health" && break; sleep 1; done curl -sf "http://127.0.0.1:$FORMTOOLS_PORT/api/health" curl -sf "http://127.0.0.1:$FORMTOOLS_PORT/api/capabilities" - - name: Tests - run: | - pip install pytest httpx - python -m pytest -q tests + + test: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 22 + cache: npm + cache-dependency-path: frontend/package-lock.json + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: backend/requirements.txt + - run: npm ci + working-directory: frontend + - run: pip install -r backend/requirements.txt pytest httpx + - name: Interface logic (vitest) + run: npx vitest run + working-directory: frontend + - name: Engine (pytest) + run: python -m pytest -q -p no:cacheprovider tests + working-directory: backend scripts: runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md index f158538..2991d2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,9 +2,10 @@ Rules for any coding agent (Claude Code, Codex, Cursor, Antigravity) working in this repository. `CLAUDE.md` is the full rule set; read it first. -- Stage: released (v0.13.0), built and bundled for macOS, Windows and Linux. `./formtools agents sync` mirrors `.claude/skills` into `.agents/skills`; `./formtools agents check` (also in CI) fails on drift. The plan of record is `DEV_PLAN.md` in the planning sidecar. Code changes route through `.claude/skills/formtools-harness`; using the app through MCP routes through `.claude/skills/formtools-driving`. +- Stage: released (v0.14.0), built and bundled for macOS, Windows and Linux. `./formtools agents sync` mirrors `.claude/skills` into `.agents/skills`; `./formtools agents check` (also in CI) fails on drift. The plan of record is `DEV_PLAN.md` in the planning sidecar. Code changes route through `.claude/skills/formtools-harness`; using the app through MCP routes through `.claude/skills/formtools-driving`. - You are an outside agent to the running app. Tools that only read always work. Any other tool (including the ones behind `./formtools cli convert`, `resize` and `rename --apply`) is asked about in the formtools window (Deny, Allow once, Always allow) unless the person chose Allowed in Settings, Integration, Outside agents, and is refused under Blocked or when no window is open to ask. Only the window can change that choice: when a call is refused, tell the person what the refusal says and stop. `agents/manifest.json` lists every tool and which ones ask. - Research lives in `docs/encyclopedia/` (start at `INDEX.md`). Paraphrase only; every page keeps its Sources list. - Before adding a dependency, check `docs/encyclopedia/engines/engine-licensing-matrix.md` and add a `NOTICE.md` row in the same commit. - Edits are surgical and hand-made. No emoji. No em dash in Markdown. Versions are `v*.*.*`. +- Tests are added when the owner asks; a change in behaviour updates its tests in the same pull request; every test follows the five rules in `docs/TESTING.md`. `./formtools test` runs them. - Commits: author and committer `nodemode-ai `, no attribution trailers of any kind. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7652cb5..61b4b41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.14.0 · 2026-11-23 + +formtools has a full test suite. + +- `./formtools test` runs two layers: interface logic (vitest with happy-dom, `frontend/tests/unit`) and the engine (pytest against the real FastAPI app, `backend/tests`). `./formtools test unit` or `./formtools test engine` runs one. `docs/TESTING.md` says how to run them and what a test must do to be accepted. +- 1,244 new cases run the app and check what a user or a calling program would notice: archives read back by independent readers and equal to their source byte for byte, hashes against published vectors, picture edits against geometry, renames with nothing lost, duplicates, disk usage, hosts files, glTF read by the format's rules, the MCP surface against JSON-RPC 2.0 and agreeing with the HTTP routes, the command-line tools, and viewers, tool forms and dialogs mounted in a document. With the 90 cases that were already here, 1,334 pass. +- No app code changed. Where a test showed the app to be wrong, the test stays as a strict expected failure whose reason starts with `DEFECT:`. There are 2 such cases: the environment.d writer leaves `$` unescaped, so systemd expands it at login, where environment.d(5) says to write `$$`; and a copy job that fails because ffmpeg is missing leaves an empty reserved output file beside the source, where every other failed copy removes its output. `git grep -n "DEFECT:" backend/tests frontend/tests` lists them. +- CI runs the tests on every pull request in one job, `test`, on Linux. +- Not run for this version: the browser demo in `demo/` was not rebuilt, so its built script still says 0.13.0. Real ffmpeg, ffprobe and exiftool output was not run, only stand-in programs. The desktop shell has no tests. The tests did not run on macOS or Windows. + ## 0.13.0 · 2026-11-20 The family's colour and layer names, all of them. diff --git a/CLAUDE.md b/CLAUDE.md index 57dff20..d54ccb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ The form* family's media and file utility belt: viewers, batch image tools, 3D v ## Stage -Released (v0.13.0), built and bundled for macOS, Windows and Linux: Phases 1 to 9 of the approved plan, with Phase 2b for formvis and the repository side of Phase 10. Run `./formtools agents sync` after changing a skill and `./formtools agents check` before committing. The plan of record (`DEV_PLAN.md`), `BUILD_NOTES.md` and the root `HASHOUT_LOG.md` ship in the planning sidecar zip; read them, then the in-tree logs (`frontend/`, `backend/`, `src-tauri/`, `setup/` `HASHOUT_LOG.md`), before changing anything. For changing the code route through `.claude/skills/formtools-harness`; for using the app through MCP, `.claude/skills/formtools-driving`. +Released (v0.14.0), built and bundled for macOS, Windows and Linux: Phases 1 to 9 of the approved plan, with Phase 2b for formvis and the repository side of Phase 10. Run `./formtools agents sync` after changing a skill and `./formtools agents check` before committing. The plan of record (`DEV_PLAN.md`), `BUILD_NOTES.md` and the root `HASHOUT_LOG.md` ship in the planning sidecar zip; read them, then the in-tree logs (`frontend/`, `backend/`, `src-tauri/`, `setup/` `HASHOUT_LOG.md`), before changing anything. For changing the code route through `.claude/skills/formtools-harness`; for using the app through MCP, `.claude/skills/formtools-driving`. ## Layout notes @@ -22,6 +22,7 @@ Released (v0.13.0), built and bundled for macOS, Windows and Linux: Phases 1 to - No emoji anywhere; no U+2014 em dash in Markdown (use the interpunct); near-zero comments, with context in the `HASHOUT_LOG.md` files. - Versions are `v*.*.*` with dots. - Vite `server.host` stays `false` with a pinned port. +- Tests are added when the owner asks; a change in behaviour updates its tests in the same pull request; every test follows the five rules in `docs/TESTING.md`. `./formtools test` runs them. ## Commits diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8946767..9224159 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,8 @@ python -m compileall -q backend setup CI also boots the engine and probes `/api/health` and `/api/capabilities`, runs `bash -n` over the shell scripts, and fails on an em dash in tracked Markdown or an -emoji in any tracked text. +emoji in any tracked text. `./formtools test` runs the tests; `docs/TESTING.md` says +where they live and what a test must do to be accepted. - Keep each pull request to one change. - Write commit subjects the way the history does: `type(scope): plain sentence (X.Y.Z)`, diff --git a/NOTICE.md b/NOTICE.md index e2c7735..0360530 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -58,6 +58,8 @@ Every dependency gets a row here with its name, version, licence and where it sh | formvis `ffmpeg_fetch.py` and `ffmpeg_record.py`, ported to `backend/app/tools/media/fetch.py` and `record.py`, Copyright (C) 2026 NodeAgentc, Inc. | 1.98.7 | Apache-2.0 | engine | | PyInstaller | 6.22.3 | GPL-2.0 with the bootloader exception | build tool only; the exception covers the frozen engine | | TypeScript, Vite, @tauri-apps/cli | 7.0.2, 8.3.5, 2.12.4 | Apache-2.0, MIT, Apache-2.0 OR MIT | build tools only | +| vitest | 5.0.5 | MIT | test only, not shipped | +| happy-dom | 21.0.4 | MIT | test only, not shipped | | The three demo folders (pictures, documents, 3D models, sounds and the Demo Pixel font) | generated | Apache-2.0, own work | made on the person's computer by `backend/app/tools/demos`; nothing is bundled in the app and no third-party picture or font is used. The browser demo pages (`demo/`, `demos/family/`, `demos/bench/`) carry the engine's recorded answers for these folders in `assets/recording.js`, made by `scripts/demo-record.py` | ## Trademarks diff --git a/README.md b/README.md index 6004d1d..0eeabc6 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.13.0 + version 0.14.0 TypeScript Python FastAPI engine macOS, Windows, Linux diff --git a/backend/app/__init__.py b/backend/app/__init__.py index f23a6b3..9e78220 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.13.0" +__version__ = "0.14.0" diff --git a/backend/tests/agents/__init__.py b/backend/tests/agents/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/agents/conftest.py b/backend/tests/agents/conftest.py new file mode 100644 index 0000000..2872eed --- /dev/null +++ b/backend/tests/agents/conftest.py @@ -0,0 +1,19 @@ +import pytest + + +@pytest.fixture +def tab(client): + from .support import tab_token + + with tab_token() as headers: + yield headers + + +@pytest.fixture +def no_catalogue(client): + from app.services import bridge + + kept = bridge.catalogue() + bridge.mirror([]) + yield + bridge.mirror(kept) diff --git a/backend/tests/agents/support.py b/backend/tests/agents/support.py new file mode 100644 index 0000000..bacafc2 --- /dev/null +++ b/backend/tests/agents/support.py @@ -0,0 +1,62 @@ +import json +from contextlib import contextmanager + +ORDINARY = (-32700, -32600, -32601, -32602, -32603) + + +def rpc(client, method, params=None, request_id=1, headers=None): + message = {"jsonrpc": "2.0", "id": request_id, "method": method} + if params is not None: + message["params"] = params + return client.post("/mcp", json=message, headers=headers or {}) + + +def well_formed(reply, request_id): + assert isinstance(reply, dict) + assert reply.get("jsonrpc") == "2.0" + assert reply.get("id") == request_id + assert ("result" in reply) != ("error" in reply) + if "error" in reply: + error = reply["error"] + assert isinstance(error["code"], int) and not isinstance(error["code"], bool) + assert isinstance(error["message"], str) and error["message"] + return reply + + +def tool_result(reply): + result = reply["result"] + assert isinstance(result["isError"], bool) + assert isinstance(result["content"], list) and result["content"] + for block in result["content"]: + assert block["type"] == "text" + assert isinstance(block["text"], str) + return result["isError"], result["content"][0]["text"] + + +def call(client, name, arguments=None, headers=None, request_id=7): + reply = rpc(client, "tools/call", {"name": name, "arguments": arguments if arguments is not None else {}}, request_id, headers).json() + return tool_result(well_formed(reply, request_id)) + + +def is_sentence(text): + words = text.split() + return len(words) >= 3 and "Traceback" not in text and not text.startswith("the tool failed") and any(ch.isalpha() for ch in text) + + +@contextmanager +def tab_token(): + from app.services import agents + + token, _ = agents.issue(8240) + try: + yield {agents.INAPP_HEADER: token} + finally: + agents.revoke(token) + + +def listed_tools(client): + return rpc(client, "tools/list").json()["result"]["tools"] + + +def as_json(text): + return json.loads(text) diff --git a/backend/tests/agents/test_bridge_and_live.py b/backend/tests/agents/test_bridge_and_live.py new file mode 100644 index 0000000..94cfbca --- /dev/null +++ b/backend/tests/agents/test_bridge_and_live.py @@ -0,0 +1,182 @@ +import threading + +import pytest + + +from .support import as_json, call + +LOCAL = {"host": "127.0.0.1:80"} +CATALOGUE = [ + {"id": "view.zoom-in", "label": "Zoom in", "group": "View", "description": "Make the picture larger", "keys": ["+"], "secret": "x"}, + {"id": "view.zoom-out", "label": "Zoom out", "group": "View"}, + {"id": "terminal-new", "label": "New terminal"}, + {"label": "no id"}, + "junk", +] + + +@pytest.fixture +def mirrored(client): + from app.services import bridge + + kept = bridge.catalogue() + reply = client.post("/api/commands/catalogue", json={"commands": [c for c in CATALOGUE if isinstance(c, dict)]}).json() + yield reply + bridge.mirror(kept) + + +@pytest.fixture +def window(client): + from app.core import window_key + + with client.websocket_connect("/api/live", headers=LOCAL) as ws: + ws.send_json({"t": "hello", "key": window_key.KEY}) + deadline = threading.Event() + for _ in range(100): + if client.get("/api/mcp/status").json()["window"]: + break + deadline.wait(0.02) + yield ws + + +def run_in_background(client, tab, command, params=None): + box = {} + + def work(): + box["out"] = call(client, "run_command", {"id": command, **({"params": params} if params is not None else {})}, tab) + + thread = threading.Thread(target=work) + thread.start() + return thread, box + + +def test_the_mirrored_catalogue_keeps_only_entries_with_an_id(mirrored): + assert mirrored == {"ok": True, "size": 3} + + +def test_list_commands_shows_window_commands_but_not_the_ones_only_a_person_runs(client, mirrored): + listing = as_json(call(client, "list_commands")[1]) + ids = [c["id"] for c in listing["commands"]] + assert "view.zoom-in" in ids and "view.zoom-out" in ids + assert "terminal-new" not in ids + assert "hint" not in listing + zoom = next(c for c in listing["commands"] if c["id"] == "view.zoom-in") + assert zoom == {"id": "view.zoom-in", "title": "Zoom in", "description": "Make the picture larger"} + + +def test_describe_command_gives_the_window_command_its_group_and_keys_and_drops_unknown_fields(client, mirrored): + described = as_json(call(client, "describe_command", {"id": "view.zoom-in"})[1]) + assert described["group"] == "View" and described["keys"] == ["+"] + assert "secret" not in described + + +def test_describe_command_will_not_describe_a_command_only_a_person_runs(client, mirrored): + failed, text = call(client, "describe_command", {"id": "terminal-new"}) + assert failed is True and "list_commands" in text + + +@pytest.mark.parametrize("command", ["terminal-toggle", "terminal-new", "claude-code", "claude-chat"]) +def test_run_command_refuses_a_command_only_a_person_runs_and_names_it(client, tab, window, command): + failed, text = call(client, "run_command", {"id": command}, tab) + assert failed is True + assert command in text and "person" in text + + +def test_run_command_refuses_an_id_the_window_does_not_have(client, tab, mirrored): + failed, text = call(client, "run_command", {"id": "view.fly"}, tab) + assert failed is True and "list_commands" in text + + +def test_run_command_with_no_window_says_to_open_formtools(client, tab, mirrored): + assert client.get("/api/mcp/status").json()["window"] is False + failed, text = call(client, "run_command", {"id": "view.zoom-in"}, tab) + assert failed is True + assert "No formtools window is open" in text + + +def test_the_status_says_a_window_is_connected_only_while_it_is(client): + from app.core import window_key + + assert client.get("/api/mcp/status").json()["window"] is False + with client.websocket_connect("/api/live", headers=LOCAL) as ws: + ws.send_json({"t": "hello", "key": window_key.KEY}) + seen = False + for _ in range(100): + seen = client.get("/api/mcp/status").json()["window"] + if seen: + break + threading.Event().wait(0.02) + assert seen is True + for _ in range(100): + if not client.get("/api/mcp/status").json()["window"]: + break + threading.Event().wait(0.02) + assert client.get("/api/mcp/status").json()["window"] is False + + +def test_a_socket_without_the_window_key_is_closed_and_never_counts_as_a_window(client): + from starlette.websockets import WebSocketDisconnect + + with client.websocket_connect("/api/live", headers=LOCAL) as ws: + ws.send_json({"t": "hello", "key": "not-the-key"}) + with pytest.raises(WebSocketDisconnect) as closed: + ws.receive_json() + assert closed.value.code == 4403 + assert client.get("/api/mcp/status").json()["window"] is False + + +def test_run_command_reaches_the_window_with_its_params_and_returns_the_windows_answer(client, tab, window, mirrored): + thread, box = run_in_background(client, tab, "view.zoom-in", {"steps": 2}) + event = window.receive_json() + assert event["t"] == "run" and event["command"] == "view.zoom-in" and event["params"] == {"steps": 2} + window.send_json({"t": "result", "id": event["id"], "ok": True, "result": {"zoom": 4}}) + thread.join(5) + assert box["out"] == (False, '{"zoom": 4}') + + +def test_run_events_arrive_in_the_order_they_were_asked_each_with_its_own_id(client, tab, window, mirrored): + seen = [] + for step in range(4): + thread, box = run_in_background(client, tab, "view.zoom-out", {"n": step}) + event = window.receive_json() + seen.append(event) + window.send_json({"t": "result", "id": event["id"], "ok": True, "result": step * 10}) + thread.join(5) + assert box["out"] == (False, str(step * 10)) + assert [e["params"]["n"] for e in seen] == [0, 1, 2, 3] + assert len({e["id"] for e in seen}) == 4 + + +def test_an_answer_for_another_id_is_ignored_and_the_right_one_completes_the_call(client, tab, window, mirrored): + thread, box = run_in_background(client, tab, "view.zoom-in") + event = window.receive_json() + window.send_json({"t": "result", "id": "r-not-this-one", "ok": True, "result": "wrong"}) + window.send_json({"t": "result", "id": event["id"], "ok": True, "result": "right"}) + thread.join(5) + assert box["out"] == (False, "right") + + +def test_a_command_the_window_fails_comes_back_as_a_tool_error_with_the_windows_words(client, tab, window, mirrored): + thread, box = run_in_background(client, tab, "view.zoom-in") + event = window.receive_json() + window.send_json({"t": "result", "id": event["id"], "ok": False, "error": "Open a picture first."}) + thread.join(5) + assert box["out"] == (True, "Open a picture first.") + + +def test_params_that_are_not_an_object_reach_the_window_as_an_empty_object(client, tab, window, mirrored): + box = {} + thread = threading.Thread(target=lambda: box.update(out=call(client, "run_command", {"id": "view.zoom-in", "params": [1, 2]}, tab))) + thread.start() + event = window.receive_json() + assert event["params"] == {} + window.send_json({"t": "result", "id": event["id"], "ok": True, "result": None}) + thread.join(5) + assert box["out"] == (False, "null") + + +def test_only_the_window_key_holder_can_replace_the_catalogue(bare, client, mirrored): + response = bare.post("/api/commands/catalogue", json={"commands": []}) + assert response.status_code == 403 + assert "window" in response.json()["error"] + assert "view.zoom-in" in [c["id"] for c in as_json(call(client, "list_commands")[1])["commands"]] diff --git a/backend/tests/agents/test_mcp_and_http_agree.py b/backend/tests/agents/test_mcp_and_http_agree.py new file mode 100644 index 0000000..ef87a6f --- /dev/null +++ b/backend/tests/agents/test_mcp_and_http_agree.py @@ -0,0 +1,107 @@ +import hashlib +import threading + +import pytest + +from .support import as_json, call + + +@pytest.fixture +def folder(tmp_path): + (tmp_path / "b10.txt").write_text("ten", encoding="utf-8") + (tmp_path / "b2.txt").write_text("two!", encoding="utf-8") + (tmp_path / "zeta").mkdir() + (tmp_path / ".hidden").write_text("h", encoding="utf-8") + return tmp_path + + +def test_fs_list_gives_the_same_folder_through_mcp_and_through_http(client, folder): + failed, text = call(client, "fs_list", {"path": str(folder)}) + assert failed is False + assert as_json(text) == client.get("/api/fs/list", params={"path": str(folder)}).json() + + +def test_fs_list_reports_what_is_on_disk_folders_first_and_numbers_in_counting_order(client, folder): + listing = as_json(call(client, "fs_list", {"path": str(folder)})[1]) + assert [e["name"] for e in listing["entries"]] == ["zeta", "b2.txt", "b10.txt"] + sizes = {e["name"]: e["size"] for e in listing["entries"]} + assert sizes["b2.txt"] == 4 and sizes["b10.txt"] == 3 + assert listing["parent"] == str(folder.parent) + + +def test_fs_list_hidden_flag_agrees_on_both_paths(client, folder): + by_mcp = as_json(call(client, "fs_list", {"path": str(folder), "hidden": True})[1]) + by_http = client.get("/api/fs/list", params={"path": str(folder), "hidden": 1}).json() + assert by_mcp == by_http + assert ".hidden" in [e["name"] for e in by_mcp["entries"]] + + +@pytest.mark.parametrize("make", ["missing", "file", "relative"]) +def test_fs_list_refuses_with_the_same_words_on_both_paths(client, folder, make): + path = {"missing": str(folder / "nowhere"), "file": str(folder / "b2.txt"), "relative": "some/folder"}[make] + failed, text = call(client, "fs_list", {"path": path}) + response = client.get("/api/fs/list", params={"path": path}) + assert failed is True + assert response.status_code >= 400 + assert response.json() == {"ok": False, "error": text} + + +def test_batch_actions_is_the_same_catalogue_on_both_paths(client): + failed, text = call(client, "batch_actions") + assert failed is False + assert as_json(text) == client.get("/api/batch/actions").json() + + +def test_templates_list_is_the_same_on_both_paths(client): + failed, text = call(client, "templates_list") + assert failed is False + assert as_json(text) == client.get("/api/templates").json() + + +def test_hosts_read_is_the_same_on_both_paths(client): + failed, text = call(client, "hosts_read") + assert failed is False + assert as_json(text) == client.get("/api/hosts").json() + + +def test_text_read_returns_the_file_text_on_both_paths(client, tmp_path): + target = tmp_path / "note.txt" + target.write_text("first line\nsecond line\n", encoding="utf-8") + failed, text = call(client, "text_read", {"path": str(target)}) + assert failed is False + by_http = client.get("/api/text", params={"path": str(target)}).json() + assert as_json(text) == by_http + assert "first line\nsecond line\n" in by_http.values() + + +def test_list_commands_names_each_registered_command_once_and_describe_agrees(client, no_catalogue): + listing = as_json(call(client, "list_commands")[1]) + ids = [c["id"] for c in listing["commands"]] + assert ids and len(ids) == len(set(ids)) + assert "hint" in listing + for item in listing["commands"]: + described = as_json(call(client, "describe_command", {"id": item["id"]})[1]) + assert {k: described[k] for k in ("id", "title", "description")} == item + assert described["params"]["type"] == "object" + + +def test_describe_command_refuses_an_unknown_id_and_points_at_list_commands(client, no_catalogue): + failed, text = call(client, "describe_command", {"id": "no.such-command"}) + assert failed is True + assert "list_commands" in text + + +def test_hash_files_then_job_status_give_the_digest_computed_here(client, tmp_path): + target = tmp_path / "data.bin" + target.write_bytes(bytes(range(256)) * 3) + failed, text = call(client, "hash_files", {"paths": [str(target)], "algorithms": ["sha256"]}) + assert failed is False + job = as_json(text) + for _ in range(200): + if job["state"] not in ("queued", "running"): + break + threading.Event().wait(0.02) + job = as_json(call(client, "job_status", {"id": job["id"]})[1]) + item = job["result"]["items"][0] + assert item["size"] == 768 + assert item["hashes"] == {"sha256": hashlib.sha256(target.read_bytes()).hexdigest()} diff --git a/backend/tests/agents/test_mcp_protocol.py b/backend/tests/agents/test_mcp_protocol.py new file mode 100644 index 0000000..4c70658 --- /dev/null +++ b/backend/tests/agents/test_mcp_protocol.py @@ -0,0 +1,196 @@ +import pytest + +from .support import ORDINARY, call, is_sentence, listed_tools, rpc, tool_result, well_formed + +JSON_TYPES = {"object", "string", "integer", "number", "boolean", "array", "null"} + + +def test_a_body_that_is_not_json_gets_the_parse_error_code_with_a_null_id(client): + reply = client.post("/mcp", content=b"{not json", headers={"content-type": "application/json"}).json() + well_formed(reply, None) + assert reply["error"]["code"] == -32700 + + +@pytest.mark.parametrize("body", [{"id": 1, "method": "ping"}, {"jsonrpc": "1.0", "id": 1, "method": "ping"}, {"jsonrpc": "2.0", "id": 1, "method": 5}, "ping", 12]) +def test_a_message_that_is_not_a_json_rpc_2_request_gets_the_invalid_request_code(client, body): + reply = client.post("/mcp", json=body).json() + assert reply["jsonrpc"] == "2.0" + assert reply["error"]["code"] == -32600 + assert "result" not in reply + + +def test_an_unknown_method_gets_method_not_found_and_the_same_id_back(client): + reply = rpc(client, "tools/destroy", request_id="abc-9").json() + well_formed(reply, "abc-9") + assert reply["error"]["code"] == -32601 + + +@pytest.mark.parametrize("request_id", [0, 41, "seven", "0"]) +def test_the_reply_carries_the_id_with_its_type_unchanged(client, request_id): + reply = rpc(client, "ping", request_id=request_id).json() + well_formed(reply, request_id) + assert type(reply["id"]) is type(request_id) + assert reply["result"] == {} + + +def test_a_notification_gets_no_reply_body(client): + response = client.post("/mcp", json={"jsonrpc": "2.0", "method": "notifications/initialized"}) + assert response.status_code == 202 + assert response.content == b"" + + +def test_a_batch_answers_each_request_once_and_skips_notifications(client): + batch = [ + {"jsonrpc": "2.0", "id": "a", "method": "ping"}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "nope"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/list"}, + ] + replies = client.post("/mcp", json=batch).json() + assert [r["id"] for r in replies] == ["a", 2, 3] + for reply, request_id in zip(replies, ["a", 2, 3]): + well_formed(reply, request_id) + assert replies[1]["error"]["code"] == -32601 + assert replies[2]["result"]["tools"] + + +def test_a_batch_of_only_notifications_gets_no_reply_body(client): + response = client.post("/mcp", json=[{"jsonrpc": "2.0", "method": "notifications/initialized"}]) + assert response.status_code == 202 + assert response.content == b"" + + +def test_a_request_not_sent_as_json_is_refused_with_a_sentence(client): + response = client.post("/mcp", content=b'{"jsonrpc":"2.0","id":1,"method":"ping"}', headers={"content-type": "text/plain"}) + assert response.status_code == 415 + reply = response.json() + assert "result" not in reply + assert "application/json" in reply["error"]["message"] + + +@pytest.mark.parametrize("version", ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]) +def test_initialize_agrees_to_a_protocol_version_the_endpoint_says_it_speaks(client, version): + assert version in client.get("/mcp").json()["protocolVersions"] + reply = rpc(client, "initialize", {"protocolVersion": version, "capabilities": {}, "clientInfo": {"name": "lane-test", "version": "1"}}).json() + well_formed(reply, 1) + assert reply["result"]["protocolVersion"] == version + + +def test_initialize_answers_an_unknown_version_with_one_it_speaks(client): + reply = rpc(client, "initialize", {"protocolVersion": "1999-01-01", "capabilities": {}, "clientInfo": {"name": "lane-test", "version": "1"}}).json() + assert reply["result"]["protocolVersion"] in client.get("/mcp").json()["protocolVersions"] + assert reply["result"]["protocolVersion"] != "1999-01-01" + + +def test_initialize_names_the_server_and_offers_tools(client): + response = rpc(client, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "lane-test", "version": "1"}}) + result = response.json()["result"] + described = client.get("/mcp").json() + assert result["serverInfo"] == {"name": described["name"], "version": described["version"]} + assert isinstance(result["capabilities"]["tools"], dict) + assert len(response.headers["mcp-session-id"]) >= 16 + + +def test_two_initialize_calls_get_different_sessions(client): + params = {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "lane-test", "version": "1"}} + first = rpc(client, "initialize", params).headers["mcp-session-id"] + second = rpc(client, "initialize", params).headers["mcp-session-id"] + assert first != second + + +def test_ping_gets_no_session_header(client): + assert "mcp-session-id" not in rpc(client, "ping").headers + + +def test_a_client_that_initialized_is_counted_in_the_status(client): + name = "lane-counted-client" + params = {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": name, "version": "1"}} + rpc(client, "initialize", params) + before = next(c for c in client.get("/api/mcp/status").json()["clients"] if c["name"] == name)["calls"] + rpc(client, "initialize", params) + after = next(c for c in client.get("/api/mcp/status").json()["clients"] if c["name"] == name) + assert after["calls"] == before + 1 + assert after["inapp"] is False + + +def test_every_listed_tool_has_a_unique_name_a_description_and_an_object_schema(client): + tools = listed_tools(client) + names = [t["name"] for t in tools] + assert len(names) == len(set(names)) and len(names) >= 4 + for tool in tools: + assert tool["name"].replace("_", "").isalnum() and len(tool["name"]) <= 64 + assert isinstance(tool["description"], str) and len(tool["description"].split()) >= 3 + schema = tool["inputSchema"] + assert schema["type"] == "object" + properties = schema.get("properties", {}) + assert isinstance(properties, dict) + assert set(schema.get("required", [])) <= set(properties) + for spec in properties.values(): + kinds = spec["type"] if isinstance(spec["type"], list) else [spec["type"]] + assert set(kinds) <= JSON_TYPES + + +def test_tool_annotations_are_booleans_and_a_read_only_tool_is_never_destructive(client): + for tool in listed_tools(client): + notes = tool["annotations"] + for key in ("readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"): + if key in notes: + assert isinstance(notes[key], bool), (tool["name"], key) + if notes.get("readOnlyHint"): + assert notes.get("destructiveHint", False) is False, tool["name"] + + +def test_the_endpoint_description_the_status_count_and_the_listing_name_the_same_tools(client): + names = [t["name"] for t in listed_tools(client)] + assert client.get("/mcp").json()["tools"] == names + assert client.get("/api/mcp/status").json()["tools"] == len(names) + + +def test_the_status_endpoint_points_at_the_mcp_path_on_this_computer(client): + status = client.get("/api/mcp/status").json() + assert status["endpoint"].startswith("http://127.0.0.1:") and status["endpoint"].endswith("/mcp") + assert status["protocolVersions"] == client.get("/mcp").json()["protocolVersions"] + + +def test_calling_a_tool_that_is_not_listed_is_an_invalid_params_error_naming_it(client): + reply = rpc(client, "tools/call", {"name": "format_disk", "arguments": {}}, 5).json() + well_formed(reply, 5) + assert reply["error"]["code"] == -32602 + assert reply["error"]["code"] in ORDINARY + assert "format_disk" in reply["error"]["message"] + + +def test_every_listed_tool_answers_a_call_with_no_arguments_in_the_tool_result_shape(client, tab, no_catalogue): + for tool in listed_tools(client): + failed, text = call(client, tool["name"], {}, tab) + needs = tool["inputSchema"].get("required", []) + if needs: + assert failed is True, tool["name"] + assert is_sentence(text), (tool["name"], text) + else: + assert failed is False, (tool["name"], text) + + +def test_every_tool_with_required_arguments_refuses_wrong_types_with_a_sentence(client, tab, no_catalogue): + checked = 0 + for tool in listed_tools(client): + needs = tool["inputSchema"].get("required", []) + if not needs: + continue + failed, text = call(client, tool["name"], {key: 12345 for key in needs}, tab) + assert failed is True, tool["name"] + assert is_sentence(text), (tool["name"], text) + checked += 1 + assert checked >= 20 + + +def test_arguments_that_are_not_an_object_are_treated_as_missing(client, tab): + reply = rpc(client, "tools/call", {"name": "fs_list", "arguments": ["/"]}, 3, tab).json() + failed, text = tool_result(well_formed(reply, 3)) + assert failed is True and is_sentence(text) + + +def test_a_tool_refusal_is_a_result_and_not_a_protocol_error(client): + reply = rpc(client, "tools/call", {"name": "fs_list", "arguments": {"path": "relative/folder"}}, 11).json() + assert "error" not in reply + assert tool_result(reply) == (True, "the path must be absolute") diff --git a/backend/tests/agents/test_terminal_refusals.py b/backend/tests/agents/test_terminal_refusals.py new file mode 100644 index 0000000..123818c --- /dev/null +++ b/backend/tests/agents/test_terminal_refusals.py @@ -0,0 +1,90 @@ +import pytest +from starlette.websockets import WebSocketDisconnect + +from conftest import window_headers + +REFUSED = "Only the formtools window can do this" +ROUTES = [("get", "/api/terminal", None), ("post", "/api/terminal", {}), ("post", "/api/terminal/claude", {}), ("post", "/api/terminal/x/resize", {"cols": 80, "rows": 24}), ("post", "/api/terminal/x/restart", None), ("delete", "/api/terminal/x", None)] + + +@pytest.fixture +def shell(client): + opened = client.post("/api/terminal", json={"cols": 90, "rows": 20, "title": "lane"}).json() + yield opened + client.delete(f"/api/terminal/{opened['id']}") + + +@pytest.mark.parametrize("method,path,body", ROUTES) +def test_every_terminal_route_refuses_a_caller_without_the_window_key(bare, client, method, path, body): + before = client.get("/api/terminal").json()["terminals"] + response = bare.request(method.upper(), path, json=body) + assert response.status_code == 403 + assert REFUSED in str(response.json()) + assert client.get("/api/terminal").json()["terminals"] == before + + +@pytest.mark.parametrize("origin", ["http://example.com", "https://formtools.example", "file://localhost"]) +def test_a_page_from_another_origin_cannot_open_a_terminal_even_with_the_key(bare, client, origin): + before = client.get("/api/terminal").json()["terminals"] + response = bare.post("/api/terminal", json={}, headers={**window_headers(), "origin": origin}) + assert response.status_code == 403 + assert client.get("/api/terminal").json()["terminals"] == before + + +def test_a_request_addressed_to_another_host_name_is_refused(bare): + response = bare.get("/api/terminal", headers={**window_headers(), "host": "evil.example:8240"}) + assert response.status_code >= 400 + assert "terminals" not in response.text + + +def test_an_opened_terminal_is_listed_until_it_is_closed(client, shell): + assert shell["id"] in [t["id"] for t in client.get("/api/terminal").json()["terminals"]] + assert client.delete(f"/api/terminal/{shell['id']}").json() == {"ok": True} + assert shell["id"] not in [t["id"] for t in client.get("/api/terminal").json()["terminals"]] + + +@pytest.mark.parametrize("size", [{"cols": 9, "rows": 24}, {"cols": 501, "rows": 24}, {"cols": 80, "rows": 3}, {"cols": 80, "rows": 201}, {"cols": "wide", "rows": 24}]) +def test_a_size_outside_the_stated_limits_is_refused(client, shell, size): + assert client.post(f"/api/terminal/{shell['id']}/resize", json=size).status_code in (400, 422) + + +def test_a_size_inside_the_limits_is_accepted(client, shell): + assert client.post(f"/api/terminal/{shell['id']}/resize", json={"cols": 10, "rows": 200}).json() == {"ok": True} + + +@pytest.mark.parametrize("action", ["resize", "restart"]) +def test_acting_on_a_terminal_that_does_not_exist_says_so(client, action): + response = client.post(f"/api/terminal/no-such-terminal/{action}", json={"cols": 80, "rows": 24}) + assert response.status_code == 404 + assert "no such terminal" in str(response.json()) + + +def test_a_title_longer_than_sixty_characters_is_refused(client): + before = client.get("/api/terminal").json()["terminals"] + assert client.post("/api/terminal", json={"title": "t" * 61}).status_code in (400, 422) + assert client.get("/api/terminal").json()["terminals"] == before + + +def test_the_stream_closes_a_socket_that_does_not_send_the_window_key(client, shell): + with client.websocket_connect(f"/api/terminal/{shell['id']}/stream", headers={"host": "127.0.0.1:80"}) as ws: + ws.send_json({"type": "key", "key": "wrong"}) + with pytest.raises(WebSocketDisconnect) as closed: + ws.receive_text() + assert closed.value.code == 4403 + + +def test_the_stream_refuses_a_socket_from_another_origin_before_accepting_it(client, shell): + with pytest.raises(WebSocketDisconnect) as closed: + with client.websocket_connect(f"/api/terminal/{shell['id']}/stream", headers={"host": "127.0.0.1:80", "origin": "http://example.com"}): + pass + assert closed.value.code == 4403 + + +def test_the_stream_for_a_terminal_that_does_not_exist_closes_with_not_found(client): + from app.core import window_key + + with client.websocket_connect("/api/terminal/no-such-terminal/stream", headers={"host": "127.0.0.1:80"}) as ws: + ws.send_json({"type": "key", "key": window_key.KEY}) + with pytest.raises(WebSocketDisconnect) as closed: + ws.receive_text() + assert closed.value.code == 4404 diff --git a/backend/tests/batch/__init__.py b/backend/tests/batch/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/batch/support.py b/backend/tests/batch/support.py new file mode 100644 index 0000000..e335de7 --- /dev/null +++ b/backend/tests/batch/support.py @@ -0,0 +1,59 @@ +import os +import time +from collections import Counter + +from PIL import Image + + +def make_files(folder, names): + paths = [] + for name in names: + target = folder / name + target.write_text(f"content of {name}", encoding="utf-8") + paths.append(str(target)) + return paths + + +def contents(folder): + found = Counter() + for root, _, files in os.walk(folder): + for name in files: + with open(os.path.join(root, name), "rb") as handle: + found[handle.read()] += 1 + return found + + +def names(folder): + return sorted(os.listdir(folder)) + + +def new_names(reply): + return [os.path.basename(item["dst"]) for item in reply["items"]] + + +def rename_plan(client, paths, rules): + return client.post("/api/rename/plan", json={"paths": paths, "rules": rules}) + + +def rename_apply(client, paths, rules): + return client.post("/api/rename/apply", json={"paths": paths, "rules": rules}) + + +def make_picture(path, size=(8, 4), left=(255, 0, 0), right=(0, 0, 255)): + image = Image.new("RGB", size, left) + half = size[0] // 2 + for x in range(half, size[0]): + for y in range(size[1]): + image.putpixel((x, y), right) + image.save(path) + return str(path) + + +def wait_job(client, job, limit=45.0): + end = time.monotonic() + limit + while time.monotonic() < end: + state = client.get(f"/api/jobs/{job['id']}").json() + if state["state"] != "running": + return state + time.sleep(0.1) + raise AssertionError("the batch job did not finish in time") diff --git a/backend/tests/batch/test_batch_run.py b/backend/tests/batch/test_batch_run.py new file mode 100644 index 0000000..e60ab29 --- /dev/null +++ b/backend/tests/batch/test_batch_run.py @@ -0,0 +1,191 @@ +import os +from concurrent.futures import as_completed + +import pytest +from PIL import Image + +from .support import contents, make_picture, wait_job + + +def plan(client, **body): + return client.post("/api/batch/plan", json=body) + + +def run(client, **body): + reply = client.post("/api/batch/run", json=body) + assert reply.status_code == 200, reply.text + return wait_job(client, reply.json()) + + +def test_the_plan_lists_pictures_in_natural_order_and_writes_nothing(client, tmp_path): + for name in ["img10.png", "img2.png", "img1.png"]: + make_picture(tmp_path / name) + (tmp_path / "notes.txt").write_text("x") + out = tmp_path / "out" + reply = plan(client, inputs=[str(tmp_path)], output={"format": "jpeg", "folder": str(out), "naming": "{name}_{n:3}"}).json() + assert [os.path.basename(i["src"]) for i in reply["items"]] == ["img1.png", "img2.png", "img10.png"] + assert [i["dst"] for i in reply["items"]] == [str(out / "img1_001.jpg"), str(out / "img2_002.jpg"), str(out / "img10_003.jpg")] + assert not out.exists() + + +def test_the_plan_reports_a_named_file_that_is_missing_or_not_a_picture(client, tmp_path): + make_picture(tmp_path / "a.png") + (tmp_path / "notes.txt").write_text("x") + reply = plan(client, inputs=[str(tmp_path / "a.png"), str(tmp_path / "notes.txt"), str(tmp_path / "gone.png")]).json() + assert len(reply["items"]) == 1 + assert reply["skipped"] == [ + {"path": str(tmp_path / "notes.txt"), "reason": "not a picture type this run converts"}, + {"path": str(tmp_path / "gone.png"), "reason": "it does not exist"}, + ] + + +def test_the_plan_never_points_two_pictures_at_one_file(client, tmp_path): + (tmp_path / "one").mkdir() + (tmp_path / "two").mkdir() + make_picture(tmp_path / "one" / "a.png") + make_picture(tmp_path / "two" / "a.png") + out = tmp_path / "out" + reply = plan(client, inputs=[str(tmp_path)], recursive=True, output={"folder": str(out)}).json() + assert sorted(i["dst"] for i in reply["items"]) == [str(out / "a (2).png"), str(out / "a.png")] + kept = plan(client, inputs=[str(tmp_path)], recursive=True, output={"folder": str(out), "keep_folders": True}).json() + assert sorted(i["dst"] for i in kept["items"]) == [str(out / "one" / "a.png"), str(out / "two" / "a.png")] + + +def test_a_folder_is_only_searched_below_its_top_level_when_asked(client, tmp_path): + (tmp_path / "deep").mkdir() + make_picture(tmp_path / "top.png") + make_picture(tmp_path / "deep" / "low.png") + flat = plan(client, inputs=[str(tmp_path)]).json() + assert [os.path.basename(i["src"]) for i in flat["items"]] == ["top.png"] + + +@pytest.mark.parametrize( + "output, message", + [ + ({"naming": "{nope}"}, "the naming template has an unknown token {nope}"), + ({"naming": "{name"}, "the naming template has an unmatched brace"), + ({"subfolder": "../up"}, "the subfolder cannot climb out of the destination"), + ({"folder": "relative/out"}, "the output folder must be an absolute path"), + ({"overwrite": "maybe"}, "overwrite must be skip, replace or rename"), + ], +) +def test_a_bad_output_setting_is_refused_with_its_reason(client, tmp_path, output, message): + make_picture(tmp_path / "a.png") + reply = plan(client, inputs=[str(tmp_path)], output=output) + assert reply.status_code == 400 + assert reply.json()["error"] == message + + +def test_a_run_with_no_pictures_is_refused(client, tmp_path): + (tmp_path / "notes.txt").write_text("x") + reply = client.post("/api/batch/run", json={"inputs": [str(tmp_path)]}) + assert reply.status_code == 400 + assert reply.json()["error"] == "there are no pictures to process in those inputs" + + +def test_a_run_writes_every_picture_and_one_broken_file_does_not_stop_the_others(client, tmp_path): + src = tmp_path / "in" + src.mkdir() + for name in ["a.png", "b.png", "d.png"]: + make_picture(src / name) + (src / "c.png").write_bytes(b"this is not a picture") + before = contents(src) + out = tmp_path / "out" + job = run(client, inputs=[str(src)], actions=[{"id": "flip", "params": {"axis": "h"}}], output={"folder": str(out)}) + assert job["state"] == "done" + assert job["done"] == job["total"] == 4 + assert job["result"]["written"] == 3 and job["result"]["failed"] == 1 + assert sorted(job["result"]["outputs"]) == [str(out / "a.png"), str(out / "b.png"), str(out / "d.png")] + assert [e["path"] for e in job["errors"]] == [str(src / "c.png")] + assert sorted(os.listdir(out)) == ["a.png", "b.png", "d.png"] + assert contents(src) == before + with Image.open(out / "a.png") as flipped: + assert flipped.size == (8, 4) + assert flipped.convert("RGB").getpixel((0, 0)) == (0, 0, 255) + assert flipped.convert("RGB").getpixel((7, 3)) == (255, 0, 0) + + +def test_a_chain_of_actions_gives_the_size_and_colours_arithmetic_predicts(client, tmp_path): + make_picture(tmp_path / "a.png", size=(8, 4), left=(200, 100, 0), right=(200, 100, 0)) + out = tmp_path / "out" + chain = [ + {"id": "rotate", "params": {"degrees": 90}}, + {"id": "border", "params": {"size": 3, "color": "#00ff00"}}, + {"id": "invert"}, + ] + job = run(client, inputs=[str(tmp_path / "a.png")], actions=chain, output={"folder": str(out), "naming": "{name}_{width}x{height}"}) + assert job["result"]["written"] == 1 + assert os.listdir(out) == ["a_10x14.png"] + with Image.open(out / "a_10x14.png") as made: + rgb = made.convert("RGB") + assert rgb.size == (10, 14) + assert rgb.getpixel((0, 0)) == (255, 0, 255) + assert rgb.getpixel((5, 7)) == (55, 155, 255) + + +def test_grayscale_makes_every_channel_equal(client, tmp_path): + make_picture(tmp_path / "a.png") + out = tmp_path / "out" + run(client, inputs=[str(tmp_path / "a.png")], actions=[{"id": "grayscale"}], output={"folder": str(out)}) + with Image.open(out / "a.png") as made: + for spot in [(0, 0), (7, 3)]: + r, g, b = made.convert("RGB").getpixel(spot) + assert r == g == b + + +def test_converting_to_another_format_writes_a_file_an_independent_reader_accepts(client, tmp_path): + make_picture(tmp_path / "a.png", left=(0, 0, 0), right=(0, 0, 0)) + out = tmp_path / "out" + job = run(client, inputs=[str(tmp_path / "a.png")], output={"folder": str(out), "format": "bmp"}) + assert job["result"]["outputs"] == [str(out / "a.bmp")] + data = (out / "a.bmp").read_bytes() + assert data[:2] == b"BM" + assert int.from_bytes(data[2:6], "little") == len(data) + assert int.from_bytes(data[18:22], "little") == 8 and int.from_bytes(data[22:26], "little", signed=True) in (4, -4) + + +def test_overwrite_skip_leaves_an_existing_file_untouched(client, tmp_path): + make_picture(tmp_path / "a.png") + out = tmp_path / "out" + out.mkdir() + (out / "a.png").write_bytes(b"already here") + job = run(client, inputs=[str(tmp_path / "a.png")], output={"folder": str(out), "overwrite": "skip"}) + assert job["result"]["written"] == 0 and job["result"]["skipped"] == 1 + assert (out / "a.png").read_bytes() == b"already here" + + +def test_overwrite_rename_keeps_the_existing_file_and_writes_beside_it(client, tmp_path): + src = make_picture(tmp_path / "a.png") + original = (tmp_path / "a.png").read_bytes() + job = run(client, inputs=[src], actions=[{"id": "invert"}]) + assert job["result"]["outputs"] == [str(tmp_path / "a (2).png")] + assert (tmp_path / "a.png").read_bytes() == original + with Image.open(tmp_path / "a (2).png") as made: + assert made.convert("RGB").getpixel((0, 0)) == (0, 255, 255) + + +def test_the_action_list_names_every_action_once_and_a_run_refuses_others(client, tmp_path): + listed = [a["id"] for a in client.get("/api/batch/actions").json()["actions"]] + assert len(listed) == len(set(listed)) + assert {"resize", "crop", "rotate", "flip", "grayscale", "watermark-text", "strip-metadata"} <= set(listed) + make_picture(tmp_path / "a.png") + reply = client.post("/api/batch/run", json={"inputs": [str(tmp_path)], "actions": [{"id": "explode"}]}) + assert reply.status_code == 400 and reply.json()["error"] == "unknown action explode" + assert os.listdir(tmp_path) == ["a.png"] + + +def test_the_worker_pool_finishes_every_job_exactly_once(app): + from app.tools.batch.pool import runner + + futures = {runner.submit(divmod, number, 7)[0]: number for number in range(40)} + results = sorted((futures[f], f.result(timeout=40)) for f in as_completed(futures, timeout=40)) + assert results == [(n, (n // 7, n % 7)) for n in range(40)] + + +def test_the_pool_uses_one_worker_fewer_than_the_processors_and_never_zero(monkeypatch): + from app.tools.batch import pool + + monkeypatch.setattr(pool.os, "cpu_count", lambda: 8) + assert pool.worker_count() == 7 + monkeypatch.setattr(pool.os, "cpu_count", lambda: 1) + assert pool.worker_count() == 1 diff --git a/backend/tests/batch/test_presets.py b/backend/tests/batch/test_presets.py new file mode 100644 index 0000000..1e4bbe4 --- /dev/null +++ b/backend/tests/batch/test_presets.py @@ -0,0 +1,69 @@ +import uuid + +import pytest + + +@pytest.fixture +def preset(client): + name = f"lane-{uuid.uuid4().hex[:8]}" + yield name + client.delete(f"/api/batch/presets/{name}") + + +def find(client, name): + return [p for p in client.get("/api/batch/presets").json()["presets"] if p["name"] == name] + + +def test_a_saved_preset_reads_back_with_its_actions_and_output(client, preset): + body = {"actions": [{"id": "border", "params": {"size": 7, "color": "#ff0000"}}, {"id": "grayscale"}], "output": {"format": "webp", "quality": 55, "naming": "{name}_{n:3}"}} + assert client.put(f"/api/batch/presets/{preset}", json=body).json() == {"ok": True, "name": preset} + found = find(client, preset) + assert len(found) == 1 + assert [a["id"] for a in found[0]["actions"]] == ["border", "grayscale"] + assert found[0]["actions"][0]["params"]["size"] == 7 + assert found[0]["actions"][0]["params"]["color"] == "#ff0000" + assert found[0]["output"]["format"] == "webp" + assert found[0]["output"]["quality"] == 55 + assert found[0]["output"]["naming"] == "{name}_{n:3}" + + +def test_saving_again_under_the_same_name_replaces_the_preset(client, preset): + client.put(f"/api/batch/presets/{preset}", json={"actions": [{"id": "sepia"}]}) + client.put(f"/api/batch/presets/{preset}", json={"actions": [{"id": "invert"}]}) + found = find(client, preset) + assert len(found) == 1 and [a["id"] for a in found[0]["actions"]] == ["invert"] + + +def test_a_deleted_preset_is_gone_and_cannot_be_deleted_twice(client, preset): + client.put(f"/api/batch/presets/{preset}", json={}) + assert client.delete(f"/api/batch/presets/{preset}").json() == {"ok": True} + assert find(client, preset) == [] + again = client.delete(f"/api/batch/presets/{preset}") + assert again.status_code == 404 + assert again.json()["error"] == "there is no preset with that name" + + +def test_a_preset_name_with_other_characters_is_refused(client): + reply = client.put("/api/batch/presets/bad.name", json={}) + assert reply.status_code == 400 + assert reply.json()["error"] == "a preset name is 1 to 64 letters, digits, spaces, dashes or underscores" + assert find(client, "bad.name") == [] + + +def test_a_preset_with_an_unknown_action_is_refused_and_not_saved(client, preset): + reply = client.put(f"/api/batch/presets/{preset}", json={"actions": [{"id": "explode"}]}) + assert reply.status_code == 400 + assert reply.json()["error"] == "unknown action explode" + assert find(client, preset) == [] + + +def test_a_preset_with_an_output_format_that_cannot_be_written_is_refused(client, preset): + reply = client.put(f"/api/batch/presets/{preset}", json={"output": {"format": "psd"}}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the output format is not one formtools can write" + assert find(client, preset) == [] + + +def test_a_preset_quality_outside_1_to_100_is_brought_into_range(client, preset): + client.put(f"/api/batch/presets/{preset}", json={"output": {"quality": 500}}) + assert find(client, preset)[0]["output"]["quality"] == 100 diff --git a/backend/tests/batch/test_regexguard.py b/backend/tests/batch/test_regexguard.py new file mode 100644 index 0000000..8d6e15d --- /dev/null +++ b/backend/tests/batch/test_regexguard.py @@ -0,0 +1,60 @@ +import re + +import pytest + +from app.core.errors import ApiError +from app.tools.batch import regexguard + +from .support import make_files, names, rename_apply, rename_plan + + +def test_a_pattern_that_backtracks_without_end_is_stopped_and_nothing_is_renamed(client, tmp_path): + paths = make_files(tmp_path, ["a" * 40 + "!.txt"]) + rule = {"type": "replace", "regex": True, "find": "(a+)+$", "replace": "x"} + reply = rename_apply(client, paths, [rule]) + assert reply.status_code == 400 + assert reply.json()["error"] == "that regular expression took longer than 1 second and was stopped" + assert names(tmp_path) == ["a" * 40 + "!.txt"] + + +def test_a_broken_pattern_is_refused_with_a_message(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + reply = rename_plan(client, paths, [{"type": "replace", "regex": True, "find": "(a", "replace": "x"}]) + assert reply.status_code == 400 + assert "not valid" in reply.json()["error"] + + +def test_a_pattern_longer_than_256_characters_is_refused(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + reply = rename_plan(client, paths, [{"type": "replace", "regex": True, "find": "a" * 257, "replace": "x"}]) + assert reply.status_code == 400 + assert reply.json()["error"] == "the regular expression is too long" + + +@pytest.mark.parametrize("pattern", ["(a+)+$", "(a*)*b", "(a|aa)+$", "(.*a){12}", "a+b+c+d+"]) +def test_the_guard_refuses_patterns_whose_repeats_can_blow_up(pattern): + with pytest.raises(ApiError) as caught: + regexguard.inline_checked(pattern) + assert caught.value.status == 400 + assert caught.value.message == "that regular expression is too complex to run safely here; simplify the repeats" + + +@pytest.mark.parametrize("pattern", [r"\d+", r"IMG_(\d{4})", "^a|b$", r"[a-z]+\.[a-z]+", "a?b"]) +def test_the_guard_lets_ordinary_patterns_through(pattern): + assert regexguard.inline_checked(pattern) is None + + +@pytest.mark.parametrize( + "pattern, replacement, ignore, count", + [(r"\d+", "#", False, 0), ("a", "b", True, 1), (r"(\w)(\w)", r"\g<2>\g<1>", False, 0)], +) +def test_substitute_agrees_with_the_standard_library(pattern, replacement, ignore, count): + texts = ["Abc123a45", "AaAa", "no digits", ""] + expected = [re.sub(pattern, replacement, t, count=count, flags=re.IGNORECASE if ignore else 0) for t in texts] + assert regexguard.substitute(pattern, replacement, texts, ignore, count) == expected + + +def test_substitute_refuses_a_name_longer_than_1024_characters(): + with pytest.raises(ApiError) as caught: + regexguard.substitute("a", "b", ["a" * 1025], False, 0) + assert caught.value.message == "a name is longer than 1024 characters" diff --git a/backend/tests/batch/test_rename.py b/backend/tests/batch/test_rename.py new file mode 100644 index 0000000..ef8bdb8 --- /dev/null +++ b/backend/tests/batch/test_rename.py @@ -0,0 +1,246 @@ +import os +import time + +import pytest + +from .support import contents, make_files, names, new_names, rename_apply, rename_plan + + +def test_a_counter_numbers_the_files_in_the_order_given_with_padding(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "b.txt", "c.txt"]) + reply = rename_plan(client, paths, [{"type": "counter", "start": 1, "pad": 3}]).json() + assert new_names(reply) == ["a_001.txt", "b_002.txt", "c_003.txt"] + assert names(tmp_path) == ["a.txt", "b.txt", "c.txt"] + + +def test_a_counter_can_start_anywhere_step_and_sit_in_front(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "b.txt", "c.txt"]) + rule = {"type": "counter", "start": 10, "step": 5, "pad": 0, "position": "start", "separator": "-"} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["10-a.txt", "15-b.txt", "20-c.txt"] + + +def test_applying_a_counter_renames_the_files_and_loses_no_content(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "b.txt", "c.txt"]) + before = contents(tmp_path) + reply = rename_apply(client, paths, [{"type": "counter", "start": 1, "pad": 2}]).json() + assert reply["renamed"] == 3 + assert names(tmp_path) == ["a_01.txt", "b_02.txt", "c_03.txt"] + assert contents(tmp_path) == before + assert (tmp_path / "b_02.txt").read_text() == "content of b.txt" + + +@pytest.mark.parametrize( + "mode, expected", + [ + ("upper", "MY HOLIDAY PHOTO.jpg"), + ("lower", "my holiday photo.jpg"), + ("title", "My Holiday Photo.jpg"), + ("sentence", "My holiday photo.jpg"), + ], +) +def test_a_case_change_alters_the_name_and_keeps_the_extension(client, tmp_path, mode, expected): + paths = make_files(tmp_path, ["my HOLIDAY photo.jpg"]) + assert new_names(rename_plan(client, paths, [{"type": "case", "mode": mode}]).json()) == [expected] + + +def test_find_and_replace_changes_every_match_and_ignores_case_by_default(client, tmp_path): + paths = make_files(tmp_path, ["IMG_img_1.png"]) + reply = rename_plan(client, paths, [{"type": "replace", "find": "img", "replace": "pic"}]).json() + assert new_names(reply) == ["pic_pic_1.png"] + + +def test_find_and_replace_can_match_case_and_only_the_first_match(client, tmp_path): + paths = make_files(tmp_path, ["IMG_img_img.png"]) + rule = {"type": "replace", "find": "img", "replace": "pic", "case": True, "all": False} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["IMG_pic_img.png"] + + +def test_find_and_replace_on_the_name_leaves_the_extension_alone(client, tmp_path): + paths = make_files(tmp_path, ["png_scan.png"]) + rule = {"type": "replace", "find": "png", "replace": "x"} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["x_scan.png"] + + +def test_find_and_replace_scoped_to_the_extension_leaves_the_name_alone(client, tmp_path): + paths = make_files(tmp_path, ["jpeg_scan.jpeg"]) + rule = {"type": "replace", "find": "jpeg", "replace": "jpg", "scope": "ext"} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["jpeg_scan.jpg"] + + +def test_a_regular_expression_replace_can_reorder_captured_groups(client, tmp_path): + paths = make_files(tmp_path, ["2024-03-15 trip.txt"]) + rule = {"type": "replace", "regex": True, "find": r"(\d{4})-(\d{2})-(\d{2})", "replace": "$3.$2.$1"} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["15.03.2024 trip.txt"] + + +def test_extension_rules_change_only_the_extension(client, tmp_path): + paths = make_files(tmp_path, ["Shot.JPG"]) + assert new_names(rename_plan(client, paths, [{"type": "extension", "mode": "lower"}]).json()) == ["Shot.jpg"] + assert new_names(rename_plan(client, paths, [{"type": "extension", "mode": "set", "value": ".jpeg"}]).json()) == ["Shot.jpeg"] + + +def test_insert_remove_and_trim_rules_edit_the_name_as_described(client, tmp_path): + paths = make_files(tmp_path, ["abcdef.txt"]) + assert new_names(rename_plan(client, paths, [{"type": "insert", "text": "X", "position": 2}]).json()) == ["abXcdef.txt"] + assert new_names(rename_plan(client, paths, [{"type": "insert", "text": "X", "position": "end"}]).json()) == ["abcdefX.txt"] + assert new_names(rename_plan(client, paths, [{"type": "remove", "from": 1, "count": 3}]).json()) == ["aef.txt"] + spaced = make_files(tmp_path, [" a b__c .txt"]) + assert new_names(rename_plan(client, spaced, [{"type": "trim"}]).json()) == ["a b_c.txt"] + + +def test_rules_run_in_the_order_given(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + first = [{"type": "insert", "text": "b", "position": "end"}, {"type": "case", "mode": "upper"}] + second = list(reversed(first)) + assert new_names(rename_plan(client, paths, first).json()) == ["AB.txt"] + assert new_names(rename_plan(client, paths, second).json()) == ["Ab.txt"] + + +def test_a_date_rule_adds_the_modified_date_of_each_file(client, tmp_path): + paths = make_files(tmp_path, ["note.txt"]) + moment = time.mktime((2021, 7, 4, 12, 0, 0, 0, 0, -1)) + os.utime(paths[0], (moment, moment)) + rule = {"type": "date", "source": "mtime", "format": "%Y%m%d", "position": "start"} + assert new_names(rename_plan(client, paths, [rule]).json()) == ["20210704_note.txt"] + + +def test_a_folder_with_a_dot_in_its_name_is_renamed_whole(client, tmp_path): + (tmp_path / "v1.2").mkdir() + reply = rename_plan(client, [str(tmp_path / "v1.2")], [{"type": "insert", "text": "_final", "position": "end"}, {"type": "extension", "mode": "set", "value": "bak"}]).json() + assert new_names(reply) == ["v1.2_final"] + + +def test_two_files_that_would_get_the_same_name_are_marked_and_refused(client, tmp_path): + paths = make_files(tmp_path, ["a1.txt", "a2.txt"]) + rule = {"type": "replace", "regex": True, "find": r"\d", "replace": ""} + plan = rename_plan(client, paths, [rule]).json() + assert [item["conflict"] for item in plan["items"]] == ["duplicate", "duplicate"] + before = contents(tmp_path) + reply = rename_apply(client, paths, [rule]) + assert reply.status_code == 409 + assert reply.json()["error"] == "2 names conflict or cannot be used; nothing was renamed" + assert names(tmp_path) == ["a1.txt", "a2.txt"] + assert contents(tmp_path) == before + + +def test_a_name_taken_by_a_file_outside_the_rename_is_refused_and_that_file_survives(client, tmp_path): + make_files(tmp_path, ["new.txt"]) + paths = make_files(tmp_path, ["old.txt"]) + rule = {"type": "replace", "find": "old", "replace": "new"} + assert rename_plan(client, paths, [rule]).json()["items"][0]["conflict"] == "exists" + reply = rename_apply(client, paths, [rule]) + assert reply.status_code == 409 + assert reply.json()["error"] == "1 name conflict or cannot be used; nothing was renamed" + assert (tmp_path / "new.txt").read_text() == "content of new.txt" + assert (tmp_path / "old.txt").read_text() == "content of old.txt" + + +def test_a_name_with_a_forbidden_character_is_marked_invalid_and_refused(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + rule = {"type": "insert", "text": "x:y", "position": "end"} + assert rename_plan(client, paths, [rule]).json()["items"][0]["conflict"] == "invalid" + assert rename_apply(client, paths, [rule]).status_code == 409 + assert names(tmp_path) == ["a.txt"] + + +def test_a_rule_that_empties_a_name_is_marked_invalid(client, tmp_path): + paths = make_files(tmp_path, ["abc"]) + rule = {"type": "remove", "from": 0, "count": 3} + assert rename_plan(client, paths, [rule]).json()["items"][0]["conflict"] == "invalid" + + +def test_a_rename_onto_a_name_another_renamed_file_is_leaving_keeps_both_contents(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "aa.txt"]) + before = contents(tmp_path) + reply = rename_apply(client, paths, [{"type": "insert", "text": "a", "position": "start"}]) + assert reply.json()["renamed"] == 2 + assert names(tmp_path) == ["aa.txt", "aaa.txt"] + assert (tmp_path / "aa.txt").read_text() == "content of a.txt" + assert (tmp_path / "aaa.txt").read_text() == "content of aa.txt" + assert contents(tmp_path) == before + + +def test_a_rename_that_changes_nothing_renames_nothing_and_gives_no_undo(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + reply = rename_apply(client, paths, []).json() + assert reply["renamed"] == 0 and reply["undo"] is None + assert rename_plan(client, paths, []).json()["items"][0]["changed"] is False + + +def test_undo_puts_every_name_and_content_back(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "aa.txt", "b.txt"]) + before = contents(tmp_path) + done = rename_apply(client, paths, [{"type": "insert", "text": "a", "position": "start"}, {"type": "extension", "mode": "set", "value": "md"}]).json() + assert names(tmp_path) == ["aa.md", "aaa.md", "ab.md"] + back = client.post("/api/rename/undo", json={"undo": done["undo"]}).json() + assert back["restored"] == 3 + assert names(tmp_path) == ["a.txt", "aa.txt", "b.txt"] + assert all((tmp_path / n).read_text() == f"content of {n}" for n in names(tmp_path)) + assert contents(tmp_path) == before + + +def test_an_undo_can_be_used_only_once(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + done = rename_apply(client, paths, [{"type": "case", "mode": "upper"}]).json() + assert client.post("/api/rename/undo", json={"undo": done["undo"]}).status_code == 200 + again = client.post("/api/rename/undo", json={"undo": done["undo"]}) + assert again.status_code == 404 + assert again.json()["error"] == "there is no undo with that id; only the last 20 renames are kept" + assert names(tmp_path) == ["a.txt"] + + +def test_undo_is_refused_when_a_renamed_file_has_gone(client, tmp_path): + paths = make_files(tmp_path, ["a.txt", "b.txt"]) + done = rename_apply(client, paths, [{"type": "insert", "text": "x", "position": "start"}]).json() + (tmp_path / "xa.txt").unlink() + reply = client.post("/api/rename/undo", json={"undo": done["undo"]}) + assert reply.status_code == 409 + assert reply.json()["error"] == "xa.txt is no longer there, so the rename cannot be undone" + assert names(tmp_path) == ["xb.txt"] + + +def test_undo_is_refused_when_the_old_name_is_taken_again(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + done = rename_apply(client, paths, [{"type": "insert", "text": "x", "position": "start"}]).json() + (tmp_path / "a.txt").write_text("newcomer") + reply = client.post("/api/rename/undo", json={"undo": done["undo"]}) + assert reply.status_code == 409 + assert reply.json()["error"] == "a.txt exists again, so the rename cannot be undone" + assert (tmp_path / "a.txt").read_text() == "newcomer" + assert (tmp_path / "xa.txt").read_text() == "content of a.txt" + + +def test_the_same_rename_through_the_agent_tool_and_the_route_agree(client, tmp_path): + from app.tools.batch import rename_plan_tool + + paths = make_files(tmp_path, ["a.txt", "b.txt"]) + rules = [{"type": "counter", "start": 7, "pad": 2}] + assert rename_plan_tool({"paths": paths, "rules": rules}) == rename_plan(client, paths, rules).json() + + +def test_a_missing_file_is_refused_by_name(client, tmp_path): + reply = rename_plan(client, [str(tmp_path / "ghost.txt")], []) + assert reply.status_code == 404 + assert reply.json()["error"] == "ghost.txt does not exist" + + +def test_an_unknown_rule_and_an_empty_list_are_refused(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + reply = rename_plan(client, paths, [{"type": "shuffle"}]) + assert reply.status_code == 400 and reply.json()["error"] == "unknown rule type shuffle" + empty = rename_plan(client, [], []) + assert empty.status_code == 400 and empty.json()["error"] == "paths must list at least one file or folder" + + +def test_a_folder_and_a_file_inside_it_cannot_be_renamed_together(client, tmp_path): + (tmp_path / "box").mkdir() + inner = make_files(tmp_path / "box", ["a.txt"]) + reply = rename_plan(client, [str(tmp_path / "box")] + inner, [{"type": "case", "mode": "upper"}]) + assert reply.status_code == 400 + assert reply.json()["error"].startswith("a.txt is inside a folder that is renamed too") + + +def test_the_same_path_given_twice_is_renamed_once(client, tmp_path): + paths = make_files(tmp_path, ["a.txt"]) + reply = rename_plan(client, paths + paths, [{"type": "counter", "start": 1}]).json() + assert new_names(reply) == ["a_1.txt"] diff --git a/backend/tests/core/__init__.py b/backend/tests/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/core/support.py b/backend/tests/core/support.py new file mode 100644 index 0000000..fc300c0 --- /dev/null +++ b/backend/tests/core/support.py @@ -0,0 +1,100 @@ +import os +import re +import subprocess +import sys +import time +from pathlib import Path + +BACKEND = Path(__file__).resolve().parents[2] +REPO = BACKEND.parent +REFUSAL_TEXT = "formtools answers this computer's own window and agents only" +CLOSED_URL = "http://127.0.0.1:9" + + +def app_version() -> str: + text = (BACKEND / "app" / "__init__.py").read_text(encoding="utf-8") + return re.search(r"__version__\s*=\s*['\"]([^'\"]+)['\"]", text).group(1) + + +def wait_for(client, job_id: str, until=("done", "failed", "cancelled"), limit: float = 5.0) -> dict: + deadline = time.monotonic() + limit + while True: + reply = client.get(f"/api/jobs/{job_id}").json() + if reply["state"] in until or time.monotonic() > deadline: + return reply + time.sleep(0.01) + + +def run_cli(args, cwd, extra_env=None) -> subprocess.CompletedProcess: + env = {k: v for k, v in os.environ.items() if not k.startswith("FORMTOOLS_")} + env["FORMTOOLS_URL"] = CLOSED_URL + env.update(extra_env or {}) + return subprocess.run([sys.executable, str(REPO / "setup" / "cli.py"), *args], cwd=str(cwd), env=env, capture_output=True, text=True, timeout=30) + + +import shutil +import threading +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def copy_setup(tmp: Path, version_ts: str | None = None, package: dict | None = None) -> Path: + root = tmp / "copy" + (root / "setup").mkdir(parents=True) + for name in ("cli.py", "mcp_stdio.py", "mcpb.py"): + shutil.copy2(REPO / "setup" / name, root / "setup" / name) + shutil.copytree(REPO / "setup" / "mcpb", root / "setup" / "mcpb") + (root / "frontend" / "src").mkdir(parents=True) + shutil.copy2(REPO / "frontend" / "package.json", root / "frontend" / "package.json") + if version_ts is not None: + (root / "frontend" / "src" / "version.ts").write_text(f"export const VERSION = '{version_ts}';\n", encoding="utf-8") + if package is not None: + import json + + (root / "frontend" / "package.json").write_text(json.dumps(package), encoding="utf-8") + return root + + +def run_program(script: Path, args, cwd, extra_env=None, stdin: str | None = None) -> subprocess.CompletedProcess: + env = {k: v for k, v in os.environ.items() if not k.startswith("FORMTOOLS_")} + env["FORMTOOLS_URL"] = CLOSED_URL + env["FORMTOOLS_MCP_URL"] = CLOSED_URL + "/mcp" + env["FORMTOOLS_MCP_AUTOSTART"] = "0" + env["FORMTOOLS_DATA_DIR"] = str(Path(cwd) / "no-data") + env.update(extra_env or {}) + return subprocess.run([sys.executable, str(script), *args], cwd=str(cwd), env=env, capture_output=True, text=True, timeout=30, input=stdin) + + +@contextmanager +def engine_bridge(test_client): + class Relay(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def relay(self, method): + size = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(size) if size else None + headers = {k: v for k, v in self.headers.items() if k.lower() in ("content-type", "accept", "mcp-session-id")} + reply = test_client.request(method, self.path, content=body, headers=headers) + self.send_response(reply.status_code) + for key, value in reply.headers.items(): + if key.lower() not in ("content-length", "transfer-encoding", "connection"): + self.send_header(key, value) + self.send_header("Content-Length", str(len(reply.content))) + self.end_headers() + self.wfile.write(reply.content) + + def do_GET(self): + self.relay("GET") + + def do_POST(self): + self.relay("POST") + + server = ThreadingHTTPServer(("127.0.0.1", 0), Relay) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() diff --git a/backend/tests/core/test_command_lines.py b/backend/tests/core/test_command_lines.py new file mode 100644 index 0000000..e8fd408 --- /dev/null +++ b/backend/tests/core/test_command_lines.py @@ -0,0 +1,219 @@ +import json +import zipfile + +import pytest + +from .support import CLOSED_URL, app_version, copy_setup, engine_bridge, run_program + + +@pytest.fixture +def copy(tmp_path): + return copy_setup(tmp_path, version_ts="7.7.7-copy") + + +def cli(copy, args, **kw): + return run_program(copy / "setup" / "cli.py", args, copy, **kw) + + +def test_cli_without_a_command_prints_usage_and_succeeds(copy): + done = cli(copy, []) + assert done.returncode == 0 and done.stdout.startswith("usage: ./formtools cli COMMAND") + + +def test_cli_unknown_command_prints_usage_to_stderr_and_exits_2(copy): + done = cli(copy, ["frobnicate"]) + assert done.returncode == 2 and done.stdout == "" and "usage: ./formtools cli COMMAND" in done.stderr + + +def test_cli_version_reads_the_window_version_file_and_says_the_engine_is_not_running(copy): + done = cli(copy, ["version"]) + assert (done.returncode, done.stdout) == (0, "formtools 7.7.7-copy\nengine not running\n") + + +def test_cli_version_falls_back_to_package_json_when_version_file_is_absent(tmp_path): + copy = copy_setup(tmp_path, package={"version": "5.4.3"}) + assert cli(copy, ["version"]).stdout.splitlines()[0] == "formtools 5.4.3" + + +def test_cli_version_names_the_running_engine_version(copy, bare): + with engine_bridge(bare) as url: + done = cli(copy, ["version"], extra_env={"FORMTOOLS_URL": url}) + assert done.stdout.splitlines() == ["formtools 7.7.7-copy", f"engine {app_version()}"] + + +def test_cli_says_how_to_start_the_engine_when_it_is_not_answering(copy, tmp_path): + done = cli(copy, ["list", str(tmp_path)]) + assert done.returncode == 1 + assert done.stderr.startswith(f"formtools: the engine is not answering at {CLOSED_URL}") and "Start it with ./formtools boot." in done.stderr + + +def test_cli_list_prints_the_folder_as_json_through_the_running_engine(copy, bare, tmp_path): + folder = tmp_path / "pics" + folder.mkdir() + (folder / "b.png").write_bytes(b"12345") + (folder / "a2.txt").write_text("hi", encoding="utf-8") + (folder / "a10.txt").write_text("hello", encoding="utf-8") + with engine_bridge(bare) as url: + done = cli(copy, ["list", str(folder)], extra_env={"FORMTOOLS_URL": url}) + assert done.returncode == 0, done.stderr + listing = json.loads(done.stdout) + assert [(e["name"], e["size"]) for e in listing["entries"]] == [("a2.txt", 2), ("a10.txt", 5), ("b.png", 5)] + + +def test_cli_list_of_a_missing_folder_exits_1_with_the_engine_sentence(copy, bare, tmp_path): + with engine_bridge(bare) as url: + done = cli(copy, ["list", str(tmp_path / "gone")], extra_env={"FORMTOOLS_URL": url}) + assert done.returncode == 1 and done.stderr.strip() == "formtools: that folder does not exist" + + +def test_cli_rename_prints_the_plan_and_renames_nothing_without_apply(copy, bare, tmp_path): + tmp_path = tmp_path / "shots" + tmp_path.mkdir() + (tmp_path / "IMG_1.jpg").write_bytes(b"x") + (tmp_path / "keep.jpg").write_bytes(b"x") + with engine_bridge(bare) as url: + done = cli(copy, ["rename", "--find", "IMG", "--replace", "trip", str(tmp_path / "IMG_1.jpg"), str(tmp_path / "keep.jpg")], extra_env={"FORMTOOLS_URL": url}) + assert done.returncode == 0, done.stderr + lines = done.stdout.splitlines() + assert f"{tmp_path / 'IMG_1.jpg'} -> trip_1.jpg" in lines + assert f"{tmp_path / 'keep.jpg'} (unchanged)" in lines + assert lines[-2:] == ["1 of 2 names change", "nothing was renamed; add --apply to do it"] + assert sorted(p.name for p in tmp_path.iterdir()) == ["IMG_1.jpg", "keep.jpg"] + + +def test_cli_rename_without_rules_exits_2(copy, tmp_path): + done = cli(copy, ["rename", str(tmp_path)]) + assert done.returncode == 2 and done.stderr.strip() == "formtools: give --find and or --counter" + + +def test_cli_convert_without_inputs_exits_2(copy): + done = cli(copy, ["convert", "--format", "png"]) + assert done.returncode == 2 and done.stderr.strip() == "formtools: give at least one input file or folder" + + +def test_cli_convert_with_an_unreadable_config_file_exits_1(copy, tmp_path): + done = cli(copy, ["convert", "--config", str(tmp_path / "none.json"), str(tmp_path)]) + assert done.returncode == 1 and done.stderr.startswith("formtools: cannot read the config file:") + + +def test_cli_resize_needs_the_longest_side(copy, tmp_path): + done = cli(copy, ["resize", str(tmp_path)]) + assert done.returncode == 2 and "--longest" in done.stderr + + +def mcp(copy, args, **kw): + return run_program(copy / "setup" / "mcp_stdio.py", args, copy, **kw) + + +def test_mcp_bridge_version_matches_the_window_version_file(copy): + assert mcp(copy, ["--version"]).stdout == "formtools 7.7.7-copy\n" + + +def test_mcp_bridge_where_prints_launcher_script_and_url(copy): + where = json.loads(mcp(copy, ["--where", "--url", "http://127.0.0.1:1/mcp"]).stdout) + assert where["url"] == "http://127.0.0.1:1/mcp" + assert where["script"] == str(copy / "setup" / "mcp_stdio.py") + assert where["claude_desktop"]["mcpServers"]["formtools"] == {"command": str(copy / "formtools"), "args": ["mcp"]} + + +def test_mcp_bridge_answers_a_line_that_is_not_json_with_a_parse_error(copy): + done = mcp(copy, [], stdin="this is not json\n") + assert json.loads(done.stdout) == {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} + + +def test_mcp_bridge_without_an_engine_answers_requests_with_a_sentence_and_stays_silent_for_notifications(copy): + lines = json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n" + json.dumps({"jsonrpc": "2.0", "id": 7, "method": "tools/list"}) + "\n" + done = mcp(copy, [], stdin=lines) + replies = [json.loads(line) for line in done.stdout.splitlines()] + assert len(replies) == 1 and replies[0]["id"] == 7 and replies[0]["error"]["code"] == -32000 + assert "not running and could not be started" in replies[0]["error"]["message"] + + +def test_mcp_bridge_relays_tool_listing_from_the_engine(copy, client, bare): + from app.routers import mcp as mcp_router + + request = json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/list"}) + "\n" + with engine_bridge(bare) as url: + done = mcp(copy, ["--url", url + "/mcp"], stdin=request) + reply = json.loads(done.stdout) + assert reply["id"] == 3 + assert sorted(t["name"] for t in reply["result"]["tools"]) == sorted(t.name for t in mcp_router.all_tools()) + + +def test_mcp_bridge_finds_the_engine_from_the_port_file_in_the_data_folder(copy, bare, tmp_path): + data = tmp_path / "data" + data.mkdir() + request = json.dumps({"jsonrpc": "2.0", "id": 9, "method": "tools/list"}) + "\n" + with engine_bridge(bare) as url: + (data / "engine.port").write_text(json.dumps({"pid": 1, "port": int(url.rsplit(":", 1)[1])}), encoding="utf-8") + env = {"FORMTOOLS_PORT": "9", "FORMTOOLS_DATA_DIR": str(data)} + done = run_program(copy / "setup" / "mcp_stdio.py", [], copy, extra_env=env, stdin=request) + env_free = json.loads(done.stdout) + assert env_free["id"] == 9 and "result" in env_free + assert f"using the running engine at {url}/mcp" in done.stderr + + +def mcpb(copy, args): + return run_program(copy / "setup" / "mcpb.py", args, copy) + + +def matched_copy(tmp_path): + copy = copy_setup(tmp_path) + manifest = json.loads((copy / "setup" / "mcpb" / "manifest.json").read_text(encoding="utf-8")) + (copy / "frontend" / "package.json").write_text(json.dumps({"version": manifest["version"]}), encoding="utf-8") + return copy, manifest + + +def test_mcpb_check_accepts_a_manifest_that_matches_package_json(tmp_path): + copy, _ = matched_copy(tmp_path) + done = mcpb(copy, ["--check"]) + assert (done.returncode, done.stdout.strip()) == (0, "[mcpb] manifest is valid and matches package.json") + + +def test_mcpb_check_refuses_a_version_that_differs_from_package_json(tmp_path): + copy, manifest = matched_copy(tmp_path) + (copy / "frontend" / "package.json").write_text(json.dumps({"version": "0.0.1"}), encoding="utf-8") + done = mcpb(copy, ["--check"]) + assert done.returncode == 1 + assert f"[mcpb] manifest version {manifest['version']} differs from package.json 0.0.1" in done.stderr + + +def test_mcpb_check_lists_every_broken_manifest_rule(tmp_path): + copy, manifest = matched_copy(tmp_path) + manifest.update(manifest_version="0.1", name="Form Tools", server={"type": "node", "entry_point": "lib/x.js", "mcp_config": {}}) + manifest.pop("author", None) + (copy / "setup" / "mcpb" / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + lines = set(mcpb(copy, ["--check"]).stderr.splitlines()) + for rule in ("manifest needs author", "manifest_version must be 0.2", "manifest name must be lower-case letters, digits and hyphens", "manifest author needs a name", "server type must be python", "server entry_point must be a file under server/", "server mcp_config needs a command and args"): + assert f"[mcpb] {rule}" in lines + + +def test_mcpb_build_writes_a_zip_holding_the_manifest_and_bridge_with_fixed_dates(tmp_path): + copy, _ = matched_copy(tmp_path) + done = mcpb(copy, ["--build", str(tmp_path / "out")]) + target = tmp_path / "out" / "formtools.mcpb" + assert (done.returncode, done.stdout.strip()) == (0, f"[mcpb] wrote {target}") + with zipfile.ZipFile(target) as z: + assert z.namelist() == ["manifest.json", "server/mcp_stdio.py"] + assert z.read("manifest.json") == (copy / "setup" / "mcpb" / "manifest.json").read_bytes() + assert z.read("server/mcp_stdio.py") == (copy / "setup" / "mcp_stdio.py").read_bytes() + assert all(info.date_time == (1980, 1, 1, 0, 0, 0) for info in z.infolist()) + + +def test_mcpb_build_is_byte_for_byte_repeatable(tmp_path): + copy, _ = matched_copy(tmp_path) + mcpb(copy, ["--build", str(tmp_path / "one")]) + mcpb(copy, ["--build", str(tmp_path / "two")]) + assert (tmp_path / "one" / "formtools.mcpb").read_bytes() == (tmp_path / "two" / "formtools.mcpb").read_bytes() + + +def test_mcpb_build_refuses_and_writes_nothing_when_the_manifest_is_wrong(tmp_path): + copy, _ = matched_copy(tmp_path) + (copy / "frontend" / "package.json").write_text(json.dumps({"version": "0.0.1"}), encoding="utf-8") + done = mcpb(copy, ["--build", str(tmp_path / "out")]) + assert done.returncode == 1 and not (tmp_path / "out").exists() + + +def test_mcpb_needs_check_or_build(tmp_path): + copy, _ = matched_copy(tmp_path) + assert mcpb(copy, []).returncode == 2 diff --git a/backend/tests/core/test_config_seal_runtime.py b/backend/tests/core/test_config_seal_runtime.py new file mode 100644 index 0000000..f217361 --- /dev/null +++ b/backend/tests/core/test_config_seal_runtime.py @@ -0,0 +1,97 @@ +import hashlib +import hmac +import json +import logging +import os +from pathlib import Path + +import pytest + +from app.core import config, runtime, seal + + +@pytest.mark.parametrize("raw,port", [("", 8240), ("9123", 9123), ("0", 0), ("65535", 65535), ("65536", 8240), ("-1", 8240), ("abc", 8240), (" 7000 ", 7000)]) +def test_engine_port_reads_the_environment_and_falls_back_to_8240(monkeypatch, raw, port): + monkeypatch.setenv("FORMTOOLS_PORT", raw) + assert config.engine_port() == port + + +def test_data_folder_follows_the_environment_and_is_created(monkeypatch, tmp_path): + target = tmp_path / "a" / "b" + monkeypatch.setenv("FORMTOOLS_DATA_DIR", str(target)) + assert config.data_dir() == target and target.is_dir() + cache = config.cache_dir("thumbs", "256") + assert cache == target / "cache" / "thumbs" / "256" and cache.is_dir() + + +@pytest.mark.skipif(not __import__("sys").platform.startswith("linux"), reason="the XDG rule applies on Linux only") +def test_linux_data_folder_uses_an_absolute_xdg_folder_and_ignores_a_relative_one(monkeypatch, tmp_path): + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg")) + assert config.platform_data_dir() == tmp_path / "xdg" / "formtools" + monkeypatch.setenv("XDG_DATA_HOME", "relative/xdg") + assert config.platform_data_dir() == Path.home() / ".local" / "share" / "formtools" + + +def test_built_window_folder_is_found_only_when_it_holds_index_html(monkeypatch, tmp_path): + monkeypatch.setenv("FORMTOOLS_DIST", str(tmp_path)) + assert config.dist_dir() is None + (tmp_path / "index.html").write_text("", encoding="utf-8") + assert config.dist_dir() == tmp_path + + +@pytest.fixture +def sealed(monkeypatch): + key = bytes(range(32)) + monkeypatch.setattr(seal, "_CACHE", {"tried": True, "available": True, "key": key}) + return key + + +def test_sealed_settings_carry_an_hmac_sha256_of_the_sealed_fields(sealed): + signed = seal.sign({"agentAccess": "allowed", "theme": "dark"}) + expected = hmac.new(sealed, b'{"agentAccess":"allowed"}', hashlib.sha256).hexdigest() + assert signed == {"agentAccess": "allowed", "theme": "dark", "seal": expected} + + +def test_signed_settings_read_back_as_sealed_ok(sealed): + view = seal.effective(seal.sign({"agentAccess": "allowed", "theme": "dark"})) + assert view == {"agentAccess": "allowed", "theme": "dark", "seal": "ok", "sealBroken": False} + + +def test_hand_loosened_agent_access_is_put_back_to_ask_and_marked_broken(sealed): + stored = seal.sign({"agentAccess": "blocked"}) + stored["agentAccess"] = "allowed" + view = seal.effective(stored) + assert (view["agentAccess"], view["seal"], view["sealBroken"]) == ("ask", "broken", True) + + +def test_unsigned_settings_that_do_not_loosen_access_are_left_alone(sealed): + assert seal.effective({"agentAccess": "blocked"}) == {"agentAccess": "blocked", "seal": "unsealed", "sealBroken": False} + + +def test_without_a_keychain_settings_are_read_as_unavailable_and_signed_without_a_seal(monkeypatch): + monkeypatch.setattr(seal, "_CACHE", {"tried": True, "available": False, "key": None}) + assert seal.effective({"agentAccess": "allowed", "seal": "x"}) == {"agentAccess": "allowed", "seal": "unavailable", "sealBroken": False} + assert seal.sign({"agentAccess": "allowed", "seal": "old"}) == {"agentAccess": "allowed"} + + +def test_engine_log_is_written_in_the_logs_folder_and_names_the_process(tmp_path): + try: + path = runtime.start_logging(tmp_path) + logging.getLogger("formtools").info("a line from the test") + for handler in logging.getLogger("formtools").handlers: + handler.flush() + text = path.read_text(encoding="utf-8") + finally: + runtime.stop_logging() + assert path == tmp_path / "Logs" / "formtools-engine.log" + assert f"engine started, pid {os.getpid()}" in text and "a line from the test" in text + assert not any(h.get_name() == "formtools-file" for h in logging.getLogger("uvicorn").handlers) + + +def test_port_file_records_this_process_and_release_removes_only_its_own_files(tmp_path): + runtime.write_port(tmp_path, 51234) + assert json.loads((tmp_path / "engine.port").read_text()) == {"pid": os.getpid(), "port": 51234} + (tmp_path / "engine.lock").write_text(json.dumps({"pid": os.getpid() + 100000}), encoding="utf-8") + runtime.release(tmp_path) + assert not (tmp_path / "engine.port").exists() + assert (tmp_path / "engine.lock").exists() diff --git a/backend/tests/core/test_errors_guard_system.py b/backend/tests/core/test_errors_guard_system.py new file mode 100644 index 0000000..a9e7828 --- /dev/null +++ b/backend/tests/core/test_errors_guard_system.py @@ -0,0 +1,87 @@ +import pytest + +from conftest import ORIGIN, PORT + +from .support import REFUSAL_TEXT, app_version + + +def test_unknown_address_is_answered_as_a_sentence_in_the_error_shape(client): + reply = client.get("/api/no-such-route-here") + assert (reply.status_code, reply.json()) == (404, {"ok": False, "error": "nothing is served at that address"}) + + +def test_missing_query_value_names_the_field_in_the_sentence(client): + reply = client.get("/api/fs/list") + assert (reply.status_code, reply.json()) == (400, {"ok": False, "error": "the request is missing or has a bad value for path"}) + + +def test_query_value_of_the_wrong_type_names_the_field(client, tmp_path): + reply = client.get("/api/fs/list", params={"path": str(tmp_path), "hidden": "lots"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the request is missing or has a bad value for hidden") + + +def test_health_names_the_app_and_its_own_version(client): + assert client.get("/api/health").json() == {"ok": True, "app": "formtools", "version": app_version()} + + +def test_capabilities_report_the_same_version_as_health(client): + caps = client.get("/api/capabilities").json() + assert caps["version"] == client.get("/api/health").json()["version"] + assert caps["os"] == {"linux": "linux", "darwin": "macos", "win32": "windows"}[__import__("sys").platform] + + +def test_capabilities_formats_hold_each_media_family_once(client): + formats = client.get("/api/capabilities").json()["formats"] + assert set(formats) == {"image", "video", "audio", "model", "text"} + for kind in ("video", "audio", "model", "text"): + assert len(formats[kind]) == len(set(formats[kind])) + for key in ("native", "engine"): + assert len(formats["image"][key]) == len(set(formats["image"][key])) + + +def test_engine_refuses_a_request_addressed_to_a_foreign_host(bare): + reply = bare.get("/api/health", headers={"host": "evil.example"}) + assert (reply.status_code, reply.json()) == (403, {"ok": False, "error": REFUSAL_TEXT}) + + +def test_engine_refuses_its_own_name_on_another_port(bare): + reply = bare.get("/api/health", headers={"host": f"127.0.0.1:{PORT + 1}"}) + assert reply.status_code == 403 and reply.json()["error"] == REFUSAL_TEXT + + +@pytest.mark.parametrize("origin", ["http://evil.example", "https://127.0.0.1:5240", "http://127.0.0.1:5999", "null", "http://192.168.1.2:5240"]) +def test_engine_refuses_pages_from_other_origins(bare, origin): + reply = bare.get("/api/health", headers={"origin": origin}) + assert reply.status_code == 403 and reply.json()["error"] == REFUSAL_TEXT + + +@pytest.mark.parametrize("origin", ["http://127.0.0.1:5240", "http://localhost:5241", ORIGIN, f"http://localhost:{PORT}"]) +def test_engine_answers_its_own_window_origins(bare, origin): + reply = bare.get("/api/health", headers={"origin": origin}) + assert reply.status_code == 200 and reply.json()["ok"] is True + + +def test_localhost_name_is_accepted_as_the_host(bare): + assert bare.get("/api/health", headers={"host": f"localhost:{PORT}"}).json()["ok"] is True + + +@pytest.mark.parametrize( + "host,port,allowed", + [("127.0.0.1:8240", 8240, True), ("LOCALHOST:8240", 8240, True), ("127.0.0.1", 8240, False), ("127.0.0.1:8240", None, False), ("127.0.0.2:8240", 8240, False), ("127.0.0.1:x", 8240, False)], +) +def test_host_rule_needs_a_loopback_name_and_the_listening_port(host, port, allowed): + from app.core import guard + + assert guard.host_allowed(host, port) is allowed + + +def test_write_route_without_the_window_key_is_refused_with_a_sentence(bare): + reply = bare.post("/api/jobs/j1/cancel") + assert (reply.status_code, reply.json()) == (403, {"ok": False, "error": "Only the formtools window can do this"}) + + +def test_write_route_with_a_wrong_window_key_is_refused(bare): + from app.core import window_key + + reply = bare.post("/api/jobs/j1/cancel", headers={window_key.HEADER: window_key.KEY + "x"}) + assert reply.status_code == 403 and reply.json()["error"] == "Only the formtools window can do this" diff --git a/backend/tests/core/test_filetypes_registry.py b/backend/tests/core/test_filetypes_registry.py new file mode 100644 index 0000000..5fb44ee --- /dev/null +++ b/backend/tests/core/test_filetypes_registry.py @@ -0,0 +1,82 @@ +import mimetypes +import pkgutil + +import pytest + +from app.core import filetypes, registry + + +@pytest.mark.parametrize( + "name,ext", + [("photo.JPG", "jpg"), ("/a/b.c/archive.tar.gz", "gz"), (".bashrc", ""), ("README", ""), ("C:\\x\\y.Tiff", "tiff"), ("dir.d/file", ""), ("trailing.", "")], +) +def test_extension_is_the_lower_case_text_after_the_last_dot_of_the_file_name(name, ext): + assert filetypes.ext_of(name) == ext + + +@pytest.mark.parametrize( + "ext,family", + [("cr3", "image"), ("nef", "image"), ("heic", "image"), ("mov", "video"), ("flac", "audio"), ("usdz", "model"), ("stl", "model"), ("pdf", "pdf"), ("woff2", "font"), ("7z", "archive"), ("tsx", "text"), ("fvd", "family"), ("xyz123", "other"), ("", "other")], +) +def test_each_extension_falls_in_its_media_family(ext, family): + assert filetypes.classify(ext) == family + + +def test_raw_camera_formats_are_images(): + assert all(filetypes.classify(ext) == "image" for ext in filetypes.RAW) + + +@pytest.mark.parametrize("name,media", [("a.jpg", "image/jpeg"), ("a.gif", "image/gif"), ("a.zip", "application/zip"), ("a.html", "text/html")]) +def test_common_formats_get_the_standard_media_type(name, media): + assert filetypes.content_type(name) == media == mimetypes.guess_type(name)[0] + + +def test_text_formats_unknown_to_the_system_are_served_as_utf8_text(monkeypatch): + monkeypatch.setattr(mimetypes, "guess_type", lambda name, strict=True: (None, None)) + assert filetypes.content_type("Cargo.lock") == "text/plain; charset=utf-8" + assert filetypes.content_type("blob.qqq") == "application/octet-stream" + + +def test_every_tool_module_loads_and_registers_one_tool(client): + from app import tools as package + + modules = sorted(info.name for info in pkgutil.iter_modules(package.__path__) if not info.name.startswith("_")) + assert registry.failed() == {} + assert len(registry.tools()) == len(modules) + + +def test_capabilities_list_every_registered_tool_once(client): + listed = client.get("/api/capabilities").json()["tools"] + assert sorted(listed) == sorted(tool.id for tool in registry.tools()) + assert len(listed) == len(set(listed)) + + +def test_every_tool_with_routes_answers_a_plain_get_on_one_of_them(client): + assert registry.tools() + quiet = [] + for tool in registry.tools(): + plain = [r.path for router in tool.routers for r in router.routes if "GET" in r.methods and "{" not in r.path and not any(p.field_info.is_required() for p in r.dependant.query_params)] + if not plain: + continue + answered = [client.get(path) for path in plain[:3]] + if not any(reply.status_code == 200 for reply in answered): + quiet.append(tool.id) + assert quiet == [] + + +def test_tool_effects_are_limited_to_reads_adds_alters(): + with pytest.raises(ValueError, match="must declare its effect as one of reads, adds, alters"): + registry.McpTool("x", "x", {}, lambda a: None, effect="deletes") + + +def test_registering_the_same_tool_id_twice_is_refused(client): + existing = registry.tools()[0] + with pytest.raises(ValueError, match=f"tool {existing.id} is already registered"): + registry.register(registry.Tool(id=existing.id, title="again")) + + +def test_command_lookup_finds_a_listed_command_and_none_for_unknown(client): + listed = registry.commands() + if listed: + assert registry.command(listed[0].id) is listed[0] + assert registry.command("no-such-command-anywhere") is None diff --git a/backend/tests/core/test_fs_routes.py b/backend/tests/core/test_fs_routes.py new file mode 100644 index 0000000..7f10974 --- /dev/null +++ b/backend/tests/core/test_fs_routes.py @@ -0,0 +1,186 @@ +import pytest + + +@pytest.fixture +def tree(tmp_path): + root = tmp_path / "shoot" + root.mkdir() + (root / "frame10.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 7) + (root / "frame2.png").write_bytes(b"\x89PNG\r\n\x1a\n") + (root / "Frame1.png").write_bytes(b"abc") + (root / "notes.md").write_text("# hello\n", encoding="utf-8") + (root / "clip.MOV").write_bytes(b"\x00" * 12) + (root / ".secret").write_text("hidden", encoding="utf-8") + (root / "zeta").mkdir() + (root / "alpha").mkdir() + (root / "alpha" / "inner").mkdir() + (root / ".cache").mkdir() + (root / ".cache" / "deep").mkdir() + return root + + +def names(reply): + return [entry["name"] for entry in reply["entries"]] + + +def test_listing_puts_folders_first_then_files_in_natural_number_order(client, tree): + reply = client.get("/api/fs/list", params={"path": str(tree)}).json() + assert names(reply) == ["alpha", "zeta", "clip.MOV", "Frame1.png", "frame2.png", "frame10.png", "notes.md"] + + +def test_listing_hides_dot_files_unless_hidden_is_asked_for(client, tree): + plain = names(client.get("/api/fs/list", params={"path": str(tree)}).json()) + shown = names(client.get("/api/fs/list", params={"path": str(tree), "hidden": 1}).json()) + assert ".secret" not in plain and ".cache" not in plain + assert set(shown) - set(plain) == {".secret", ".cache"} + + +def test_listing_reports_each_file_size_in_bytes_written(client, tree): + entries = {e["name"]: e for e in client.get("/api/fs/list", params={"path": str(tree)}).json()["entries"]} + assert entries["frame10.png"]["size"] == 15 + assert entries["Frame1.png"]["size"] == 3 + assert entries["notes.md"]["size"] == len("# hello\n") + assert entries["alpha"]["size"] == 0 + + +def test_listing_names_kind_extension_and_family_of_each_entry(client, tree): + entries = {e["name"]: e for e in client.get("/api/fs/list", params={"path": str(tree)}).json()["entries"]} + assert (entries["clip.MOV"]["kind"], entries["clip.MOV"]["ext"], entries["clip.MOV"]["type"]) == ("file", "mov", "video") + assert (entries["notes.md"]["ext"], entries["notes.md"]["type"]) == ("md", "text") + assert (entries["frame2.png"]["ext"], entries["frame2.png"]["type"]) == ("png", "image") + assert (entries["alpha"]["kind"], entries["alpha"]["ext"]) == ("dir", "") + + +def test_listing_gives_each_entry_its_full_path_inside_the_folder(client, tree): + reply = client.get("/api/fs/list", params={"path": str(tree)}).json() + assert reply["path"] == str(tree) + assert reply["parent"] == str(tree.parent) + assert all(entry["path"] == str(tree / entry["name"]) for entry in reply["entries"]) + + +def test_listing_the_filesystem_root_has_no_parent(client): + assert client.get("/api/fs/list", params={"path": "/"}).json()["parent"] is None + + +def test_folder_tree_lists_only_folders_and_says_which_have_subfolders(client, tree): + reply = client.get("/api/fs/dirs", params={"path": str(tree)}).json() + assert [(d["name"], d["has_children"]) for d in reply["dirs"]] == [("alpha", True), ("zeta", False)] + + +def test_folder_tree_shows_hidden_folders_only_when_asked(client, tree): + reply = client.get("/api/fs/dirs", params={"path": str(tree), "hidden": 1}).json() + assert [(d["name"], d["has_children"]) for d in reply["dirs"]] == [(".cache", True), ("alpha", True), ("zeta", False)] + + +def test_folder_tree_hides_a_hidden_grandchild_when_judging_has_children(client, tmp_path): + (tmp_path / "outer" / ".only-hidden").mkdir(parents=True) + plain = client.get("/api/fs/dirs", params={"path": str(tmp_path)}).json()["dirs"] + shown = client.get("/api/fs/dirs", params={"path": str(tmp_path), "hidden": 1}).json()["dirs"] + assert plain == [{"name": "outer", "path": str(tmp_path / "outer"), "has_children": False}] + assert shown[0]["has_children"] is True + + +@pytest.mark.parametrize("route", ["/api/fs/list", "/api/fs/dirs"]) +def test_folder_routes_refuse_a_relative_path_with_a_sentence(client, route): + reply = client.get(route, params={"path": "relative/place"}) + assert (reply.status_code, reply.json()) == (400, {"ok": False, "error": "the path must be absolute"}) + + +@pytest.mark.parametrize("route", ["/api/fs/list", "/api/fs/dirs"]) +def test_folder_routes_say_a_missing_folder_does_not_exist(client, tmp_path, route): + reply = client.get(route, params={"path": str(tmp_path / "gone")}) + assert (reply.status_code, reply.json()) == (404, {"ok": False, "error": "that folder does not exist"}) + + +@pytest.mark.parametrize("route", ["/api/fs/list", "/api/fs/dirs"]) +def test_folder_routes_refuse_a_file_given_as_a_folder(client, tree, route): + reply = client.get(route, params={"path": str(tree / "notes.md")}) + assert (reply.status_code, reply.json()) == (400, {"ok": False, "error": "that path is not a folder"}) + + +@pytest.mark.parametrize("route", ["/api/fs/list", "/api/fs/dirs", "/api/file/raw"]) +def test_path_routes_refuse_an_empty_path(client, route): + reply = client.get(route, params={"path": ""}) + assert (reply.status_code, reply.json()) == (400, {"ok": False, "error": "a path is needed"}) + + +@pytest.mark.parametrize("route", ["/api/fs/list", "/api/fs/dirs", "/api/file/raw"]) +def test_path_routes_refuse_a_path_holding_a_nul_byte(client, tree, route): + reply = client.get(route, params={"path": str(tree) + "\x00/etc"}) + assert (reply.status_code, reply.json()["error"]) == (400, "a path is needed") + + +@pytest.mark.skipif(not hasattr(__import__("os"), "getuid") or __import__("os").getuid() == 0, reason="the root user can read every folder, so a locked folder cannot be shown") +def test_listing_a_folder_without_read_permission_is_refused_with_a_sentence(client, tmp_path): + locked = tmp_path / "locked" + locked.mkdir() + locked.chmod(0) + try: + reply = client.get("/api/fs/list", params={"path": str(locked)}) + finally: + locked.chmod(0o755) + assert (reply.status_code, reply.json()["error"]) == (400, "formtools is not allowed to read that folder") + + +def test_raw_file_route_returns_the_exact_bytes_on_disk(client, tree): + payload = bytes(range(256)) * 3 + (tree / "blob.bin").write_bytes(payload) + reply = client.get("/api/file/raw", params={"path": str(tree / "blob.bin")}) + assert reply.status_code == 200 + assert reply.content == payload + + +@pytest.mark.parametrize( + "name,media", + [ + ("a.png", "image/png"), + ("a.webp", "image/webp"), + ("a.svg", "image/svg+xml"), + ("a.mp4", "video/mp4"), + ("a.mkv", "video/x-matroska"), + ("a.flac", "audio/flac"), + ("a.glb", "model/gltf-binary"), + ("a.pdf", "application/pdf"), + ("a.woff2", "font/woff2"), + ], +) +def test_raw_file_route_labels_each_format_with_its_registered_media_type(client, tmp_path, name, media): + (tmp_path / name).write_bytes(b"\x00\x01") + reply = client.get("/api/file/raw", params={"path": str(tmp_path / name)}) + assert reply.headers["content-type"].split(";")[0].strip() == media + + +def test_raw_file_route_serves_markdown_as_utf8_text(client, tree): + reply = client.get("/api/file/raw", params={"path": str(tree / "notes.md")}) + kind = reply.headers["content-type"].replace(" ", "").lower() + assert kind.startswith("text/markdown") and "charset=utf-8" in kind + assert reply.text == "# hello\n" + + +def test_raw_file_route_says_a_missing_file_does_not_exist(client, tree): + reply = client.get("/api/file/raw", params={"path": str(tree / "nope.png")}) + assert (reply.status_code, reply.json()) == (404, {"ok": False, "error": "that file does not exist"}) + + +def test_raw_file_route_refuses_a_folder(client, tree): + reply = client.get("/api/file/raw", params={"path": str(tree / "alpha")}) + assert (reply.status_code, reply.json()) == (400, {"ok": False, "error": "that path is not a file"}) + + +def test_raw_file_route_refuses_a_relative_path(client): + reply = client.get("/api/file/raw", params={"path": "notes.md"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the path must be absolute") + + +def test_home_route_names_the_home_folder_first_and_lists_known_folders_that_exist(client): + from pathlib import Path + + home = Path.home() + (home / "Pictures").mkdir(exist_ok=True) + reply = client.get("/api/fs/home").json() + assert reply["home"] == str(home) + assert reply["roots"][0] == {"name": "Home", "path": str(home)} + assert {"name": "Pictures", "path": str(home / "Pictures")} in reply["roots"] + listed = {root["name"] for root in reply["roots"][1:]} + for name in ("Desktop", "Documents", "Downloads", "Movies", "Videos", "Music"): + assert (name in listed) == (home / name).is_dir() diff --git a/backend/tests/core/test_jobs.py b/backend/tests/core/test_jobs.py new file mode 100644 index 0000000..0e6f6a7 --- /dev/null +++ b/backend/tests/core/test_jobs.py @@ -0,0 +1,117 @@ +import threading + +from app.core import jobs +from app.core.errors import ApiError + +from .support import wait_for + + +def test_job_started_runs_to_done_and_reports_its_result(client): + def work(job): + for name in ("a.png", "b.png", "c.png"): + job.step(current=name) + return {"written": 3} + + job = jobs.start("test-batch", "Three pictures", 3, work) + reply = wait_for(client, job.id) + assert (reply["state"], reply["done"], reply["total"], reply["current"], reply["result"]) == ("done", 3, 3, "c.png", {"written": 3}) + assert reply["kind"] == "test-batch" and reply["title"] == "Three pictures" + assert reply["finished"] >= reply["started"] + + +def test_running_job_shows_as_running_and_is_listed_newest_first(client): + gate = threading.Event() + first = jobs.start("test", "first", 1, lambda job: gate.wait(2)) + second = jobs.start("test", "second", 1, lambda job: gate.wait(2)) + try: + listed = [item["id"] for item in client.get("/api/jobs").json()["jobs"]] + assert listed.index(second.id) < listed.index(first.id) + assert client.get(f"/api/jobs/{first.id}").json()["state"] == "running" + finally: + gate.set() + assert wait_for(client, second.id)["state"] == "done" + + +def test_cancel_route_stops_a_job_that_checks_for_cancel(client): + started = threading.Event() + + def work(job): + started.set() + for _ in range(200): + job.check() + threading.Event().wait(0.01) + return "finished anyway" + + job = jobs.start("test", "long", 200, work) + started.wait(2) + reply = client.post(f"/api/jobs/{job.id}/cancel") + assert reply.status_code == 200 and reply.json()["id"] == job.id + final = wait_for(client, job.id) + assert (final["state"], final["result"]) == ("cancelled", None) + + +def test_job_that_returns_after_cancel_counts_as_cancelled(client): + gate = threading.Event() + job = jobs.start("test", "ignores cancel", 1, lambda j: gate.wait(2) and "value") + client.post(f"/api/jobs/{job.id}/cancel") + gate.set() + assert wait_for(client, job.id)["state"] == "cancelled" + + +def test_job_raising_an_api_error_fails_with_its_sentence(client): + def work(job): + raise ApiError(400, "that picture cannot be read") + + final = wait_for(client, jobs.start("test", "bad", 1, work).id) + assert final["state"] == "failed" + assert final["errors"] == [{"path": "", "error": "that picture cannot be read"}] + + +def test_job_crashing_fails_and_names_the_exception(client, capsys): + def work(job): + raise ValueError("bad width") + + final = wait_for(client, jobs.start("test", "crash", 1, work).id) + assert final["state"] == "failed" + assert final["errors"] == [{"path": "", "error": "ValueError: bad width"}] + + +def test_job_keeps_per_file_errors_but_at_most_five_hundred(client): + def work(job): + for n in range(520): + job.error(f"/p/{n}", "unreadable") + return {"failed": 520} + + final = wait_for(client, jobs.start("test", "many errors", 0, work).id) + assert final["state"] == "done" + assert len(final["errors"]) == 500 and final["errors"][0] == {"path": "/p/0", "error": "unreadable"} + + +def test_step_can_set_progress_and_change_the_total(client): + def work(job): + job.step(done=5, total=10, current="half") + job.step() + return None + + final = wait_for(client, jobs.start("test", "steps", 2, work).id) + assert (final["done"], final["total"], final["current"]) == (6, 10, "half") + + +def test_negative_total_is_counted_as_zero(client): + assert wait_for(client, jobs.start("test", "neg", -4, lambda j: None).id)["total"] == 0 + + +def test_unknown_job_is_answered_with_a_sentence(client): + for reply in (client.get("/api/jobs/j999999"), client.post("/api/jobs/j999999/cancel")): + assert (reply.status_code, reply.json()) == (404, {"ok": False, "error": "there is no job with that id"}) + + +def test_only_the_newest_finished_jobs_are_kept(client, monkeypatch): + monkeypatch.setattr(jobs, "KEEP", 3) + made = [] + for n in range(6): + made.append(jobs.start("test", f"keep {n}", 0, lambda j: None)) + wait_for(client, made[-1].id) + listed = {item["id"] for item in client.get("/api/jobs").json()["jobs"]} + assert made[-1].id in listed and made[0].id not in listed + assert len(listed) <= 4 diff --git a/backend/tests/files/__init__.py b/backend/tests/files/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/files/support.py b/backend/tests/files/support.py new file mode 100644 index 0000000..c151c24 --- /dev/null +++ b/backend/tests/files/support.py @@ -0,0 +1,68 @@ +import io +import tarfile +import time +import zipfile +from pathlib import Path + + +def finish(client, started: dict, seconds: float = 20.0) -> dict: + job = started + deadline = time.monotonic() + seconds + while job["state"] == "running": + if time.monotonic() > deadline: + raise AssertionError(f"job {job['id']} did not finish") + time.sleep(0.02) + job = client.get(f"/api/jobs/{job['id']}").json() + return job + + +def post_job(client, url: str, body: dict) -> dict: + reply = client.post(url, json=body) + assert reply.status_code == 200, reply.text + return finish(client, reply.json()) + + +def tree(root: Path) -> dict[str, bytes]: + return {p.relative_to(root).as_posix(): p.read_bytes() for p in sorted(root.rglob("*")) if p.is_file() and not p.is_symlink()} + + +def make_source(base: Path) -> Path: + src = base / "src" + (src / "sub" / "deep").mkdir(parents=True) + (src / "a.txt").write_bytes(b"alpha\nline two\n") + (src / "sub" / "b.bin").write_bytes(bytes(range(256)) * 9000) + (src / "sub" / "deep" / "empty.dat").write_bytes(b"") + (src / "sub" / "deep" / "unicode name \u00e9.txt").write_bytes("caf\u00e9".encode("utf-8")) + return src + + +def tar_with(path: Path, members: list[tuple[tarfile.TarInfo, bytes | None]], mode: str = "w:gz") -> Path: + with tarfile.open(path, mode) as tf: + for info, payload in members: + if payload is None: + tf.addfile(info) + else: + info.size = len(payload) + tf.addfile(info, io.BytesIO(payload)) + return path + + +def file_info(name: str, mode: int = 0o644, mtime: int = 1_000_000_000) -> tarfile.TarInfo: + info = tarfile.TarInfo(name) + info.mode = mode + info.mtime = mtime + return info + + +def link_info(name: str, target: str, kind: bytes = tarfile.SYMTYPE) -> tarfile.TarInfo: + info = tarfile.TarInfo(name) + info.type = kind + info.linkname = target + return info + + +def zip_with(path: Path, members: dict[str, bytes], compression: int = zipfile.ZIP_DEFLATED) -> Path: + with zipfile.ZipFile(path, "w", compression=compression) as zf: + for name, payload in members.items(): + zf.writestr(name, payload) + return path diff --git a/backend/tests/files/test_archive_create.py b/backend/tests/files/test_archive_create.py new file mode 100644 index 0000000..2124453 --- /dev/null +++ b/backend/tests/files/test_archive_create.py @@ -0,0 +1,232 @@ +import io +import os +import random +import stat +import tarfile +import zipfile + +import pytest +import zstandard + +from .support import make_source, post_job, tree + +FORMATS = ["zip", "tar", "tar.gz", "tar.xz", "tar.zst"] + + +def create(client, paths, out, fmt): + job = post_job(client, "/api/archive/create", {"paths": [str(p) for p in paths], "out": str(out), "format": fmt}) + assert job["state"] == "done", job + return job + + +def read_back(path, fmt): + found = {} + if fmt == "zip": + with zipfile.ZipFile(path) as zf: + assert zf.testzip() is None + for info in zf.infolist(): + if not info.is_dir(): + found[info.filename] = zf.read(info) + return found + if fmt == "tar.zst": + stream = zstandard.ZstdDecompressor().stream_reader(open(path, "rb")) + tf = tarfile.open(fileobj=stream, mode="r|") + else: + tf = tarfile.open(path) + with tf: + for member in tf: + if member.isreg(): + found[member.name] = tf.extractfile(member).read() + return found + + +@pytest.mark.parametrize("fmt", FORMATS) +def test_an_archive_made_by_the_app_reads_back_byte_for_byte_with_the_standard_library(client, tmp_path, fmt): + src = make_source(tmp_path) + out = tmp_path / f"made.{fmt}" + job = create(client, [src], out, fmt) + expected = {f"src/{name}": data for name, data in tree(src).items()} + assert read_back(out, fmt) == expected + assert job["result"]["path"] == str(out) + assert job["result"]["files"] == 4 + assert job["result"]["bytes"] == out.stat().st_size + + +@pytest.mark.parametrize("fmt", FORMATS) +def test_a_folder_becomes_an_archive_entry_for_every_subfolder_including_empty_ones(client, tmp_path, fmt): + src = tmp_path / "proj" + (src / "empty").mkdir(parents=True) + (src / "full").mkdir() + (src / "full" / "f.txt").write_bytes(b"x") + out = tmp_path / f"o.{fmt}" + create(client, [src], out, fmt) + if fmt == "zip": + with zipfile.ZipFile(out) as zf: + names = sorted(zf.namelist()) + elif fmt == "tar.zst": + with tarfile.open(fileobj=zstandard.ZstdDecompressor().stream_reader(open(out, "rb")), mode="r|") as tf: + names = sorted(m.name + ("/" if m.isdir() else "") for m in tf) + else: + with tarfile.open(out) as tf: + names = sorted(m.name + ("/" if m.isdir() else "") for m in tf) + assert names == ["proj/", "proj/empty/", "proj/full/", "proj/full/f.txt"] + + +def test_the_zip_made_by_the_app_stores_the_file_modification_time(client, tmp_path): + src = tmp_path / "f.txt" + src.write_bytes(b"data") + os.utime(src, (1_500_000_000, 1_500_000_000)) + out = tmp_path / "t.zip" + create(client, [src], out, "zip") + with zipfile.ZipFile(out) as zf: + stamp = zf.getinfo("f.txt").date_time + assert (2017, 7, 13) <= stamp[:3] <= (2017, 7, 15) + + +def test_the_tar_made_by_the_app_keeps_mtime_and_executable_bit_and_clears_owner(client, tmp_path): + src = tmp_path / "run.sh" + src.write_bytes(b"#!/bin/sh\n") + src.chmod(0o755) + os.utime(src, (1_500_000_000, 1_500_000_000)) + out = tmp_path / "t.tar" + create(client, [src], out, "tar") + with tarfile.open(out) as tf: + info = tf.getmember("run.sh") + assert info.mtime == 1_500_000_000 + assert info.mode & 0o777 == 0o755 + assert (info.uid, info.gid, info.uname, info.gname) == (0, 0, "", "") + + +def test_several_sources_with_the_same_name_get_numbered_names_inside_the_archive(client, tmp_path): + (tmp_path / "one").mkdir() + (tmp_path / "two").mkdir() + (tmp_path / "one" / "same.txt").write_bytes(b"first") + (tmp_path / "two" / "same.txt").write_bytes(b"second") + out = tmp_path / "both.zip" + create(client, [tmp_path / "one" / "same.txt", tmp_path / "two" / "same.txt"], out, "zip") + found = read_back(out, "zip") + assert len(found) == 2 and sorted(found.values()) == [b"first", b"second"] + assert found["same.txt"] == b"first" + + +def test_a_missing_extension_is_added_to_the_archive_name(client, tmp_path): + src = tmp_path / "f.txt" + src.write_bytes(b"x") + job = create(client, [src], tmp_path / "bundle", "tar.gz") + assert job["result"]["path"] == str(tmp_path / "bundle.tar.gz") + assert (tmp_path / "bundle.tar.gz").is_file() + + +def test_an_existing_archive_is_never_overwritten_the_new_one_gets_a_number(client, tmp_path): + src = tmp_path / "f.txt" + src.write_bytes(b"new content") + (tmp_path / "keep.zip").write_bytes(b"precious") + job = create(client, [src], tmp_path / "keep.zip", "zip") + assert (tmp_path / "keep.zip").read_bytes() == b"precious" + assert job["result"]["path"] == str(tmp_path / "keep (2).zip") + assert read_back(tmp_path / "keep (2).zip", "zip") == {"f.txt": b"new content"} + + +def test_an_archive_written_inside_the_folder_it_packs_does_not_contain_itself(client, tmp_path): + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_bytes(b"a") + create(client, [src], src / "self.zip", "zip") + with zipfile.ZipFile(src / "self.zip") as zf: + assert sorted(zf.namelist()) == ["proj/", "proj/a.txt"] + + +@pytest.mark.skipif(os.name == "nt", reason="symbolic links need privileges on Windows") +def test_symbolic_links_are_left_out_and_reported(client, tmp_path): + src = tmp_path / "proj" + src.mkdir() + (src / "real.txt").write_bytes(b"real") + os.symlink(src / "real.txt", src / "link.txt") + out = tmp_path / "o.zip" + job = create(client, [src], out, "zip") + assert read_back(out, "zip") == {"proj/real.txt": b"real"} + assert [os.path.basename(e["path"]) for e in job["errors"]] == ["link.txt"] + assert job["errors"][0]["error"].startswith("skipped:") + + +@pytest.mark.skipif(os.name == "nt", reason="symbolic links need privileges on Windows") +def test_a_source_that_is_only_a_symbolic_link_leaves_nothing_to_archive(client, tmp_path): + (tmp_path / "t.txt").write_bytes(b"x") + os.symlink(tmp_path / "t.txt", tmp_path / "ln") + reply = client.post("/api/archive/create", json={"paths": [str(tmp_path / "ln")], "out": str(tmp_path / "o.zip"), "format": "zip"}) + assert (reply.status_code, reply.json()["error"]) == (400, "there is nothing to put in the archive") + + +def test_a_missing_source_is_refused_by_name(client, tmp_path): + reply = client.post("/api/archive/create", json={"paths": [str(tmp_path / "ghost")], "out": str(tmp_path / "o.zip"), "format": "zip"}) + assert (reply.status_code, reply.json()["error"]) == (404, "ghost does not exist") + + +def test_an_archive_cannot_be_written_into_a_folder_that_does_not_exist(client, tmp_path): + (tmp_path / "f").write_bytes(b"x") + reply = client.post("/api/archive/create", json={"paths": [str(tmp_path / "f")], "out": str(tmp_path / "nope" / "o.zip"), "format": "zip"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the folder for the new archive does not exist") + + +def test_a_relative_output_path_is_refused(client, tmp_path): + (tmp_path / "f").write_bytes(b"x") + reply = client.post("/api/archive/create", json={"paths": [str(tmp_path / "f")], "out": "o.zip", "format": "zip"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the path must be absolute") + + +def test_an_unknown_format_is_refused(client, tmp_path): + (tmp_path / "f").write_bytes(b"x") + reply = client.post("/api/archive/create", json={"paths": [str(tmp_path / "f")], "out": str(tmp_path / "o.rar"), "format": "rar"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the request is missing or has a bad value for format") + assert not (tmp_path / "o.rar").exists() + + +def test_a_file_with_every_byte_value_survives_a_zip_round_trip_through_the_app(client, tmp_path): + payload = bytes(range(256)) * 5000 + b"\r\n\x00\x00" + src = tmp_path / "all.bin" + src.write_bytes(payload) + zipped = create(client, [src], tmp_path / "all.zip", "zip")["result"]["path"] + out = tmp_path / "unpacked" + done = post_job(client, "/api/archive/extract", {"path": zipped, "dest": str(out)}) + assert done["state"] == "done" + assert (out / "all.bin").read_bytes() == payload + + +@pytest.mark.parametrize("fmt", FORMATS) +def test_extracting_what_the_app_created_reproduces_the_source_tree_exactly(client, tmp_path, fmt): + src = make_source(tmp_path) + (src / "sub" / "b.bin").write_bytes(random.Random(7).randbytes(300000)) + archive_path = create(client, [src], tmp_path / f"rt.{fmt}", fmt)["result"]["path"] + out = tmp_path / "unpacked" + done = post_job(client, "/api/archive/extract", {"path": archive_path, "dest": str(out)}) + assert done["state"] == "done" and done["errors"] == [] + assert tree(out / "src") == tree(src) + assert (out / "src" / "sub" / "deep").is_dir() + + +def test_the_executable_bit_survives_a_create_and_extract_round_trip(client, tmp_path): + src = tmp_path / "tool.sh" + src.write_bytes(b"#!/bin/sh\n") + src.chmod(0o755) + path = create(client, [src], tmp_path / "t.tar.gz", "tar.gz")["result"]["path"] + post_job(client, "/api/archive/extract", {"path": path, "dest": str(tmp_path / "out")}) + assert os.stat(tmp_path / "out" / "tool.sh").st_mode & stat.S_IXUSR + + +def test_a_zip_made_by_the_app_is_listed_by_the_app_with_the_same_names_and_sizes(client, tmp_path): + src = make_source(tmp_path) + out = create(client, [src], tmp_path / "l.zip", "zip")["result"]["path"] + listing = client.get("/api/archive/list", params={"path": out}).json() + with zipfile.ZipFile(out) as zf: + expected = [(i.filename, i.file_size) for i in zf.infolist()] + assert [(e["member"], e["size"]) for e in listing["entries"]] == expected + assert listing["format"] == "zip" and listing["total"] == len(expected) and listing["truncated"] is False + + +def test_a_file_dated_before_1980_is_still_archived_into_a_zip_that_reads_back(client, tmp_path): + src = tmp_path / "old.txt" + src.write_bytes(b"ancient") + os.utime(src, (0, 0)) + out = tmp_path / "old.zip" + create(client, [src], out, "zip") + assert read_back(out, "zip") == {"old.txt": b"ancient"} diff --git a/backend/tests/files/test_data.py b/backend/tests/files/test_data.py new file mode 100644 index 0000000..0d2f87a --- /dev/null +++ b/backend/tests/files/test_data.py @@ -0,0 +1,183 @@ +import csv +import hashlib +import io +import sqlite3 + +import pytest + + +def csv_of(client, tmp_path, payload, name="d.csv", **params): + target = tmp_path / name + target.write_bytes(payload if isinstance(payload, bytes) else payload.encode("utf-8")) + reply = client.get("/api/data/csv", params={"path": str(target), **params}) + assert reply.status_code == 200, reply.text + return reply.json() + + +@pytest.mark.parametrize("delimiter", [",", ";", "\t", "|"]) +def test_each_common_delimiter_is_detected_and_the_cells_split_correctly(client, tmp_path, delimiter): + text = "".join(delimiter.join(row) + "\n" for row in [["name", "qty", "note"], ["apple", "3", "red"], ["pear", "5", "green"]]) + result = csv_of(client, tmp_path, text) + assert result["delimiter"] == delimiter + assert result["header"] == ["name", "qty", "note"] + assert result["rows"] == [["apple", "3", "red"], ["pear", "5", "green"]] + assert result["total_rows"] == 2 and result["truncated"] is False + + +def test_a_quoted_cell_with_a_comma_a_quote_and_a_line_break_stays_one_cell(client, tmp_path): + text = 'id,text\n1,"a, b ""quoted""\nsecond line"\n2,plain\n' + result = csv_of(client, tmp_path, text) + assert result["rows"] == [["1", 'a, b "quoted"\nsecond line'], ["2", "plain"]] + + +def test_a_first_row_of_numbers_is_data_not_a_header(client, tmp_path): + result = csv_of(client, tmp_path, "1,2,3\n4,5,6\n7,8,9\n") + assert result["header"] is None + assert result["total_rows"] == 3 + + +def test_text_header_over_numeric_columns_is_taken_as_header(client, tmp_path): + result = csv_of(client, tmp_path, "x,y\n1,2\n3,4\n") + assert result["header"] == ["x", "y"] and result["total_rows"] == 2 + + +def test_a_tsv_file_is_read_as_tab_separated(client, tmp_path): + result = csv_of(client, tmp_path, "a\tb\n1\t2\n", name="d.tsv") + assert result["delimiter"] == "\t" + + +def test_blank_lines_are_skipped(client, tmp_path): + result = csv_of(client, tmp_path, "h1,h2\n\n1,2\n\n\n3,4\n") + assert result["rows"] == [["1", "2"], ["3", "4"]] + + +def test_a_utf8_byte_order_mark_does_not_end_up_in_the_first_header_cell(client, tmp_path): + result = csv_of(client, tmp_path, b"\xef\xbb\xbfname,qty\nx,1\ny,2\n") + assert result["header"] == ["name", "qty"] + + +def test_a_utf16_csv_is_decoded(client, tmp_path): + payload = b"\xff\xfe" + "name,qty\nna\u00efve,1\nb,2\n".encode("utf-16-le") + result = csv_of(client, tmp_path, payload) + assert result["header"] == ["name", "qty"] and result["rows"][0] == ["na\u00efve", "1"] + + +def test_the_row_limit_truncates_but_the_total_counts_every_row(client, tmp_path): + text = "n,v\n" + "".join(f"r{i},{i}\n" for i in range(50)) + result = csv_of(client, tmp_path, text, limit=10) + assert (len(result["rows"]), result["total_rows"], result["truncated"]) == (10, 50, True) + assert result["rows"][0] == ["r0", "0"] and result["rows"][9] == ["r9", "9"] + + +def test_rows_written_by_the_standard_csv_writer_come_back_identical(client, tmp_path): + rows = [["1", "he said \"hi\", twice", "line\nbreak"], ["2", "", "tab\there"], ["3", "caf\u00e9", ";semi"], ["4", " padded ", "x"]] + buffer = io.StringIO(newline="") + writer = csv.writer(buffer) + writer.writerow(["id", "text", "other"]) + writer.writerows(rows) + result = csv_of(client, tmp_path, buffer.getvalue()) + assert result["header"] == ["id", "text", "other"] + assert result["rows"] == rows + + +def test_csv_of_a_missing_file_is_refused(client, tmp_path): + reply = client.get("/api/data/csv", params={"path": str(tmp_path / "ghost.csv")}) + assert (reply.status_code, reply.json()["error"]) == (404, "that file does not exist") + + +def make_db(path): + conn = sqlite3.connect(path) + conn.executescript( + ''' + create table people (id integer primary key, name text not null, score real, photo blob); + insert into people values (1, 'Ada', 9.5, x'0102030405'); + insert into people values (2, 'Grace "G"', null, null); + insert into people values (3, 'Linus', 1e999, null); + create table "odd ""name""" (a, b); + insert into "odd ""name""" values (1, 'x'); + create view top as select name from people where id < 3; + ''' + ) + conn.commit() + conn.close() + return path + + +def test_sqlite_tables_and_views_are_listed_with_columns_row_counts_and_primary_keys(client, tmp_path): + db = make_db(tmp_path / "t.db") + reply = client.get("/api/data/sqlite/tables", params={"path": str(db)}).json() + by_name = {t["name"]: t for t in reply["tables"]} + assert set(by_name) == {"people", 'odd "name"', "top"} + people = by_name["people"] + assert (people["kind"], people["rows"]) == ("table", 3) + assert [(c["name"], c["type"], c["pk"]) for c in people["columns"]] == [("id", "INTEGER", True), ("name", "TEXT", False), ("score", "REAL", False), ("photo", "BLOB", False)] + assert (by_name["top"]["kind"], by_name["top"]["rows"]) == ("view", 2) + assert by_name['odd "name"']["rows"] == 1 + + +def test_sqlite_rows_come_back_with_blobs_as_sizes_nulls_as_none_and_infinity_as_text(client, tmp_path): + db = make_db(tmp_path / "t.db") + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": "people"}).json() + assert reply["columns"] == ["id", "name", "score", "photo"] + assert reply["rows"] == [[1, "Ada", 9.5, {"blob": 5}], [2, 'Grace "G"', None, None], [3, "Linus", "inf", None]] + assert reply["total"] == 3 + + +def test_sqlite_paging_with_offset_and_limit_returns_the_right_slice(client, tmp_path): + db = tmp_path / "p.db" + conn = sqlite3.connect(db) + conn.execute("create table n (v integer)") + conn.executemany("insert into n values (?)", [(i,) for i in range(100)]) + conn.commit() + conn.close() + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": "n", "offset": 40, "limit": 5}).json() + assert reply["rows"] == [[40], [41], [42], [43], [44]] and reply["total"] == 100 + + +def test_a_table_name_with_quotes_can_be_read(client, tmp_path): + db = make_db(tmp_path / "t.db") + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": 'odd "name"'}).json() + assert reply["rows"] == [[1, "x"]] + + +def test_an_unknown_table_is_refused(client, tmp_path): + db = make_db(tmp_path / "t.db") + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": "missing"}) + assert (reply.status_code, reply.json()["error"]) == (404, "that table or view is not in the database") + + +def test_a_table_name_that_is_an_sql_injection_is_not_run(client, tmp_path): + db = make_db(tmp_path / "t.db") + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": 'people"; drop table people; --'}) + assert reply.status_code == 404 + conn = sqlite3.connect(db) + assert conn.execute("select count(*) from people").fetchone() == (3,) + conn.close() + + +def test_reading_a_database_does_not_change_the_file(client, tmp_path): + db = make_db(tmp_path / "t.db") + before = hashlib.sha256(db.read_bytes()).hexdigest() + client.get("/api/data/sqlite/tables", params={"path": str(db)}) + client.get("/api/data/sqlite/rows", params={"path": str(db), "table": "people"}) + assert hashlib.sha256(db.read_bytes()).hexdigest() == before + assert sorted(p.name for p in tmp_path.iterdir()) == ["t.db"] + + +def test_a_file_that_is_not_a_database_is_refused(client, tmp_path): + target = tmp_path / "fake.db" + target.write_bytes(b"this is not sqlite at all, just text") + reply = client.get("/api/data/sqlite/tables", params={"path": str(target)}) + assert (reply.status_code, reply.json()["error"]) == (415, "that file is not a SQLite database") + + +def test_text_stored_in_a_database_that_is_not_valid_utf8_is_shown_with_replacement_marks(client, tmp_path): + db = tmp_path / "b.db" + conn = sqlite3.connect(db) + conn.text_factory = bytes + conn.execute("create table t (s text)") + conn.execute("insert into t values (cast(x'61ff62' as text))") + conn.commit() + conn.close() + reply = client.get("/api/data/sqlite/rows", params={"path": str(db), "table": "t"}).json() + assert reply["rows"] == [["a\ufffdb"]] diff --git a/backend/tests/files/test_extract.py b/backend/tests/files/test_extract.py new file mode 100644 index 0000000..6bf3f7e --- /dev/null +++ b/backend/tests/files/test_extract.py @@ -0,0 +1,386 @@ +import bz2 +import gzip +import io +import lzma +import os +import stat +import tarfile +import zipfile + +import pytest +import zstandard + +from .support import file_info, link_info, post_job, tar_with, tree, zip_with + +LINKS = pytest.mark.skipif(os.name == "nt", reason="symbolic links need privileges on Windows") + + +def extract(client, archive, dest=None, members=None): + body = {"path": str(archive)} + if dest is not None: + body["dest"] = str(dest) + if members is not None: + body["members"] = members + return post_job(client, "/api/archive/extract", body) + + +def errors_by_name(job): + return {e["path"]: e["error"] for e in job["errors"]} + + +def test_a_tar_member_that_climbs_out_with_dot_dot_is_refused_and_nothing_is_written_outside(client, tmp_path): + arc = tar_with(tmp_path / "evil.tar", [(file_info("../escaped.txt"), b"bad"), (file_info("ok.txt"), b"fine")]) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert not (tmp_path / "escaped.txt").exists() + assert tree(dest) == {"ok.txt": b"fine"} + assert errors_by_name(job)["../escaped.txt"] == "refused: the name climbs out of the destination with .." + assert (job["result"]["written"], job["result"]["skipped"]) == (1, 1) + + +def test_a_dot_dot_in_the_middle_of_a_name_is_refused(client, tmp_path): + arc = tar_with(tmp_path / "evil.tar", [(file_info("a/../../escaped.txt"), b"bad")]) + job = extract(client, arc, tmp_path / "dest") + assert not (tmp_path / "escaped.txt").exists() + assert errors_by_name(job)["a/../../escaped.txt"].startswith("refused: the name climbs") + + +def test_an_absolute_member_name_is_refused_and_the_target_file_is_not_created(client, tmp_path): + target = tmp_path / "absolute-target.txt" + arc = tar_with(tmp_path / "evil.tar", [(file_info(str(target)), b"bad")]) + job = extract(client, arc, tmp_path / "dest") + assert not target.exists() + assert errors_by_name(job)[str(target)] == "refused: the name is absolute" + + +def test_a_windows_drive_letter_name_is_refused(client, tmp_path): + arc = zip_with(tmp_path / "evil.zip", {"C:/Windows/evil.txt": b"bad", "fine.txt": b"ok"}) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert tree(dest) == {"fine.txt": b"ok"} + assert errors_by_name(job)["C:/Windows/evil.txt"] == "refused: the name starts with a drive letter" + + +def test_a_backslash_dot_dot_name_in_a_zip_is_refused(client, tmp_path): + arc = zip_with(tmp_path / "evil.zip", {"..\\escaped.txt": b"bad"}) + job = extract(client, arc, tmp_path / "dest") + assert not (tmp_path / "escaped.txt").exists() + assert errors_by_name(job)["..\\escaped.txt"].startswith("refused: the name climbs") + + +def test_a_leading_backslash_name_in_a_zip_is_refused_as_absolute(client, tmp_path): + arc = zip_with(tmp_path / "evil.zip", {"\\etc\\evil": b"bad"}) + job = extract(client, arc, tmp_path / "dest") + assert errors_by_name(job)["\\etc\\evil"] == "refused: the name is absolute" + + +@LINKS +def test_a_symbolic_link_member_is_never_created(client, tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + arc = tar_with(tmp_path / "l.tar", [(link_info("link", str(outside)), None), (file_info("real.txt"), b"r")]) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert not os.path.lexists(dest / "link") + assert errors_by_name(job)["link"] == "skipped: links are never created or followed" + assert (dest / "real.txt").read_bytes() == b"r" + + +def test_a_hard_link_member_is_never_created(client, tmp_path): + secret = tmp_path / "secret.txt" + secret.write_bytes(b"secret") + arc = tar_with(tmp_path / "h.tar", [(link_info("hard", str(secret), tarfile.LNKTYPE), None)]) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert not os.path.lexists(dest / "hard") + assert errors_by_name(job)["hard"] == "skipped: links are never created or followed" + assert secret.read_bytes() == b"secret" + + +@LINKS +def test_a_file_written_through_a_link_planted_earlier_in_the_archive_stays_inside_the_destination(client, tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + arc = tar_with(tmp_path / "two.tar", [(link_info("hop", str(outside)), None), (file_info("hop/pwned.txt"), b"bad")]) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert list(outside.iterdir()) == [] + assert not os.path.islink(dest / "hop") + + +@LINKS +def test_a_symbolic_link_folder_already_in_the_destination_is_not_followed(client, tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + dest = tmp_path / "dest" + dest.mkdir() + os.symlink(outside, dest / "trap") + arc = zip_with(tmp_path / "z.zip", {"trap/pwned.txt": b"bad", "ok.txt": b"fine"}) + job = extract(client, arc, dest) + assert list(outside.iterdir()) == [] + assert errors_by_name(job)["trap/pwned.txt"] == "refused: a folder on the way is a symbolic link" + assert (dest / "ok.txt").read_bytes() == b"fine" + + +@LINKS +def test_a_symbolic_link_entry_inside_a_zip_is_skipped(client, tmp_path): + arc = tmp_path / "s.zip" + with zipfile.ZipFile(arc, "w") as zf: + info = zipfile.ZipInfo("ln") + info.create_system = 3 + info.external_attr = (stat.S_IFLNK | 0o777) << 16 + zf.writestr(info, "/etc/passwd") + zf.writestr("plain.txt", b"p") + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert tree(dest) == {"plain.txt": b"p"} + assert errors_by_name(job)["ln"] == "skipped: links are never created or followed" + + +def test_a_device_node_member_is_skipped(client, tmp_path): + node = tarfile.TarInfo("dev0") + node.type = tarfile.CHRTYPE + arc = tar_with(tmp_path / "d.tar", [(node, None), (file_info("n.txt"), b"n")]) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert errors_by_name(job)["dev0"] == "skipped: not a regular file or folder" + assert tree(dest) == {"n.txt": b"n"} + + +def test_a_dot_slash_prefix_and_doubled_slashes_are_tidied_not_refused(client, tmp_path): + arc = tar_with(tmp_path / "t.tar", [(file_info("./a//b.txt"), b"x")]) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert job["errors"] == [] + assert tree(dest) == {"a/b.txt": b"x"} + + +def test_an_existing_file_is_kept_and_the_new_one_is_written_with_a_number(client, tmp_path): + dest = tmp_path / "dest" + dest.mkdir() + (dest / "a.txt").write_bytes(b"mine") + arc = zip_with(tmp_path / "z.zip", {"a.txt": b"theirs"}) + job = extract(client, arc, dest) + assert (dest / "a.txt").read_bytes() == b"mine" + assert (dest / "a (2).txt").read_bytes() == b"theirs" + assert job["result"]["written"] == 1 + + +def test_extracting_twice_gives_three_distinct_copies(client, tmp_path): + dest = tmp_path / "dest" + arc = zip_with(tmp_path / "z.zip", {"a.txt": b"v"}) + extract(client, arc, dest) + extract(client, arc, dest) + extract(client, arc, dest) + assert sorted(tree(dest)) == ["a (2).txt", "a (3).txt", "a.txt"] + + +def test_without_a_destination_a_new_folder_named_after_the_archive_is_made_beside_it(client, tmp_path): + arc = zip_with(tmp_path / "pack.zip", {"a.txt": b"1"}) + job = extract(client, arc) + assert job["result"]["dest"] == str(tmp_path / "pack") + assert (tmp_path / "pack" / "a.txt").read_bytes() == b"1" + again = extract(client, arc) + assert again["result"]["dest"] == str(tmp_path / "pack (2)") + + +def test_a_double_extension_tar_archive_is_unpacked_into_a_folder_without_either_extension(client, tmp_path): + arc = tar_with(tmp_path / "bundle.tar.gz", [(file_info("a.txt"), b"1")]) + assert extract(client, arc)["result"]["dest"] == str(tmp_path / "bundle") + + +def test_a_destination_that_is_a_file_is_refused(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"a": b"1"}) + (tmp_path / "file").write_bytes(b"x") + reply = client.post("/api/archive/extract", json={"path": str(arc), "dest": str(tmp_path / "file")}) + assert (reply.status_code, reply.json()["error"]) == (400, "the destination is a file, not a folder") + + +def test_only_the_asked_members_and_the_contents_of_asked_folders_are_extracted(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"top.txt": b"t", "dir/one.txt": b"1", "dir/two.txt": b"2", "other/x.txt": b"x"}) + dest = tmp_path / "dest" + job = extract(client, arc, dest, ["dir", "top.txt"]) + assert tree(dest) == {"top.txt": b"t", "dir/one.txt": b"1", "dir/two.txt": b"2"} + assert job["errors"] == [] + + +def test_asking_for_a_member_that_is_not_in_the_archive_is_reported(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"a.txt": b"1"}) + job = extract(client, arc, tmp_path / "dest", ["a.txt", "nope.txt"]) + assert errors_by_name(job) == {"nope.txt": "that member is not in the archive"} + assert (tmp_path / "dest" / "a.txt").exists() + + +def test_file_times_from_the_archive_are_restored(client, tmp_path): + arc = tar_with(tmp_path / "t.tar", [(file_info("a.txt", mtime=1_400_000_000), b"x")]) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert int(os.stat(dest / "a.txt").st_mtime) == 1_400_000_000 + + +def test_an_executable_member_comes_out_executable_and_a_plain_one_does_not(client, tmp_path): + arc = tar_with(tmp_path / "t.tar", [(file_info("run", mode=0o755), b"x"), (file_info("data", mode=0o644), b"y")]) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert os.stat(dest / "run").st_mode & stat.S_IXUSR + assert not os.stat(dest / "data").st_mode & stat.S_IXUSR + + +def test_empty_folders_and_empty_files_in_an_archive_are_recreated(client, tmp_path): + folder = tarfile.TarInfo("emptydir") + folder.type = tarfile.DIRTYPE + folder.mode = 0o755 + arc = tar_with(tmp_path / "t.tar", [(folder, None), (file_info("zero"), b"")]) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert (dest / "emptydir").is_dir() + assert (dest / "zero").read_bytes() == b"" + + +@pytest.mark.parametrize("opener,suffix", [(gzip.compress, ".gz"), (bz2.compress, ".bz2"), (lzma.compress, ".xz"), (zstandard.ZstdCompressor().compress, ".zst")]) +def test_a_single_compressed_file_is_unpacked_to_its_name_without_the_suffix(client, tmp_path, opener, suffix): + payload = b"hello single file\n" * 40 + os.urandom(64) + arc = tmp_path / f"notes.txt{suffix}" + arc.write_bytes(opener(payload)) + dest = tmp_path / "dest" + job = extract(client, arc, dest) + assert job["state"] == "done" + assert tree(dest) == {"notes.txt": payload} + + +@pytest.mark.parametrize("comp,mode", [("gz", "w:gz"), ("bz2", "w:bz2"), ("xz", "w:xz")]) +def test_tar_archives_in_each_compression_made_by_the_standard_library_unpack_identically(client, tmp_path, comp, mode): + members = [(file_info("d/a.txt"), b"alpha"), (file_info("b.bin"), bytes(range(256)))] + arc = tar_with(tmp_path / f"t.tar.{comp}", members, mode) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert tree(dest) == {"d/a.txt": b"alpha", "b.bin": bytes(range(256))} + + +def test_a_zstd_tar_made_with_the_zstandard_library_unpacks(client, tmp_path): + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + info = file_info("z.txt") + info.size = 3 + tf.addfile(info, io.BytesIO(b"zzz")) + arc = tmp_path / "t.tar.zst" + arc.write_bytes(zstandard.ZstdCompressor().compress(raw.getvalue())) + dest = tmp_path / "dest" + extract(client, arc, dest) + assert tree(dest) == {"z.txt": b"zzz"} + + +def test_an_archive_that_expands_past_the_ratio_limit_is_stopped_as_a_zip_bomb(client, tmp_path, monkeypatch): + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_RATIO", "10") + arc = zip_with(tmp_path / "bomb.zip", {"zeros.bin": bytes(2_000_000)}) + reply = client.post("/api/archive/extract", json={"path": str(arc), "dest": str(tmp_path / "dest")}).json() + from .support import finish + + job = finish(client, reply) + assert job["state"] == "failed" + assert job["errors"][-1]["error"] == "extraction stopped because the archive expands more than 10 times its own size, which looks like a zip bomb" + assert not (tmp_path / "dest" / "zeros.bin").exists() + + +def test_an_archive_that_expands_past_the_byte_limit_is_stopped(client, tmp_path, monkeypatch): + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_BYTES", "1000") + arc = tar_with(tmp_path / "big.tar", [(file_info("big.bin"), os.urandom(5000))], "w") + from .support import finish + + job = finish(client, client.post("/api/archive/extract", json={"path": str(arc), "dest": str(tmp_path / "dest")}).json()) + assert job["state"] == "failed" + assert job["errors"][-1]["error"] == "extraction stopped because the archive expands past the size limit" + assert not (tmp_path / "dest" / "big.bin").exists() + + +def test_a_truncated_zip_is_refused_as_damaged(client, tmp_path): + good = zip_with(tmp_path / "g.zip", {"a.txt": b"x" * 5000}) + cut = tmp_path / "cut.zip" + cut.write_bytes(good.read_bytes()[:40]) + reply = client.post("/api/archive/extract", json={"path": str(cut)}) + assert (reply.status_code, reply.json()["error"]) == (400, "that archive is damaged or cut short") + + +def test_a_gzip_file_cut_short_is_refused_as_damaged(client, tmp_path): + cut = tmp_path / "cut.tar.gz" + cut.write_bytes(gzip.compress(os.urandom(5000))[:6]) + reply = client.get("/api/archive/list", params={"path": str(cut)}) + assert (reply.status_code, reply.json()["error"]) == (400, "that archive is damaged or cut short") + + +def test_extracting_a_missing_archive_is_refused(client, tmp_path): + reply = client.post("/api/archive/extract", json={"path": str(tmp_path / "ghost.zip")}) + assert (reply.status_code, reply.json()["error"]) == (404, "that file does not exist") + + +def test_extracting_a_folder_is_refused(client, tmp_path): + reply = client.post("/api/archive/extract", json={"path": str(tmp_path)}) + assert (reply.status_code, reply.json()["error"]) == (400, "that path is not a file") + + +def test_a_plain_text_file_is_not_an_archive(client, tmp_path): + from app.tools.files import archive + + from .support import finish + + plain = tmp_path / "notes.txt" + plain.write_text("hello", encoding="utf-8") + reply = client.get("/api/archive/list", params={"path": str(plain)}) + assert reply.status_code == 415 + if archive.LIBARCHIVE: + assert reply.json()["error"].startswith("formtools could not read that file as an archive") + else: + assert reply.json()["error"] == archive.NO_LIBARCHIVE + started = client.post("/api/archive/extract", json={"path": str(plain), "dest": str(tmp_path / "dest")}) + if started.status_code == 200: + job = finish(client, started.json()) + assert job["state"] == "failed" and job["errors"][-1]["error"].startswith("formtools could not read that file as an archive") + assert not (tmp_path / "dest" / "notes.txt").exists() + + +def test_listing_reports_names_sizes_and_the_engine_for_a_tar(client, tmp_path): + arc = tar_with(tmp_path / "t.tar", [(file_info("dir/a.txt"), b"12345"), (file_info("b.txt"), b"")], "w") + listing = client.get("/api/archive/list", params={"path": str(arc)}).json() + assert listing["format"] == "tar" and listing["engine"] == "tarfile" + assert [(e["name"], e["member"], e["size"]) for e in listing["entries"]] == [("a.txt", "dir/a.txt", 5), ("b.txt", "b.txt", 0)] + + +def test_listing_with_a_limit_reports_the_total_and_truncation(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {f"f{i}.txt": b"x" for i in range(7)}) + listing = client.get("/api/archive/list", params={"path": str(arc), "limit": 3}).json() + assert (len(listing["entries"]), listing["total"], listing["truncated"]) == (3, 7, True) + + +def test_a_single_gzip_is_listed_as_one_entry_with_its_unpacked_size(client, tmp_path): + arc = tmp_path / "log.txt.gz" + arc.write_bytes(gzip.compress(b"x" * 1234)) + listing = client.get("/api/archive/list", params={"path": str(arc)}).json() + assert [(e["member"], e["size"]) for e in listing["entries"]] == [("log.txt", 1234)] + assert listing["format"] == "gz" + + +def test_a_member_is_read_out_of_a_zip_with_its_content_type(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"d/hello.txt": b"hello"}) + reply = client.get("/api/archive/member", params={"path": str(arc), "member": "d/hello.txt"}) + assert reply.status_code == 200 and reply.content == b"hello" + assert reply.headers["content-type"].startswith("text/plain") + assert reply.headers["x-content-type-options"] == "nosniff" + assert reply.headers["content-security-policy"] == "sandbox" + + +def test_reading_a_member_that_is_not_there_is_refused(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"a": b"1"}) + reply = client.get("/api/archive/member", params={"path": str(arc), "member": "b"}) + assert (reply.status_code, reply.json()["error"]) == (404, "that member is not in the archive") + + +def test_reading_a_folder_member_is_refused(client, tmp_path): + arc = zip_with(tmp_path / "z.zip", {"d/": b"", "d/a": b"1"}) + reply = client.get("/api/archive/member", params={"path": str(arc), "member": "d"}) + assert (reply.status_code, reply.json()["error"]) == (400, "that member is a folder") + + +def test_reading_a_link_member_is_refused(client, tmp_path): + arc = tar_with(tmp_path / "t.tar", [(link_info("ln", "/etc/passwd"), None)], "w") + reply = client.get("/api/archive/member", params={"path": str(arc), "member": "ln"}) + assert (reply.status_code, reply.json()["error"]) == (400, "that member is a link or a special file") diff --git a/backend/tests/files/test_fonts.py b/backend/tests/files/test_fonts.py new file mode 100644 index 0000000..a3f7bc6 --- /dev/null +++ b/backend/tests/files/test_fonts.py @@ -0,0 +1,129 @@ +import pytest +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib import TTCollection, TTFont + +from app.tools.files import fonts + + +def build_font(path, family="Form Test", style="Regular", codes=(65, 66, 0x4E2D, 0x20AC), license_text="Free to use"): + names = [".notdef"] + [f"g{c:x}" for c in codes] + builder = FontBuilder(1000, isTTF=True) + builder.setupGlyphOrder(names) + builder.setupCharacterMap({c: f"g{c:x}" for c in codes}) + empty = TTGlyphPen(None).glyph() + builder.setupGlyf({n: empty for n in names}) + builder.setupHorizontalMetrics({n: (500, 0) for n in names}) + builder.setupHorizontalHeader(ascent=800, descent=-200) + builder.setupNameTable({"familyName": family, "styleName": style, "licenseDescription": license_text, "psName": f"{family.replace(' ', '')}-{style}", "fullName": f"{family} {style}", "uniqueFontIdentifier": f"{family}-{style}"}) + builder.setupOS2(sTypoAscender=800, usWinAscent=800, usWinDescent=200) + builder.setupPost() + builder.save(str(path)) + return path + + +@pytest.fixture +def user_folder(tmp_path, monkeypatch): + folder = tmp_path / "userfonts" + monkeypatch.setattr(fonts, "user_dir", lambda: folder) + monkeypatch.setattr(fonts, "font_dirs", lambda: [folder]) + monkeypatch.setattr(fonts.shutil, "which", lambda name: None) + return folder + + +def test_font_info_reports_the_names_glyph_count_and_format_written_into_the_font(client, tmp_path, user_folder): + path = build_font(tmp_path / "t.ttf", family="Form Sans", style="Bold") + info = client.get("/api/font/info", params={"path": str(path)}).json() + assert info["family"] == "Form Sans" + assert info["subfamily"] == "Bold" + assert info["full_name"] == "Form Sans Bold" + assert info["postscript"] == "FormSans-Bold" + assert info["license"] == "Free to use" + assert info["glyphs"] == 5 + assert (info["format"], info["faces"]) == ("TrueType", 1) + assert info["installed"] is False + + +def test_font_coverage_counts_characters_per_unicode_block(client, tmp_path, user_folder): + path = build_font(tmp_path / "t.ttf", codes=(65, 66, 67, 0x4E2D, 0x4E2E, 0x20AC)) + info = client.get("/api/font/info", params={"path": str(path)}).json() + assert {c["block"]: c["count"] for c in info["coverage"]} == {"Basic Latin": 3, "CJK Unified Ideographs": 2, "Currency Symbols": 1} + assert info["coverage"][0] == {"block": "Basic Latin", "count": 3} + + +def test_a_font_converted_to_woff_is_reported_as_woff_with_the_same_names(client, tmp_path, user_folder): + path = build_font(tmp_path / "t.ttf", family="Web Face") + font = TTFont(str(path)) + font.flavor = "woff" + woff = tmp_path / "t.woff" + font.save(str(woff)) + info = client.get("/api/font/info", params={"path": str(woff)}).json() + assert (info["format"], info["family"], info["glyphs"]) == ("WOFF", "Web Face", 5) + + +def test_a_collection_reports_its_face_count_and_the_first_face(client, tmp_path, user_folder): + one = build_font(tmp_path / "one.ttf", family="First Face") + two = build_font(tmp_path / "two.ttf", family="Second Face") + collection = TTCollection() + collection.fonts = [TTFont(str(one)), TTFont(str(two))] + ttc = tmp_path / "pair.ttc" + collection.save(str(ttc)) + info = client.get("/api/font/info", params={"path": str(ttc)}).json() + assert (info["format"], info["faces"], info["family"]) == ("collection", 2, "First Face") + + +def test_a_file_that_is_not_a_font_is_refused(client, tmp_path): + bad = tmp_path / "bad.ttf" + bad.write_bytes(b"this is definitely not a font file" * 10) + reply = client.get("/api/font/info", params={"path": str(bad)}) + assert (reply.status_code, reply.json()["error"]) == (415, "that file is not a font formtools can read") + + +def test_installing_a_font_copies_it_into_the_user_font_folder_byte_for_byte(client, tmp_path, user_folder): + path = build_font(tmp_path / "inst.ttf") + reply = client.post("/api/font/install", json={"path": str(path)}) + assert reply.status_code == 200 and reply.json() == {"ok": True, "path": str(user_folder / "inst.ttf")} + assert (user_folder / "inst.ttf").read_bytes() == path.read_bytes() + assert [p.name for p in user_folder.iterdir()] == ["inst.ttf"] + + +def test_after_installing_the_font_info_says_it_is_installed(client, tmp_path, user_folder): + path = build_font(tmp_path / "inst.ttf") + client.post("/api/font/install", json={"path": str(path)}) + assert client.get("/api/font/info", params={"path": str(path)}).json()["installed"] is True + + +def test_installing_the_same_font_twice_is_accepted_and_changes_nothing(client, tmp_path, user_folder): + path = build_font(tmp_path / "inst.ttf") + client.post("/api/font/install", json={"path": str(path)}) + again = client.post("/api/font/install", json={"path": str(path)}) + assert again.status_code == 200 + assert [p.name for p in user_folder.iterdir()] == ["inst.ttf"] + + +def test_installing_a_different_font_with_an_installed_name_is_refused_and_keeps_the_first(client, tmp_path, user_folder): + (tmp_path / "a").mkdir() + first = build_font(tmp_path / "a" / "same.ttf") + second_dir = tmp_path / "b" + second_dir.mkdir() + second = build_font(second_dir / "same.ttf", family="Another") + client.post("/api/font/install", json={"path": str(first)}) + reply = client.post("/api/font/install", json={"path": str(second)}) + assert (reply.status_code, reply.json()["error"]) == (400, "a different font file with that name is already installed") + assert (user_folder / "same.ttf").read_bytes() == first.read_bytes() + + +def test_web_font_extensions_cannot_be_installed(client, tmp_path, user_folder): + woff = tmp_path / "w.woff" + woff.write_bytes(b"wOFF" + bytes(40)) + reply = client.post("/api/font/install", json={"path": str(woff)}) + assert (reply.status_code, reply.json()["error"]) == (415, "only TrueType and OpenType fonts (ttf, otf, ttc, otc) can be installed; web fonts cannot") + assert not user_folder.exists() + + +def test_a_broken_file_named_ttf_is_not_installed(client, tmp_path, user_folder): + bad = tmp_path / "bad.ttf" + bad.write_bytes(b"nope" * 100) + reply = client.post("/api/font/install", json={"path": str(bad)}) + assert reply.status_code == 415 + assert not (user_folder / "bad.ttf").exists() diff --git a/backend/tests/files/test_hashing.py b/backend/tests/files/test_hashing.py new file mode 100644 index 0000000..58018a1 --- /dev/null +++ b/backend/tests/files/test_hashing.py @@ -0,0 +1,200 @@ +import hashlib +import os +import zlib + +import pytest + +from .support import finish, post_job + +EMPTY = { + "md5": "d41d8cd98f00b204e9800998ecf8427e", + "sha1": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha512": "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + "sha3_256": "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", + "blake3": "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262", + "xxh64": "ef46db3751d8e999", + "crc32": "00000000", +} +ABC = { + "md5": "900150983cd24fb0d6963f7d28e17f72", + "sha1": "a9993e364706816aba3e25717850c26c9cd0d89d", + "sha256": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "sha512": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", + "sha3_256": "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", + "blake3": "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85", + "xxh64": "44bc2cf5ad770999", + "crc32": "352441c2", +} + + +def hash_one(client, path, algorithms): + job = post_job(client, "/api/hash", {"paths": [str(path)], "algorithms": algorithms}) + assert job["state"] == "done", job + return job["result"]["items"] + + +@pytest.mark.parametrize("algorithm", sorted(EMPTY)) +def test_hashing_an_empty_file_gives_the_published_empty_input_digest(client, tmp_path, algorithm): + target = tmp_path / "empty" + target.write_bytes(b"") + items = hash_one(client, target, [algorithm]) + assert items == [{"path": str(target), "size": 0, "hashes": {algorithm: EMPTY[algorithm]}}] + + +@pytest.mark.parametrize("algorithm", sorted(ABC)) +def test_hashing_abc_gives_the_published_test_vector(client, tmp_path, algorithm): + target = tmp_path / "abc.txt" + target.write_bytes(b"abc") + assert hash_one(client, target, [algorithm])[0]["hashes"] == {algorithm: ABC[algorithm]} + + +def test_crc32_of_the_standard_check_string_is_cbf43926(client, tmp_path): + target = tmp_path / "check" + target.write_bytes(b"123456789") + assert hash_one(client, target, ["crc32"])[0]["hashes"]["crc32"] == "cbf43926" + + +def test_a_file_larger_than_one_read_block_hashes_like_hashlib_in_one_pass(client, tmp_path): + payload = os.urandom(1024 * 1024 * 2 + 12345) + target = tmp_path / "big.bin" + target.write_bytes(payload) + hashes = hash_one(client, target, ["md5", "sha256", "sha512", "crc32"])[0]["hashes"] + assert hashes == { + "md5": hashlib.md5(payload).hexdigest(), + "sha256": hashlib.sha256(payload).hexdigest(), + "sha512": hashlib.sha512(payload).hexdigest(), + "crc32": f"{zlib.crc32(payload) & 0xFFFFFFFF:08x}", + } + + +def test_a_folder_expands_to_every_file_in_sorted_order_with_sizes(client, tmp_path): + (tmp_path / "b").mkdir() + (tmp_path / "b" / "z.txt").write_bytes(b"zz") + (tmp_path / "b" / "a.txt").write_bytes(b"a") + (tmp_path / "c.txt").write_bytes(b"ccc") + job = post_job(client, "/api/hash", {"paths": [str(tmp_path)]}) + items = job["result"]["items"] + assert [os.path.relpath(i["path"], tmp_path) for i in items] == [os.path.join("c.txt"), os.path.join("b", "a.txt"), os.path.join("b", "z.txt")] + assert [i["size"] for i in items] == [3, 1, 2] + assert [i["hashes"]["sha256"] for i in items] == [hashlib.sha256(b) .hexdigest() for b in (b"ccc", b"a", b"zz")] + assert job["done"] == job["total"] == 6 + + +def test_the_default_algorithm_is_sha256_only(client, tmp_path): + target = tmp_path / "x" + target.write_bytes(b"abc") + job = post_job(client, "/api/hash", {"paths": [str(target)]}) + assert job["result"]["items"][0]["hashes"] == {"sha256": ABC["sha256"]} + + +def test_algorithm_names_are_case_insensitive_and_duplicates_collapse(client, tmp_path): + target = tmp_path / "x" + target.write_bytes(b"abc") + hashes = hash_one(client, target, ["MD5", "md5", "SHA3-256"])[0]["hashes"] + assert hashes == {"md5": ABC["md5"], "sha3_256": ABC["sha3_256"]} + + +def test_an_unknown_algorithm_is_refused_with_the_supported_list(client, tmp_path): + target = tmp_path / "x" + target.write_bytes(b"abc") + reply = client.post("/api/hash", json={"paths": [str(target)], "algorithms": ["whirlpool"]}) + assert reply.status_code == 400 + assert reply.json()["error"] == "whirlpool is not a supported algorithm; use md5, sha1, sha256, sha512, sha3_256, blake3, xxh64, crc32" + + +def test_hashing_a_missing_path_is_refused_with_its_name(client, tmp_path): + reply = client.post("/api/hash", json={"paths": [str(tmp_path / "ghost.bin")]}) + assert (reply.status_code, reply.json()["error"]) == (404, "ghost.bin does not exist") + + +def test_hashing_an_empty_folder_is_refused(client, tmp_path): + reply = client.post("/api/hash", json={"paths": [str(tmp_path)]}) + assert (reply.status_code, reply.json()["error"]) == (400, "there are no files to hash") + + +def test_hashing_a_relative_path_is_refused(client): + reply = client.post("/api/hash", json={"paths": ["relative/file.txt"]}) + assert (reply.status_code, reply.json()["error"]) == (400, "the path must be absolute") + + +def write_pair(folder): + (folder / "good.txt").write_bytes(b"abc") + (folder / "bad.txt").write_bytes(b"abd") + + +def verify(client, sums): + job = post_job(client, "/api/hash/verify", {"path": str(sums)}) + assert job["state"] == "done", job + return job["result"] + + +def test_verify_a_sha256sum_file_counts_good_bad_and_missing_entries(client, tmp_path): + write_pair(tmp_path) + sums = tmp_path / "SHA256SUMS" + digest = ABC["sha256"] + sums.write_text(f"{digest} good.txt\n{digest} *bad.txt\n{digest} gone.txt\n", encoding="utf-8") + result = verify(client, sums) + assert (result["ok"], result["failed"], result["missing"]) == (1, 1, 1) + by_name = {os.path.basename(i["path"]): i for i in result["items"]} + assert by_name["good.txt"]["ok"] is True + assert by_name["bad.txt"]["actual"] == hashlib.sha256(b"abd").hexdigest() + assert by_name["gone.txt"]["missing"] is True and by_name["gone.txt"]["actual"] is None + + +def test_verify_reads_bsd_tagged_lines_for_several_algorithms(client, tmp_path): + write_pair(tmp_path) + sums = tmp_path / "CHECKSUMS" + sums.write_text(f"MD5 (good.txt) = {ABC['md5']}\nSHA1 (good.txt) = {ABC['sha1']}\nSHA512 (bad.txt) = {ABC['sha512']}\n", encoding="utf-8") + result = verify(client, sums) + assert (result["ok"], result["failed"], result["missing"]) == (2, 1, 0) + + +def test_verify_reads_an_sfv_file_as_crc32(client, tmp_path): + write_pair(tmp_path) + sums = tmp_path / "files.sfv" + sums.write_text(f"; made by hand\ngood.txt {ABC['crc32']}\nbad.txt {ABC['crc32']}\n", encoding="utf-8") + result = verify(client, sums) + assert (result["ok"], result["failed"]) == (1, 1) + assert result["items"][1]["actual"] == f"{zlib.crc32(b'abd'):08x}" + + +def test_verify_accepts_uppercase_digests_and_a_utf8_bom(client, tmp_path): + write_pair(tmp_path) + sums = tmp_path / "list.md5" + sums.write_bytes(b"\xef\xbb\xbf" + f"{ABC['md5'].upper()} good.txt\r\n".encode("ascii")) + result = verify(client, sums) + assert (result["ok"], result["failed"], result["missing"]) == (1, 0, 0) + assert result["items"][0]["expected"] == ABC["md5"] + + +def test_verify_a_file_with_no_checksums_is_refused(client, tmp_path): + sums = tmp_path / "notes.txt" + sums.write_text("just words\nno digests here\n", encoding="utf-8") + reply = client.post("/api/hash/verify", json={"path": str(sums)}) + assert (reply.status_code, reply.json()["error"]) == (400, "no checksums were found in that file") + + +def test_verify_a_missing_checksum_file_is_refused(client, tmp_path): + reply = client.post("/api/hash/verify", json={"path": str(tmp_path / "SHA256SUMS")}) + assert (reply.status_code, reply.json()["error"]) == (404, "that checksum file does not exist") + + +def test_hashes_written_by_the_app_verify_cleanly_through_the_app(client, tmp_path): + (tmp_path / "data").mkdir() + (tmp_path / "data" / "one.bin").write_bytes(os.urandom(5000)) + (tmp_path / "data" / "two.bin").write_bytes(b"") + items = post_job(client, "/api/hash", {"paths": [str(tmp_path / "data")], "algorithms": ["sha512"]})["result"]["items"] + sums = tmp_path / "data" / "SHA512SUMS" + sums.write_text("".join(f"{i['hashes']['sha512']} {os.path.basename(i['path'])}\n" for i in items), encoding="utf-8") + result = verify(client, sums) + assert (result["ok"], result["failed"], result["missing"]) == (2, 0, 0) + + +def test_a_finished_hash_job_is_reported_by_the_jobs_route(client, tmp_path): + target = tmp_path / "x" + target.write_bytes(b"abc") + started = client.post("/api/hash", json={"paths": [str(target)], "algorithms": ["md5"]}).json() + done = finish(client, started) + assert done["kind"] == "hash" and done["title"] == "Hash 1 file" + assert done["result"]["items"][0]["hashes"]["md5"] == ABC["md5"] diff --git a/backend/tests/files/test_safety.py b/backend/tests/files/test_safety.py new file mode 100644 index 0000000..8099db6 --- /dev/null +++ b/backend/tests/files/test_safety.py @@ -0,0 +1,184 @@ +import os + +import pytest + +from app.core.errors import ApiError +from app.tools.files import safety + + +@pytest.mark.parametrize( + "name,parts", + [ + ("a.txt", ["a.txt"]), + ("dir/sub/a.txt", ["dir", "sub", "a.txt"]), + ("./a.txt", ["a.txt"]), + ("a//b///c", ["a", "b", "c"]), + ("dir\\sub\\a.txt", ["dir", "sub", "a.txt"]), + ("trailing/", ["trailing"]), + ("a/./b", ["a", "b"]), + ("...", ["..."]), + ("name..ext", ["name..ext"]), + ], +) +def test_ordinary_member_names_are_split_into_their_parts(name, parts): + assert safety.split_name(name) == parts + + +@pytest.mark.parametrize( + "name,reason", + [ + ("", "the name is empty or has a null character"), + ("a\x00b", "the name is empty or has a null character"), + ("/etc/passwd", "the name is absolute"), + ("\\windows\\x", "the name is absolute"), + ("C:/x", "the name starts with a drive letter"), + ("z:\\x", "the name starts with a drive letter"), + ("c:x", "the name starts with a drive letter"), + ("..", "the name climbs out of the destination with .."), + ("../x", "the name climbs out of the destination with .."), + ("a/../x", "the name climbs out of the destination with .."), + ("a/b/..", "the name climbs out of the destination with .."), + ("a\\..\\x", "the name climbs out of the destination with .."), + ("./", "the name has no usable part"), + ("a/..\\..\\x", "the name climbs out of the destination with .."), + ], +) +def test_names_that_could_escape_the_destination_are_refused_with_a_reason(name, reason): + with pytest.raises(safety.Refused) as caught: + safety.split_name(name) + assert str(caught.value) == reason + + +def test_unique_returns_the_same_path_when_nothing_is_there(tmp_path): + assert safety.unique(tmp_path / "a.txt") == tmp_path / "a.txt" + + +def test_unique_counts_up_from_two_and_keeps_the_extension(tmp_path): + (tmp_path / "a.txt").write_bytes(b"") + assert safety.unique(tmp_path / "a.txt") == tmp_path / "a (2).txt" + (tmp_path / "a (2).txt").write_bytes(b"") + assert safety.unique(tmp_path / "a.txt") == tmp_path / "a (3).txt" + + +def test_unique_keeps_a_double_tar_extension_together(tmp_path): + (tmp_path / "pack.tar.gz").write_bytes(b"") + assert safety.unique(tmp_path / "pack.tar.gz") == tmp_path / "pack (2).tar.gz" + + +def test_unique_treats_a_dangling_symbolic_link_as_taken(tmp_path): + os.symlink(tmp_path / "nowhere", tmp_path / "a.txt") + assert safety.unique(tmp_path / "a.txt") == tmp_path / "a (2).txt" + + +def test_place_moves_the_temp_file_to_the_wanted_name(tmp_path): + temp = tmp_path / "t.part" + temp.write_bytes(b"content") + final = safety.place(temp, tmp_path / "wanted.bin") + assert final == tmp_path / "wanted.bin" and final.read_bytes() == b"content" + assert not temp.exists() + + +def test_place_never_overwrites_an_existing_file(tmp_path): + (tmp_path / "wanted.bin").write_bytes(b"old") + temp = tmp_path / "t.part" + temp.write_bytes(b"new") + final = safety.place(temp, tmp_path / "wanted.bin") + assert final == tmp_path / "wanted (2).bin" + assert (tmp_path / "wanted.bin").read_bytes() == b"old" and final.read_bytes() == b"new" + + +def test_temp_names_are_distinct_hidden_part_files_in_the_given_folder(tmp_path): + first = safety.temp_beside(tmp_path) + second = safety.temp_beside(tmp_path) + assert first != second + assert first.parent == tmp_path and first.name.startswith(".") and first.name.endswith(".part") + + +def test_discard_removes_a_file_and_ignores_a_missing_one(tmp_path): + target = tmp_path / "x.part" + target.write_bytes(b"1") + safety.discard(target) + safety.discard(target) + assert not target.exists() + + +def test_inside_accepts_the_root_and_children_but_not_a_sibling_with_the_same_prefix(): + assert safety.inside("/data/dest", "/data/dest") + assert safety.inside("/data/dest", "/data/dest/sub/file") + assert not safety.inside("/data/dest", "/data/dest-evil/file") + assert not safety.inside("/data/dest", "/data") + + +def test_safe_folder_creates_each_missing_folder_below_the_root(tmp_path): + made = safety.safe_folder(tmp_path, ["a", "b", "c"]) + assert made == tmp_path / "a" / "b" / "c" and made.is_dir() + + +@pytest.mark.skipif(os.name == "nt", reason="symbolic links need privileges on Windows") +def test_safe_folder_refuses_to_walk_through_a_symbolic_link(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + root = tmp_path / "root" + root.mkdir() + os.symlink(outside, root / "hop") + with pytest.raises(safety.Refused, match="a folder on the way is a symbolic link"): + safety.safe_folder(root, ["hop", "deeper"]) + assert list(outside.iterdir()) == [] + + +def test_safe_folder_refuses_when_a_file_is_where_a_folder_is_needed(tmp_path): + (tmp_path / "a").write_bytes(b"file") + with pytest.raises(safety.Refused, match="a file is in the way of a folder"): + safety.safe_folder(tmp_path, ["a", "b"]) + + +def test_prepare_target_returns_the_path_for_the_last_part_after_making_its_folders(tmp_path): + target = safety.prepare_target(tmp_path, ["x", "y", "z.txt"]) + assert target == tmp_path / "x" / "y" / "z.txt" + assert (tmp_path / "x" / "y").is_dir() and not target.exists() + + +def test_the_default_limits_are_twenty_gibibytes_and_a_ratio_of_one_thousand(monkeypatch): + monkeypatch.delenv("FORMTOOLS_ARCHIVE_MAX_BYTES", raising=False) + monkeypatch.delenv("FORMTOOLS_ARCHIVE_MAX_RATIO", raising=False) + assert safety.limit_bytes() == 20 * 1024**3 + assert safety.limit_ratio() == 1000 + + +def test_limits_can_be_lowered_through_the_environment_and_junk_values_are_ignored(monkeypatch): + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_BYTES", "5000") + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_RATIO", "junk") + assert safety.limit_bytes() == 5000 + assert safety.limit_ratio() == 1000 + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_BYTES", "0") + assert safety.limit_bytes() == 20 * 1024**3 + + +def test_the_budget_allows_data_up_to_the_ratio_and_refuses_beyond(monkeypatch): + monkeypatch.delenv("FORMTOOLS_ARCHIVE_MAX_BYTES", raising=False) + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_RATIO", "100") + budget = safety.Budget(archive_size=10) + budget.add(1000) + with pytest.raises(ApiError) as caught: + budget.add(1) + assert caught.value.status == 400 + assert caught.value.message == "extraction stopped because the archive expands more than 100 times its own size, which looks like a zip bomb" + + +def test_the_budget_refuses_a_declared_size_that_will_not_fit(monkeypatch): + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_BYTES", "500") + budget = safety.Budget(archive_size=10**6) + budget.declared(None) + budget.declared(500) + with pytest.raises(ApiError) as caught: + budget.declared(501) + assert caught.value.message == "extraction stopped because the archive expands past the size limit" + + +def test_the_budget_counts_all_members_together(monkeypatch): + monkeypatch.setenv("FORMTOOLS_ARCHIVE_MAX_BYTES", "100") + budget = safety.Budget(archive_size=10**6) + budget.add(60) + assert budget.room() == 40 + with pytest.raises(ApiError): + budget.add(41) diff --git a/backend/tests/files/test_text.py b/backend/tests/files/test_text.py new file mode 100644 index 0000000..eb0d42b --- /dev/null +++ b/backend/tests/files/test_text.py @@ -0,0 +1,128 @@ +import pytest + + +def read(client, tmp_path, payload, name="f.txt", **params): + target = tmp_path / name + target.write_bytes(payload) + reply = client.get("/api/text", params={"path": str(target), **params}) + assert reply.status_code == 200, reply.text + return reply.json() + + +@pytest.mark.parametrize( + "payload,eol,lines", + [ + (b"a\nb\nc\n", "lf", 3), + (b"a\nb\nc", "lf", 3), + (b"a\r\nb\r\n", "crlf", 2), + (b"a\r\nb\r\nc", "crlf", 3), + (b"a\rb\rc\r", "cr", 3), + (b"a\r\nb\nc", "mixed", 3), + (b"a\rb\nc\r\n", "mixed", 3), + (b"\n\n\n", "lf", 3), + (b"one line no break", "lf", 1), + (b"", "lf", 0), + ], +) +def test_line_endings_and_line_counts_match_a_hand_count(client, tmp_path, payload, eol, lines): + result = read(client, tmp_path, payload) + assert (result["eol"], result["lines"]) == (eol, lines) + + +def test_plain_ascii_is_reported_as_utf8_without_a_bom(client, tmp_path): + result = read(client, tmp_path, b"plain text\n") + assert (result["encoding"], result["bom"], result["text"]) == ("utf-8", False, "plain text\n") + + +def test_a_utf8_byte_order_mark_is_reported_and_removed_from_the_text(client, tmp_path): + result = read(client, tmp_path, b"\xef\xbb\xbfhi") + assert (result["encoding"], result["bom"], result["text"]) == ("utf-8", True, "hi") + + +@pytest.mark.parametrize("codec,label", [("utf-16-le", "utf-16le"), ("utf-16-be", "utf-16be"), ("utf-32-le", "utf-32le"), ("utf-32-be", "utf-32be")]) +def test_unicode_files_with_a_byte_order_mark_are_decoded_back_to_the_original_text(client, tmp_path, codec, label): + import codecs + + marks = {"utf-16-le": codecs.BOM_UTF16_LE, "utf-16-be": codecs.BOM_UTF16_BE, "utf-32-le": codecs.BOM_UTF32_LE, "utf-32-be": codecs.BOM_UTF32_BE} + original = "caf\u00e9 \u4e2d\u6587 \U0001f600\nline2\n" + result = read(client, tmp_path, marks[codec] + original.encode(codec)) + assert (result["encoding"], result["bom"], result["text"], result["lines"]) == (label, True, original, 2) + + +def test_utf16_without_a_byte_order_mark_is_recognised_from_its_zero_bytes(client, tmp_path): + result = read(client, tmp_path, "hello world\n".encode("utf-16-le")) + assert (result["encoding"], result["bom"], result["text"]) == ("utf-16le", False, "hello world\n") + result = read(client, tmp_path, "hello world\n".encode("utf-16-be"), name="g.txt") + assert (result["encoding"], result["text"]) == ("utf-16be", "hello world\n") + + +def test_valid_multibyte_utf8_is_decoded_exactly(client, tmp_path): + original = "na\u00efve \u00fcber \u65e5\u672c\u8a9e \U0001f680" + result = read(client, tmp_path, original.encode("utf-8")) + assert (result["encoding"], result["text"]) == ("utf-8", original) + + +def test_bytes_that_are_not_utf8_are_read_as_windows_1252(client, tmp_path): + result = read(client, tmp_path, b"caf\xe9 \x80 \x93q\x94") + assert result["encoding"] == "cp1252" + assert result["text"] == "caf\u00e9 \u20ac \u201cq\u201d" + + +def test_a_file_cut_to_max_bytes_is_marked_truncated_and_returns_that_many_bytes(client, tmp_path): + result = read(client, tmp_path, b"abcdefghij", max=4) + assert (result["text"], result["truncated"]) == ("abcd", True) + + +def test_a_file_exactly_max_bytes_long_is_not_truncated(client, tmp_path): + result = read(client, tmp_path, b"abcd", max=4) + assert (result["text"], result["truncated"]) == ("abcd", False) + + +def test_cutting_in_the_middle_of_a_multibyte_character_drops_the_partial_character(client, tmp_path): + result = read(client, tmp_path, "\u00e9\u00e9\u00e9".encode("utf-8"), max=3) + assert (result["text"], result["truncated"], result["encoding"]) == ("\u00e9", True, "utf-8") + + +def test_the_returned_text_never_exceeds_max_bytes_after_encoding(client, tmp_path): + result = read(client, tmp_path, ("\u4e2d" * 100).encode("utf-8"), max=50) + assert len(result["text"].encode("utf-8")) <= 50 + assert result["text"] == "\u4e2d" * 16 + + +def test_max_below_one_is_refused(client, tmp_path): + target = tmp_path / "f.txt" + target.write_bytes(b"x") + reply = client.get("/api/text", params={"path": str(target), "max": 0}) + assert (reply.status_code, reply.json()["error"]) == (400, "max must be at least 1 byte") + + +def test_reading_a_missing_file_is_refused(client, tmp_path): + reply = client.get("/api/text", params={"path": str(tmp_path / "ghost.txt")}) + assert (reply.status_code, reply.json()["error"]) == (404, "that file does not exist") + + +def test_reading_a_folder_as_text_is_refused(client, tmp_path): + reply = client.get("/api/text", params={"path": str(tmp_path)}) + assert (reply.status_code, reply.json()["error"]) == (400, "that path is not a file") + + +def test_reading_a_relative_path_is_refused(client): + reply = client.get("/api/text", params={"path": "rel/f.txt"}) + assert (reply.status_code, reply.json()["error"]) == (400, "the path must be absolute") + + +@pytest.mark.parametrize( + "name,language", + [("a.py", "python"), ("b.js", "javascript"), ("c.ts", "typescript"), ("d.json", "json"), ("e.yml", "yaml"), ("f.md", "markdown"), ("g.rs", "rust"), ("Dockerfile", "dockerfile"), ("Makefile", "makefile"), ("h.sh", "bash"), ("noext", None), ("x.zzz", None)], +) +def test_the_highlight_language_follows_the_file_name(client, tmp_path, name, language): + assert read(client, tmp_path, b"x", name=name)["language"] == language + + +def test_a_text_file_read_through_the_mcp_tool_matches_the_route(client, tmp_path): + target = tmp_path / "m.txt" + target.write_bytes(b"one\r\ntwo\r\n") + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "text_read", "arguments": {"path": str(target)}}}).json() + assert "error" not in reply + body = str(reply["result"]) + assert "crlf" in body and "one" in body diff --git a/backend/tests/image/__init__.py b/backend/tests/image/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/image/support.py b/backend/tests/image/support.py new file mode 100644 index 0000000..286ee35 --- /dev/null +++ b/backend/tests/image/support.py @@ -0,0 +1,126 @@ +import math +import struct +import zlib + +from PIL import Image + +A, B, C, D, E, F = (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (90, 60, 30) +GRID = [[A, B, C], [D, E, F]] + + +def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) + + +def orientation_tiff(value: int) -> bytes: + return b"MM\x00\x2a\x00\x00\x00\x08" + struct.pack(">H", 1) + struct.pack(">HHIHH", 0x0112, 3, 1, value, 0) + b"\x00\x00\x00\x00" + + +def png_bytes(grid, orientation=None) -> bytes: + height, width = len(grid), len(grid[0]) + channels = len(grid[0][0]) + colour_type = {3: 2, 4: 6}[channels] + raw = b"".join(b"\x00" + b"".join(bytes(p) for p in row) for row in grid) + out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, colour_type, 0, 0, 0)) + if orientation is not None: + out += chunk(b"eXIf", orientation_tiff(orientation)) + return out + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def grey16_png_bytes(rows) -> bytes: + height, width = len(rows), len(rows[0]) + raw = b"".join(b"\x00" + b"".join(struct.pack(">H", v) for v in row) for row in rows) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 16, 0, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def ppm_bytes(grid) -> bytes: + return b"P6\n%d %d\n255\n" % (len(grid[0]), len(grid)) + b"".join(bytes(p) for row in grid for p in row) + + +def hdr_bytes(rows, size_line=None) -> bytes: + height, width = len(rows), len(rows[0]) + line = size_line or b"-Y %d +X %d" % (height, width) + return b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n" + line + b"\n" + b"".join(bytes(p) for row in rows for p in row) + + +def hdr_run_length_bytes(rows) -> bytes: + height, width = len(rows), len(rows[0]) + body = b"" + for row in rows: + body += bytes((2, 2, width >> 8, width & 255)) + for channel in range(4): + position = 0 + while position < width: + run = 1 + while position + run < width and row[position + run][channel] == row[position][channel] and run < 127: + run += 1 + body += bytes((128 + run, row[position][channel])) + position += run + return b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n" + b"-Y %d +X %d\n" % (height, width) + body + + +def rgbe_value(mantissa: int, exponent: int) -> float: + return (mantissa + 0.5) * 2.0 ** (exponent - 136) if exponent else 0.0 + + +def srgb8(linear: float) -> int: + x = min(1.0, max(0.0, linear)) + encoded = x * 12.92 if x <= 0.0031308 else 1.055 * x ** (1 / 2.4) - 0.055 + return int(encoded * 255 + 0.5) + + +def aces(x: float) -> float: + return min(1.0, max(0.0, (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14))) + + +def read_grid(path): + with Image.open(path) as image: + image.load() + width, height = image.size + return [[image.getpixel((x, y)) for x in range(width)] for y in range(height)] + + +def flip_h(grid): + return [list(reversed(row)) for row in grid] + + +def flip_v(grid): + return [list(row) for row in reversed(grid)] + + +def turn_cw(grid): + height, width = len(grid), len(grid[0]) + return [[grid[height - 1 - x][y] for x in range(height)] for y in range(width)] + + +def turn_ccw(grid): + return turn_cw(turn_cw(turn_cw(grid))) + + +def turn_180(grid): + return flip_v(flip_h(grid)) + + +def transpose(grid): + return [[grid[y][x] for y in range(len(grid))] for x in range(len(grid[0]))] + + +SHOWN_FOR_ORIENTATION = { + 1: lambda g: [list(r) for r in g], + 2: flip_h, + 3: turn_180, + 4: flip_v, + 5: transpose, + 6: turn_cw, + 7: lambda g: turn_180(transpose(g)), + 8: turn_ccw, +} + + +def close(grid, wanted, slack): + assert len(grid) == len(wanted) and len(grid[0]) == len(wanted[0]) + return all(abs(a - b) <= slack for row, want in zip(grid, wanted) for p, q in zip(row, want) for a, b in zip(p[:3], q[:3])) + + +def error_of(reply): + return reply.status_code, reply.json()["error"] diff --git a/backend/tests/image/test_edit.py b/backend/tests/image/test_edit.py new file mode 100644 index 0000000..c00267e --- /dev/null +++ b/backend/tests/image/test_edit.py @@ -0,0 +1,203 @@ +import pytest +from PIL import Image + +from .support import A, B, C, D, E, F, GRID, close, error_of, flip_h, flip_v, png_bytes, ppm_bytes, read_grid, turn_180, turn_ccw, turn_cw + + +@pytest.fixture +def picture(tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + return path + + +def edit(client, path, ops, **more): + return client.post("/api/image/edit", json={"path": str(path), "ops": ops, **more}) + + +@pytest.mark.parametrize( + "step,geometry", + [ + ({"op": "rotate", "degrees": 90}, turn_cw), + ({"op": "rotate", "degrees": 180}, turn_180), + ({"op": "rotate", "degrees": 270}, turn_ccw), + ({"op": "flip", "axis": "h"}, flip_h), + ({"op": "flip", "axis": "v"}, flip_v), + ], + ids=["quarter turn clockwise", "half turn", "three quarter turn clockwise", "mirror left to right", "mirror top to bottom"], +) +def test_edit_moves_every_pixel_where_geometry_says(client, picture, step, geometry): + reply = edit(client, picture, [step]).json() + assert read_grid(reply["path"]) == geometry(GRID) + + +def test_a_quarter_turn_of_a_3_by_2_picture_is_2_wide_and_3_high_with_the_bottom_left_pixel_on_top(client, picture): + out = edit(client, picture, [{"op": "rotate", "degrees": 90}]).json()["path"] + assert read_grid(out) == [[D, A], [E, B], [F, C]] + + +def test_crop_keeps_exactly_the_pixels_inside_the_box(client, picture): + out = edit(client, picture, [{"op": "crop", "x": 1, "y": 0, "w": 2, "h": 2}]).json()["path"] + assert read_grid(out) == [[B, C], [E, F]] + + +def test_steps_run_in_the_order_given(client, picture): + out = edit(client, picture, [{"op": "crop", "x": 0, "y": 0, "w": 2, "h": 1}, {"op": "flip", "axis": "h"}]).json()["path"] + assert read_grid(out) == [[B, A]] + + +def test_four_quarter_turns_give_back_the_original_pixels(client, picture): + out = edit(client, picture, [{"op": "rotate", "degrees": 90}] * 4).json()["path"] + assert read_grid(out) == GRID + + +def test_nearest_resize_to_double_size_repeats_each_pixel_in_a_2_by_2_block(client, picture): + out = edit(client, picture, [{"op": "resize", "width": 6, "height": 4, "resample": "nearest"}]).json()["path"] + assert read_grid(out) == [[GRID[y // 2][x // 2] for x in range(6)] for y in range(4)] + + +def test_resize_with_only_a_width_keeps_the_3_to_2_shape(client, tmp_path): + path = tmp_path / "flat.png" + path.write_bytes(png_bytes([[F] * 3] * 2)) + out = edit(client, path, [{"op": "resize", "width": 9}]).json()["path"] + grid = read_grid(out) + assert (len(grid[0]), len(grid)) == (9, 6) + assert close(grid, [[F] * 9] * 6, 0) + + +def test_resize_with_only_a_height_keeps_the_3_to_2_shape(client, picture): + out = edit(client, picture, [{"op": "resize", "height": 8, "resample": "nearest"}]).json()["path"] + with Image.open(out) as image: + assert image.size == (12, 8) + + +def test_shrinking_a_single_colour_picture_keeps_that_colour(client, tmp_path): + path = tmp_path / "flat.png" + path.write_bytes(png_bytes([[F] * 8] * 8)) + out = edit(client, path, [{"op": "resize", "width": 2, "height": 2}]).json()["path"] + assert read_grid(out) == [[F, F], [F, F]] + + +def test_a_crop_box_outside_the_picture_is_refused_with_the_picture_size(client, picture): + reply = edit(client, picture, [{"op": "crop", "x": 2, "y": 0, "w": 2, "h": 1}]) + assert error_of(reply) == (400, "the crop box falls outside the 3 by 2 picture") + assert not (picture.parent / "six edited.png").exists() + + +def test_a_crop_box_with_no_width_is_refused(client, picture): + reply = edit(client, picture, [{"op": "crop", "x": 0, "y": 0, "w": 0, "h": 1}]) + assert error_of(reply) == (400, "the crop box needs a width and height of at least 1 pixel") + + +def test_resize_without_a_width_or_height_is_refused(client, picture): + assert error_of(edit(client, picture, [{"op": "resize"}])) == (400, "resize needs a width, a height or both") + + +def test_resize_past_65535_pixels_is_refused(client, picture): + assert error_of(edit(client, picture, [{"op": "resize", "width": 65536}])) == (400, "resize sizes must be between 1 and 65535 pixels") + + +def test_an_edit_with_no_steps_is_refused(client, picture): + assert error_of(edit(client, picture, [])) == (400, "ops needs at least one step") + + +def test_a_turn_that_is_not_a_quarter_turn_is_refused(client, picture): + reply = edit(client, picture, [{"op": "rotate", "degrees": 45}]) + assert reply.status_code == 400 and reply.json()["ok"] is False + assert list(picture.parent.iterdir()) == [picture] + + +def test_the_edit_is_saved_beside_the_original_and_the_original_is_untouched(client, picture): + before = picture.read_bytes() + first = edit(client, picture, [{"op": "flip", "axis": "h"}]).json()["path"] + second = edit(client, picture, [{"op": "flip", "axis": "v"}]).json()["path"] + assert first == str(picture.parent / "six edited.png") + assert second == str(picture.parent / "six edited (2).png") + assert picture.read_bytes() == before + assert read_grid(first) == flip_h(GRID) and read_grid(second) == flip_v(GRID) + + +def test_an_existing_output_file_is_kept_unless_overwrite_is_set(client, picture, tmp_path): + taken = tmp_path / "taken.png" + taken.write_bytes(png_bytes([[A]])) + step = [{"op": "flip", "axis": "h"}] + refused = edit(client, picture, step, out={"path": str(taken)}) + assert error_of(refused) == (400, "a file with that name already exists; set overwrite to true to replace it") + assert read_grid(taken) == [[A]] + assert edit(client, picture, step, out={"path": str(taken)}, overwrite=True).status_code == 200 + assert read_grid(taken) == flip_h(GRID) + + +def test_replacing_the_original_needs_overwrite(client, picture): + before = picture.read_bytes() + reply = edit(client, picture, [{"op": "flip", "axis": "h"}], out={"path": str(picture)}) + assert error_of(reply) == (400, "that would replace the original; set overwrite to true and give the same out.path to confirm") + assert picture.read_bytes() == before + assert edit(client, picture, [{"op": "flip", "axis": "h"}], out={"path": str(picture)}, overwrite=True).status_code == 200 + assert read_grid(picture) == flip_h(GRID) + + +def test_an_output_name_that_disagrees_with_the_format_is_refused(client, picture, tmp_path): + reply = edit(client, picture, [{"op": "flip", "axis": "h"}], out={"path": str(tmp_path / "x.png"), "format": "jpeg"}) + assert error_of(reply) == (400, "the output file extension does not match the output format") + + +def test_an_output_name_with_an_unknown_ending_is_refused(client, picture, tmp_path): + reply = edit(client, picture, [{"op": "flip", "axis": "h"}], out={"path": str(tmp_path / "x.bmp")}) + assert error_of(reply) == (400, "the output path must end in .jpg, .png, .webp, .avif or .tiff, or out.format must be set") + + +def test_an_output_folder_that_does_not_exist_is_refused(client, picture, tmp_path): + reply = edit(client, picture, [{"op": "flip", "axis": "h"}], out={"path": str(tmp_path / "nowhere" / "x.png")}) + assert error_of(reply) == (400, "the output folder does not exist") + + +def test_a_missing_source_is_refused(client, tmp_path): + assert error_of(edit(client, tmp_path / "gone.png", [{"op": "flip", "axis": "h"}])) == (404, "that file does not exist") + + +def test_a_text_file_named_like_a_picture_is_refused_and_nothing_is_written(client, tmp_path): + path = tmp_path / "notes.png" + path.write_text("this is not a picture") + reply = edit(client, path, [{"op": "flip", "axis": "h"}]) + assert error_of(reply) == (415, "formtools cannot decode that file as a picture") + assert list(tmp_path.iterdir()) == [path] + + +@pytest.mark.parametrize("fmt,ending,file_format", [("png", "png", "PNG"), ("tiff", "tiff", "TIFF")]) +def test_converting_to_a_lossless_format_keeps_every_pixel(client, picture, fmt, ending, file_format): + out = edit(client, picture, [{"op": "flip", "axis": "h"}, {"op": "flip", "axis": "h"}], out={"format": fmt}).json()["path"] + assert out.endswith("six edited." + ending) + with Image.open(out) as image: + assert image.format == file_format + assert read_grid(out) == GRID + + +@pytest.mark.parametrize("fmt,ending,file_format", [("jpeg", "jpg", "JPEG"), ("webp", "webp", "WEBP")]) +def test_converting_a_single_colour_picture_to_a_lossy_format_stays_within_a_few_levels(client, tmp_path, fmt, ending, file_format): + path = tmp_path / "flat.png" + path.write_bytes(png_bytes([[F] * 16] * 16)) + out = edit(client, path, [{"op": "rotate", "degrees": 180}], out={"format": fmt}).json()["path"] + assert out.endswith("flat edited." + ending) + with Image.open(out) as image: + assert image.format == file_format and image.size == (16, 16) + assert close(read_grid(out), [[F] * 16] * 16, 4) + + +def test_a_ppm_source_is_saved_as_png_with_the_same_pixels(client, tmp_path): + path = tmp_path / "raw.ppm" + path.write_bytes(ppm_bytes(GRID)) + out = edit(client, path, [{"op": "rotate", "degrees": 90}]).json()["path"] + assert out == str(tmp_path / "raw edited.png") + assert read_grid(out) == turn_cw(GRID) + + +def test_see_through_pixels_survive_in_png_and_turn_white_in_jpeg(client, tmp_path): + path = tmp_path / "glass.png" + clear, solid = (10, 20, 30, 0), (10, 20, 30, 255) + path.write_bytes(png_bytes([[clear] * 8 + [solid] * 8] * 16)) + step = [{"op": "flip", "axis": "v"}] + kept = edit(client, path, step, out={"format": "png"}).json()["path"] + assert read_grid(kept) == [[clear] * 8 + [solid] * 8] * 16 + flat = read_grid(edit(client, path, step, out={"format": "jpeg", "quality": 100}).json()["path"]) + assert all(abs(v - 255) <= 4 for v in flat[8][1]) and all(abs(a - b) <= 4 for a, b in zip(flat[8][14], (10, 20, 30))) diff --git a/backend/tests/image/test_info_meta_hdr.py b/backend/tests/image/test_info_meta_hdr.py new file mode 100644 index 0000000..c2c99b5 --- /dev/null +++ b/backend/tests/image/test_info_meta_hdr.py @@ -0,0 +1,313 @@ +import math +import xml.etree.ElementTree as ET + +import numpy as np +import pytest +from PIL import Image + +from .support import A, B, F, GRID, aces, close, error_of, grey16_png_bytes, hdr_bytes, hdr_run_length_bytes, png_bytes, ppm_bytes, read_grid, rgbe_value, srgb8 + +XMP_NS = "http://ns.adobe.com/xap/1.0/" +HAND_XMP = ( + '' + '' + "" +) + + +def info(client, path): + return client.get("/api/image/info", params={"path": str(path)}) + + +def stored(sidecar, name): + root = ET.fromstring(sidecar.read_bytes()) + for element in root.iter(): + if element.tag == "{%s}%s" % (XMP_NS, name): + return element.text + value = element.get("{%s}%s" % (XMP_NS, name)) + if value is not None: + return value + return None + + +def edited(client, path): + reply = client.post("/api/image/edit", json={"path": str(path), "ops": [{"op": "flip", "axis": "h"}, {"op": "flip", "axis": "h"}]}) + assert reply.status_code == 200, reply.text + return read_grid(reply.json()["path"]) + + +def test_info_reports_the_size_format_and_depth_written_in_a_png_header(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + found = info(client, path).json() + assert (found["width"], found["height"], found["format"], found["mode"], found["bit_depth"]) == (3, 2, "PNG", "RGB", 8) + assert found["has_alpha"] is False and found["frames"] == 1 and found["animated"] is False + assert found["size"] == len(png_bytes(GRID)) + assert found["gps"] is None and found["xmp"]["rating"] in (0, None) + + +def test_info_reports_alpha_for_a_png_with_an_alpha_channel(client, tmp_path): + path = tmp_path / "glass.png" + path.write_bytes(png_bytes([[(1, 2, 3, 0), (1, 2, 3, 255)]])) + found = info(client, path).json() + assert (found["width"], found["height"], found["has_alpha"], found["mode"]) == (2, 1, True, "RGBA") + + +def test_info_reports_16_bits_for_a_16_bit_grey_png(client, tmp_path): + path = tmp_path / "deep.png" + path.write_bytes(grey16_png_bytes([[0, 0x8000, 0xFFFF]])) + found = info(client, path).json() + assert (found["width"], found["height"], found["bit_depth"]) == (3, 1, 16) + + +def test_a_16_bit_grey_png_is_shown_at_the_nearest_8_bit_level(client, tmp_path): + path = tmp_path / "deep.png" + path.write_bytes(grey16_png_bytes([[0, 0x8000, 0xFFFF, 257 * 77]])) + assert edited(client, path) == [[(0, 0, 0), (128, 128, 128), (255, 255, 255), (77, 77, 77)]] + + +def test_info_reads_a_ppm_written_by_hand(client, tmp_path): + path = tmp_path / "raw.ppm" + path.write_bytes(ppm_bytes(GRID)) + found = info(client, path).json() + assert (found["width"], found["height"], found["format"]) == (3, 2, "PPM") + + +def test_info_reads_latitude_and_longitude_as_signed_degrees(client, tmp_path): + path = tmp_path / "place.jpg" + exif = Image.Exif() + exif[0x8825] = {1: "N", 2: (40.0, 30.0, 0.0), 3: "W", 4: (74.0, 15.0, 0.0)} + Image.new("RGB", (8, 8), F).save(path, "JPEG", exif=exif) + gps = info(client, path).json()["gps"] + assert gps["lat"] == pytest.approx(40.5) and gps["lon"] == pytest.approx(-74.25) + + +@pytest.mark.parametrize( + "name,content,status,message", + [ + ("notes.png", b"plain words", 415, "formtools cannot read that file as a picture"), + ("empty.jpg", b"", 415, "formtools cannot read that file as a picture"), + ("drawing.svg", b"", 415, "SVG pictures are shown by the window itself"), + ("photo.jxl", b"\xff\x0a", 415, "JPEG XL has no cleared decoder in this build"), + ("sky.hdr", b"plain words\n", 415, "that file is not a Radiance HDR picture"), + ("sky2.hdr", b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n", 415, "the Radiance HDR header is cut short"), + ("sky3.hdr", b"#?RADIANCE\n\n+X 2 -Y 2\n", 415, "rotated Radiance HDR layouts are not supported"), + ("sky4.hdr", b"#?RADIANCE\n\nsize 2 by 2\n", 415, "the Radiance HDR size line is not understood"), + ], +) +def test_info_refuses_a_file_that_is_not_a_readable_picture(client, tmp_path, name, content, status, message): + path = tmp_path / name + path.write_bytes(content) + assert error_of(info(client, path)) == (status, message) + + +def test_info_refuses_a_missing_file_and_a_folder(client, tmp_path): + assert error_of(info(client, tmp_path / "gone.png")) == (404, "that file does not exist") + assert error_of(info(client, tmp_path)) == (400, "that path is not a file") + + +def test_a_rating_and_label_go_into_a_sidecar_and_the_picture_is_not_changed(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + reply = client.post("/api/meta/write", json={"path": str(path), "rating": 4, "label": "red"}).json() + assert (reply["rating"], reply["label"]) == (4, "red") + assert path.read_bytes() == png_bytes(GRID) + sidecar = tmp_path / "six.png.xmp" + assert stored(sidecar, "Rating") == "4" and stored(sidecar, "Label") == "Red" + read = client.post("/api/meta/read", json={"paths": [str(path)]}).json()["items"][str(path)] + assert (read["rating"], read["label"]) == (4, "red") + found = info(client, path).json()["xmp"] + assert (found["rating"], found["label"]) == (4, "red") + + +def test_a_rating_of_0_and_a_null_label_remove_them_again(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + client.post("/api/meta/write", json={"path": str(path), "rating": 5, "label": "green"}) + reply = client.post("/api/meta/write", json={"path": str(path), "rating": 0, "label": None}).json() + assert (reply["rating"], reply["label"]) == (0, None) + read = client.post("/api/meta/read", json={"paths": [str(path)]}).json()["items"][str(path)] + assert (read["rating"], read["label"]) == (0, None) + assert stored(tmp_path / "six.png.xmp", "Rating") in ("0", None) + + +def test_setting_only_the_label_keeps_the_rating(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + client.post("/api/meta/write", json={"path": str(path), "rating": 2}) + reply = client.post("/api/meta/write", json={"path": str(path), "label": "purple"}).json() + assert (reply["rating"], reply["label"]) == (2, "purple") + + +def test_a_sidecar_written_by_hand_is_read(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + (tmp_path / "six.xmp").write_text(HAND_XMP, encoding="utf-8") + read = client.post("/api/meta/read", json={"paths": [str(path), str(tmp_path / "gone.png")]}).json()["items"] + assert (read[str(path)]["rating"], read[str(path)]["label"]) == (3, "blue") + assert read[str(tmp_path / "gone.png")] == {"rating": 0, "label": None} + + +@pytest.mark.parametrize( + "body,message", + [ + ({"rating": 6}, "rating must be a whole number from 0 to 5"), + ({"rating": -1}, "rating must be a whole number from 0 to 5"), + ({"label": "pink"}, "label must be red, orange, yellow, green, blue, purple, grey or null"), + ], +) +def test_a_bad_rating_or_label_is_refused_and_no_sidecar_appears(client, tmp_path, body, message): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + assert error_of(client.post("/api/meta/write", json={"path": str(path), **body})) == (400, message) + assert [p.name for p in tmp_path.iterdir()] == ["six.png"] + + +def test_a_sidecar_that_is_not_xmp_is_left_alone(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + sidecar = tmp_path / "six.png.xmp" + sidecar.write_text("mine", encoding="utf-8") + reply = client.post("/api/meta/write", json={"path": str(path), "rating": 1}) + assert reply.status_code == 400 and "left it alone" in reply.json()["error"] + assert sidecar.read_text(encoding="utf-8") == "mine" + + +def test_hdr_info_reports_the_size_on_the_size_line(client, tmp_path): + path = tmp_path / "sky.hdr" + path.write_bytes(hdr_bytes([[(128, 128, 128, 128)] * 3] * 2)) + found = info(client, path).json() + assert (found["width"], found["height"], found["format"], found["bit_depth"]) == (3, 2, "HDR", 32) + + +def test_radiance_values_up_to_1_are_shown_with_the_srgb_curve(client, tmp_path): + path = tmp_path / "dim.hdr" + rows = [[(127, 127, 127, 128), (0, 0, 0, 0)], [(63, 127, 255, 128), (127, 127, 127, 126)]] + path.write_bytes(hdr_bytes(rows)) + wanted = [[tuple(srgb8(rgbe_value(m, p[3])) for m in p[:3]) for p in row] for row in rows] + assert wanted[0][1] == (0, 0, 0) and wanted[0][0] == (187, 187, 187) + assert close(edited(client, path), wanted, 1) + + +@pytest.mark.parametrize("mantissa,exponent", [(127, 130), (180, 130)]) +def test_a_bright_grey_radiance_picture_is_exposed_to_middle_grey_then_filmic_mapped(client, tmp_path, mantissa, exponent): + path = tmp_path / "bright.hdr" + path.write_bytes(hdr_bytes([[(mantissa, mantissa, mantissa, exponent)] * 4] * 4)) + assert rgbe_value(mantissa, exponent) > 1.0 + level = srgb8(aces(0.18)) + assert close(edited(client, path), [[(level, level, level)] * 4] * 4, 1) + + +def test_a_very_bright_radiance_picture_is_darkened_by_at_most_four_stops(client, tmp_path): + path = tmp_path / "sun.hdr" + path.write_bytes(hdr_bytes([[(127, 127, 127, 133)] * 4] * 4)) + level = srgb8(aces(rgbe_value(127, 133) / 16.0)) + assert close(edited(client, path), [[(level, level, level)] * 4] * 4, 1) + + +def test_a_bright_two_level_radiance_picture_follows_exposure_from_the_geometric_mean(client, tmp_path): + path = tmp_path / "two.hdr" + low, high = (127, 127, 127, 130), (127, 127, 127, 134) + path.write_bytes(hdr_bytes([[low, high]] * 2)) + values = [rgbe_value(127, 130), rgbe_value(127, 134)] + exposure = min(16.0, max(0.0625, 0.18 / math.sqrt(values[0] * values[1]))) + wanted = [[(srgb8(aces(v * exposure)),) * 3 for v in values]] * 2 + assert close(edited(client, path), wanted, 1) + + +def test_a_bottom_up_radiance_picture_is_shown_top_row_last(client, tmp_path): + path = tmp_path / "up.hdr" + dark, light = (0, 0, 0, 0), (255, 255, 255, 128) + path.write_bytes(hdr_bytes([[dark, dark], [light, light]], size_line=b"+Y 2 +X 2")) + assert edited(client, path) == [[(255, 255, 255)] * 2, [(0, 0, 0)] * 2] + + +def test_a_right_to_left_radiance_picture_is_mirrored(client, tmp_path): + path = tmp_path / "back.hdr" + dark, light = (0, 0, 0, 0), (255, 255, 255, 128) + path.write_bytes(hdr_bytes([[dark, light]], size_line=b"-Y 1 -X 2")) + assert edited(client, path) == [[(255, 255, 255), (0, 0, 0)]] + + +def test_run_length_and_flat_radiance_files_of_the_same_pixels_decode_alike(client, tmp_path): + rows = [[(127, 127, 127, 128)] * 4 + [(63, 63, 63, 127)] * 4, [(255, 0, 0, 128)] * 8] + flat, packed = tmp_path / "flat.hdr", tmp_path / "packed.hdr" + flat.write_bytes(hdr_bytes(rows)) + packed.write_bytes(hdr_run_length_bytes(rows)) + assert packed.read_bytes() != flat.read_bytes() + wanted = [[tuple(srgb8(rgbe_value(m, p[3])) for m in p[:3]) for p in row] for row in rows] + assert close(edited(client, packed), wanted, 1) + assert edited(client, packed) == edited(client, flat) + + +def test_a_radiance_file_with_missing_pixels_is_refused(client, tmp_path): + path = tmp_path / "short.hdr" + path.write_bytes(hdr_bytes([[(127, 127, 127, 128)] * 2] * 2)[:-5]) + reply = client.get("/api/image/view", params={"path": str(path)}) + assert error_of(reply) == (415, "the Radiance HDR pixel data is cut short") + + +def test_tonemap_maps_display_range_values_through_the_srgb_curve_and_keeps_alpha(): + from app.tools.image.tonemap import tonemap + + linear = np.array([[[0.0, 0.5, 1.0, 0.25], [float("nan"), 0.0031308, 0.2, 1.0]]], dtype=np.float32) + out = tonemap(linear) + assert out.shape == (1, 2, 4) + assert out[0, 0].tolist() == [0, 188, 255, 64] + assert out[0, 1].tolist() == [0, srgb8(0.0031308), srgb8(0.2), 255] + + +def test_tonemap_turns_one_channel_into_equal_red_green_and_blue(): + from app.tools.image.tonemap import tonemap + + assert tonemap(np.array([[0.5, 1.0]], dtype=np.float32)).tolist() == [[[188, 188, 188], [255, 255, 255]]] + + +def test_view_shrinks_to_the_longest_side_asked_for_and_keeps_the_shape(client, tmp_path): + import io + + path = tmp_path / "wide.png" + path.write_bytes(png_bytes([[F] * 40] * 20)) + reply = client.get("/api/image/view", params={"path": str(path), "max": 10}) + assert reply.headers["content-type"] == "image/webp" + with Image.open(io.BytesIO(reply.content)) as image: + assert image.format == "WEBP" and image.size == (10, 5) + assert all(abs(a - b) <= 4 for a, b in zip(image.convert("RGB").getpixel((5, 2)), F)) + + +def test_view_keeps_see_through_pixels_by_answering_with_png(client, tmp_path): + import io + + path = tmp_path / "glass.png" + grid = [[(9, 8, 7, 0), (9, 8, 7, 255)]] + path.write_bytes(png_bytes(grid)) + reply = client.get("/api/image/view", params={"path": str(path)}) + assert reply.headers["content-type"] == "image/png" + with Image.open(io.BytesIO(reply.content)) as image: + assert [image.getpixel((0, 0)), image.getpixel((1, 0))] == grid[0] + + +def test_view_refuses_a_size_outside_its_range(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + for value in (-1, 30001): + assert error_of(client.get("/api/image/view", params={"path": str(path), "max": value})) == (400, "max must be between 0 and 30000") + + +def test_a_thumbnail_is_never_smaller_than_64_pixels_on_its_long_side(client, tmp_path): + path = tmp_path / "wide.png" + path.write_bytes(png_bytes([[A] * 100 + [B] * 100] * 100)) + reply = client.get("/api/image/thumb", params={"path": str(path), "size": 8}) + assert reply.headers["content-type"] == "image/webp" + import io + + with Image.open(io.BytesIO(reply.content)) as image: + assert image.size == (64, 32) + left, right = image.convert("RGB").getpixel((8, 16)), image.convert("RGB").getpixel((56, 16)) + assert left[0] > 200 and left[1] < 60 and right[1] > 200 and right[0] < 60 + + +def test_a_thumbnail_of_a_text_file_is_refused(client, tmp_path): + path = tmp_path / "notes.png" + path.write_text("words") + assert error_of(client.get("/api/image/thumb", params={"path": str(path)})) == (415, "formtools cannot decode that file as a picture") diff --git a/backend/tests/image/test_orientation_and_turns.py b/backend/tests/image/test_orientation_and_turns.py new file mode 100644 index 0000000..62335e5 --- /dev/null +++ b/backend/tests/image/test_orientation_and_turns.py @@ -0,0 +1,124 @@ +import pytest +from PIL import Image + +from .support import GRID, SHOWN_FOR_ORIENTATION, error_of, flip_h, flip_v, png_bytes, ppm_bytes, read_grid, turn_180, turn_ccw, turn_cw + +def info(client, path): + return client.get("/api/image/info", params={"path": str(path)}) + + +def turn(client, path, op, **more): + return client.post("/api/image/transform", json={"path": str(path), "op": op, **more}) + + +@pytest.mark.parametrize("orientation", range(1, 9)) +def test_the_orientation_tag_decides_how_the_stored_pixels_are_shown(client, tmp_path, orientation): + path = tmp_path / "tagged.png" + path.write_bytes(png_bytes(GRID, orientation)) + shown = SHOWN_FOR_ORIENTATION[orientation](GRID) + found = info(client, path).json() + assert (found["width"], found["height"], found["orientation"]) == (len(shown[0]), len(shown), orientation) + out = client.post("/api/image/edit", json={"path": str(path), "ops": [{"op": "flip", "axis": "h"}, {"op": "flip", "axis": "h"}]}).json()["path"] + assert read_grid(out) == shown + with Image.open(out) as image: + assert image.getexif().get(0x0112, 1) == 1 + + +@pytest.mark.parametrize( + "op,geometry", + [("rotate-cw", turn_cw), ("rotate-ccw", turn_ccw), ("rotate-180", turn_180), ("flip-h", flip_h), ("flip-v", flip_v)], +) +def test_turning_a_png_in_place_moves_the_pixels_where_geometry_says(client, tmp_path, op, geometry): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + reply = turn(client, path, op).json() + assert reply == {"ok": True, "lossless_used": True, "path": str(path)} + assert read_grid(path) == geometry(GRID) + assert sorted(p.name for p in tmp_path.iterdir()) == ["six.png"] + + +def test_turning_a_tagged_png_applies_the_tag_first_and_resets_it(client, tmp_path): + path = tmp_path / "tagged.png" + path.write_bytes(png_bytes(GRID, 6)) + turn(client, path, "rotate-cw") + assert read_grid(path) == turn_180(GRID) + assert info(client, path).json()["orientation"] == 1 + + +def test_a_clockwise_then_a_counterclockwise_turn_gives_back_the_picture(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + turn(client, path, "rotate-cw") + turn(client, path, "rotate-ccw") + assert read_grid(path) == GRID + + +@pytest.mark.parametrize("op,tag", [("rotate-cw", 6), ("rotate-ccw", 8), ("rotate-180", 3), ("flip-h", 2), ("flip-v", 4)]) +def test_a_lossless_jpeg_turn_only_writes_the_orientation_tag(client, tmp_path, op, tag): + path = tmp_path / "photo.jpg" + Image.new("RGB", (16, 8), (200, 40, 40)).save(path, "JPEG", quality=90) + before = path.read_bytes() + reply = turn(client, path, op).json() + assert reply["lossless_used"] is True + after = path.read_bytes() + scan = before[before.index(b"\xff\xda") :] + assert after.endswith(scan) + with Image.open(path) as image: + assert image.getexif()[0x0112] == tag + assert image.size == (16, 8) + found = info(client, path).json() + assert (found["width"], found["height"]) == ((8, 16) if tag in (6, 8) else (16, 8)) + + +def test_two_lossless_quarter_turns_of_a_jpeg_make_a_half_turn_tag(client, tmp_path): + path = tmp_path / "photo.jpg" + Image.new("RGB", (16, 8), (200, 40, 40)).save(path, "JPEG") + turn(client, path, "rotate-cw") + turn(client, path, "rotate-cw") + with Image.open(path) as image: + assert image.getexif()[0x0112] == 3 + turn(client, path, "rotate-180") + with Image.open(path) as image: + assert image.getexif()[0x0112] == 1 + + +def test_a_jpeg_turn_without_lossless_rewrites_the_pixels_at_the_new_size(client, tmp_path): + path = tmp_path / "photo.jpg" + Image.new("RGB", (16, 8), (200, 40, 40)).save(path, "JPEG", quality=95) + reply = turn(client, path, "rotate-cw", lossless=False).json() + assert reply["lossless_used"] is False + with Image.open(path) as image: + assert image.size == (8, 16) + assert all(abs(a - b) <= 4 for a, b in zip(image.getpixel((4, 8)), (200, 40, 40))) + + +def test_a_ppm_is_view_only_and_is_left_alone(client, tmp_path): + path = tmp_path / "raw.ppm" + path.write_bytes(ppm_bytes(GRID)) + before = path.read_bytes() + reply = turn(client, path, "rotate-cw") + assert error_of(reply) == (415, "formtools can turn JPEG, PNG, WebP, GIF, BMP and TIFF files; other formats are view-only") + assert path.read_bytes() == before + + +def test_turning_a_text_file_is_refused_and_the_file_is_left_alone(client, tmp_path): + path = tmp_path / "notes.jpg" + path.write_text("not a picture") + assert error_of(turn(client, path, "flip-h")) == (415, "formtools cannot read that file as a picture") + assert path.read_text() == "not a picture" + + +def test_turning_a_missing_file_is_refused(client, tmp_path): + assert error_of(turn(client, tmp_path / "gone.png", "flip-h")) == (404, "that file does not exist") + + +def test_turning_a_folder_is_refused(client, tmp_path): + assert error_of(turn(client, tmp_path, "flip-h")) == (400, "that path is not a file") + + +def test_an_unknown_turn_is_refused(client, tmp_path): + path = tmp_path / "six.png" + path.write_bytes(png_bytes(GRID)) + reply = turn(client, path, "rotate-45") + assert error_of(reply) == (400, "the request is missing or has a bad value for op") + assert read_grid(path) == GRID diff --git a/backend/tests/media/__init__.py b/backend/tests/media/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/media/support.py b/backend/tests/media/support.py new file mode 100644 index 0000000..8f1ea05 --- /dev/null +++ b/backend/tests/media/support.py @@ -0,0 +1,105 @@ +import base64 +import json +import struct +from pathlib import Path + +TRIANGLE = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)] +JSON_TYPE = 0x4E4F534A +BIN_TYPE = 0x004E4942 + + +def floats(points) -> bytes: + return b"".join(struct.pack("<3f", *p) for p in points) + + +def bounds(points) -> tuple[list[float], list[float]]: + return [min(p[i] for p in points) for i in range(3)], [max(p[i] for p in points) for i in range(3)] + + +def document(points=TRIANGLE, nodes=None, scenes=None, mode=None, indices=None, uri=True, with_bounds=True, extra=None) -> dict: + data = floats(points) + index_bytes = b"".join(struct.pack(" Path: + doc, _ = document(**kw) + target = folder / name + target.write_text(json.dumps(doc), encoding="utf-8") + return target + + +def glb_bytes(doc: dict, blob: bytes) -> bytes: + text = json.dumps(doc, separators=(",", ":")).encode() + text += b" " * ((4 - len(text) % 4) % 4) + body = struct.pack(" Path: + doc, blob = document(uri=False, **kw) + target = folder / name + target.write_bytes(glb_bytes(doc, blob)) + return target + + +def read_glb(data: bytes) -> tuple[dict, bytes]: + magic, version, length = struct.unpack("<4sII", data[:12]) + assert magic == b"glTF" and version == 2 and length == len(data) + size, kind = struct.unpack(" bytes: + body = b"".join(struct.pack("<3f", 0, 0, 0) + floats(t) + b"\0\0" for t in triangles) + return b"\0" * 80 + struct.pack(" list[tuple]: + count = struct.unpack(" None: + with tarfile.open(path, "w:gz") as bundle: + for name, data in members.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + info.mode = 0o755 + bundle.addfile(info, io.BytesIO(data)) + for info in extra or []: + bundle.addfile(info) + + +def library(version: str) -> bytes: + return f"package Image::ExifTool;\nour $VERSION = '{version}';\n1;\n".encode() + + +def test_unpacking_a_package_puts_the_script_and_library_in_the_staging_folder(tmp_path): + pinned = fetch.package() + archive = tmp_path / "p.tgz" + make_tar(archive, {"package/bin/" + pinned["script"]: b"#!perl\n", "package/bin/" + pinned["library"]: library(fetch.EXIFTOOL), "package/LICENSE": b"licence"}) + staged = tmp_path / "staged" + staged.mkdir() + fetch.unpack(archive, staged) + fetch.check_library(staged) + assert (staged / pinned["script"]).read_bytes() == b"#!perl\n" + assert (staged / "NPM-PACKAGE-LICENSE.txt").read_bytes() == b"licence" + + +def test_a_package_with_a_path_that_climbs_out_of_the_folder_is_refused(tmp_path): + archive = tmp_path / "p.tgz" + make_tar(archive, {"package/bin/../../evil": b"x"}) + staged = tmp_path / "staged" + staged.mkdir() + with pytest.raises(ValueError, match="unsafe path"): + fetch.unpack(archive, staged) + assert not (tmp_path / "evil").exists() + + +def test_a_package_holding_a_symbolic_link_is_refused(tmp_path): + link = tarfile.TarInfo("package/bin/exiftool") + link.type = tarfile.SYMTYPE + link.linkname = "/etc/passwd" + archive = tmp_path / "p.tgz" + make_tar(archive, {}, extra=[link]) + staged = tmp_path / "staged" + staged.mkdir() + with pytest.raises(ValueError, match="link or special file"): + fetch.unpack(archive, staged) + + +def test_a_package_of_another_exiftool_version_is_refused_and_names_both_versions(tmp_path): + pinned = fetch.package() + archive = tmp_path / "p.tgz" + make_tar(archive, {"package/bin/" + pinned["script"]: b"x", "package/bin/" + pinned["library"]: library("1.00")}) + staged = tmp_path / "staged" + staged.mkdir() + fetch.unpack(archive, staged) + with pytest.raises(ValueError, match=f"holds ExifTool 1.00, not {fetch.EXIFTOOL}"): + fetch.check_library(staged) + + +def test_installing_a_download_whose_hash_differs_from_the_pin_places_nothing(tmp_path): + archive = tmp_path / "p.tgz" + make_tar(archive, {"package/bin/exiftool": b"x"}) + where = tmp_path / "out" / "exiftool" + with pytest.raises(ValueError, match="does not match the pinned integrity"): + fetch.install(archive, "sha512-AAAA", where) + assert not where.exists() diff --git a/backend/tests/media/test_gltf_info.py b/backend/tests/media/test_gltf_info.py new file mode 100644 index 0000000..97dcc74 --- /dev/null +++ b/backend/tests/media/test_gltf_info.py @@ -0,0 +1,249 @@ +import json +import math +import struct + +import pytest + +from .support import TRIANGLE, document, glb_bytes, read_glb, write_glb, write_gltf + + +def info(client, path): + return client.get("/api/model/info", params={"path": str(path)}) + + +def test_a_one_triangle_gltf_reports_one_mesh_three_vertices_one_triangle(client, tmp_path): + body = info(client, write_gltf(tmp_path)).json() + assert (body["format"], body["meshes"], body["vertices"], body["triangles"], body["nodes"]) == ("gltf", 1, 3, 1, 1) + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [1.0, 1.0, 0.0]} + assert body["units"] == "m" + + +def test_a_one_triangle_glb_reports_the_same_counts_and_box_as_the_gltf(client, tmp_path): + glb = info(client, write_glb(tmp_path)).json() + gltf = info(client, write_gltf(tmp_path)).json() + assert glb["format"] == "glb" + for key in ("meshes", "vertices", "triangles", "bbox", "nodes"): + assert glb[key] == gltf[key] + assert glb["triangles"] == 1 + + +def test_a_node_translation_moves_the_box_by_the_same_amount(client, tmp_path): + body = info(client, write_gltf(tmp_path, nodes=[{"mesh": 0, "translation": [10, 20, 30]}])).json() + assert body["bbox"] == {"min": [10.0, 20.0, 30.0], "max": [11.0, 21.0, 30.0]} + + +def test_a_node_scale_stretches_the_box_on_each_axis(client, tmp_path): + body = info(client, write_gltf(tmp_path, nodes=[{"mesh": 0, "scale": [2, 3, 4]}])).json() + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [2.0, 3.0, 0.0]} + + +def test_a_quarter_turn_about_z_maps_x_to_y_and_y_to_minus_x(client, tmp_path): + half = math.sqrt(0.5) + body = info(client, write_gltf(tmp_path, nodes=[{"mesh": 0, "rotation": [0, 0, half, half]}])).json() + assert body["bbox"]["min"] == pytest.approx([-1.0, 0.0, 0.0], abs=1e-6) + assert body["bbox"]["max"] == pytest.approx([0.0, 1.0, 0.0], abs=1e-6) + + +def test_a_column_major_matrix_carries_its_translation_in_the_last_column(client, tmp_path): + matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 5, 6, 7, 1] + body = info(client, write_gltf(tmp_path, nodes=[{"mesh": 0, "matrix": matrix}])).json() + assert body["bbox"] == {"min": [5.0, 6.0, 7.0], "max": [6.0, 7.0, 7.0]} + + +def test_a_child_node_inherits_its_parents_translation(client, tmp_path): + nodes = [{"translation": [1, 0, 0], "children": [1]}, {"mesh": 0, "translation": [0, 2, 0]}] + body = info(client, write_gltf(tmp_path, nodes=nodes)).json() + assert body["bbox"] == {"min": [1.0, 2.0, 0.0], "max": [2.0, 3.0, 0.0]} + assert body["nodes"] == 2 + + +def test_the_scale_applies_before_the_translation_as_the_format_says(client, tmp_path): + body = info(client, write_gltf(tmp_path, nodes=[{"mesh": 0, "scale": [2, 2, 2], "translation": [1, 1, 1]}])).json() + assert body["bbox"] == {"min": [1.0, 1.0, 1.0], "max": [3.0, 3.0, 1.0]} + + +def test_one_mesh_drawn_by_two_nodes_counts_its_vertices_twice(client, tmp_path): + nodes = [{"mesh": 0}, {"mesh": 0, "translation": [5, 0, 0]}] + body = info(client, write_gltf(tmp_path, nodes=nodes, scenes=[{"nodes": [0, 1]}])).json() + assert (body["meshes"], body["vertices"], body["triangles"]) == (1, 6, 2) + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [6.0, 1.0, 0.0]} + + +def test_a_node_outside_the_chosen_scene_is_not_counted(client, tmp_path): + nodes = [{"mesh": 0}, {"mesh": 0, "translation": [100, 0, 0]}] + body = info(client, write_gltf(tmp_path, nodes=nodes, scenes=[{"nodes": [0]}])).json() + assert (body["vertices"], body["triangles"]) == (3, 1) + assert body["bbox"]["max"] == [1.0, 1.0, 0.0] + + +def test_the_scene_index_picks_which_scene_is_measured(client, tmp_path): + nodes = [{"mesh": 0}, {"mesh": 0, "translation": [0, 0, 9]}] + doc_path = write_gltf(tmp_path, nodes=nodes, scenes=[{"nodes": [0]}, {"nodes": [1]}], extra={"scene": 1}) + body = info(client, doc_path).json() + assert body["bbox"] == {"min": [0.0, 0.0, 9.0], "max": [1.0, 1.0, 9.0]} + + +def test_without_scenes_every_node_that_is_no_child_is_a_root(client, tmp_path): + nodes = [{"mesh": 0, "children": [1]}, {"mesh": 0, "translation": [0, 3, 0]}, {"mesh": 0, "translation": [-2, 0, 0]}] + doc, _ = document(nodes=nodes) + del doc["scenes"] + del doc["scene"] + target = tmp_path / "noscene.gltf" + target.write_text(json.dumps(doc), encoding="utf-8") + body = info(client, target).json() + assert (body["vertices"], body["triangles"]) == (9, 3) + assert body["bbox"] == {"min": [-2.0, 0.0, 0.0], "max": [1.0, 4.0, 0.0]} + + +def test_an_indexed_quad_counts_four_vertices_and_two_triangles(client, tmp_path): + quad = [(0, 0, 0), (2, 0, 0), (2, 3, 0), (0, 3, 0)] + body = info(client, write_gltf(tmp_path, points=quad, indices=[0, 1, 2, 0, 2, 3])).json() + assert (body["vertices"], body["triangles"]) == (4, 2) + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [2.0, 3.0, 0.0]} + + +@pytest.mark.parametrize( + "mode,count,expected", + [(4, 6, 2), (5, 5, 3), (6, 4, 2), (5, 2, 0), (0, 6, 0), (1, 6, 0), (2, 6, 0), (3, 6, 0)], + ids=["triangles", "strip", "fan", "short-strip", "points", "lines", "line-loop", "line-strip"], +) +def test_the_triangle_count_follows_the_primitive_mode(client, tmp_path, mode, count, expected): + points = [(float(i), float(i % 2), 0.0) for i in range(count)] + body = info(client, write_gltf(tmp_path, points=points, mode=mode)).json() + assert body["vertices"] == count + assert body["triangles"] == expected + + +def test_lists_of_materials_images_animations_skins_are_counted(client, tmp_path): + extra = { + "materials": [{}, {}], + "images": [{"uri": "data:image/png;base64,AA=="}, {"uri": "data:image/png;base64,AA=="}, {"uri": "data:image/png;base64,AA=="}], + "textures": [{"source": 0}], + "animations": [{"channels": [], "samplers": []}], + } + body = info(client, write_gltf(tmp_path, extra=extra)).json() + assert (body["materials"], body["textures"], body["animations"]) == (2, 3, 1) + + +def test_textures_are_counted_when_the_file_lists_no_images(client, tmp_path): + body = info(client, write_gltf(tmp_path, extra={"textures": [{}, {}]})).json() + assert body["textures"] == 2 + + +def test_a_position_without_min_and_max_gives_an_empty_box_and_says_so(client, tmp_path): + body = info(client, write_gltf(tmp_path, with_bounds=False)).json() + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [0.0, 0.0, 0.0]} + assert "the file gives no position bounds, so the box is empty" in body["notes"] + assert body["vertices"] == 3 + + +def test_required_extensions_compression_generator_and_skins_appear_in_the_notes(client, tmp_path): + extra = { + "extensionsRequired": ["KHR_materials_variants"], + "extensionsUsed": ["KHR_draco_mesh_compression", "KHR_materials_variants"], + "asset": {"version": "2.0", "generator": "Hand Writer 1"}, + "skins": [{"joints": [0]}], + } + notes = info(client, write_gltf(tmp_path, extra=extra)).json()["notes"] + assert "requires glTF extensions: KHR_materials_variants" in notes + assert "uses compression: KHR_draco_mesh_compression" in notes + assert "written by Hand Writer 1" in notes + assert "1 skin(s) with joints" in notes + + +def test_a_missing_buffer_file_and_one_outside_the_folder_are_both_reported(client, tmp_path): + extra = {"images": [{"uri": "missing.png"}, {"uri": "../outside.png"}]} + (tmp_path.parent / "outside.png").write_bytes(b"x") + folder = tmp_path / "model" + folder.mkdir() + notes = info(client, write_gltf(folder, extra=extra)).json()["notes"] + assert "2 referenced file(s) are missing or outside the model's folder" in notes + + +def test_a_buffer_file_beside_the_model_is_not_reported_missing(client, tmp_path): + doc, blob = document(uri=False) + doc["buffers"][0]["uri"] = "tri.bin" + (tmp_path / "tri.bin").write_bytes(blob) + (tmp_path / "tri.gltf").write_text(json.dumps(doc), encoding="utf-8") + body = info(client, tmp_path / "tri.gltf").json() + assert not any("missing" in note for note in body["notes"]) + assert body["triangles"] == 1 + + +def test_a_glb_with_the_wrong_magic_is_refused(client, tmp_path): + target = tmp_path / "bad.glb" + target.write_bytes(b"gLTF" + glb_bytes(*document(uri=False))[4:]) + answer = info(client, target) + assert answer.status_code == 422 + assert answer.json()["error"] == "that file is not a valid GLB container" + + +def test_a_glb_shorter_than_its_header_is_refused(client, tmp_path): + target = tmp_path / "short.glb" + target.write_bytes(b"glTF\x02\x00\x00\x00") + answer = info(client, target) + assert (answer.status_code, answer.json()["error"]) == (422, "that file is not a valid GLB container") + + +def test_a_glb_whose_first_chunk_is_binary_is_refused(client, tmp_path): + good = glb_bytes(*document(uri=False)) + target = tmp_path / "swapped.glb" + target.write_bytes(good[:16] + struct.pack(" bytes: + buffer = io.BytesIO() + Image.new("RGB", (width, height), (200, 30, 30)).save(buffer, "PNG") + return buffer.getvalue() + + +def pcm(*runs) -> bytes: + return b"".join(struct.pack(" 00:01.000\nhello\n".encode()) + answer = subtitle(client, target, file="clip.en.vtt") + assert answer.status_code == 200 + assert answer.headers["content-type"].startswith("text/vtt") + assert answer.text == "WEBVTT\n\n00:00.000 --> 00:01.000\nhello\n" + + +@pytest.mark.parametrize("name", ["sub/clip.vtt", "clip.txt", "../clip.vtt"]) +def test_a_subtitle_file_from_another_folder_or_of_another_kind_is_refused(client, rig, name): + target = rig.file("clip.mp4") + answer = subtitle(client, target, file=name) + assert (answer.status_code, answer.json()["error"]) == (400, "the subtitle file must be a .srt, .ass, .ssa or .vtt file beside the video") + + +def test_an_absolute_subtitle_path_in_another_folder_is_refused(client, rig, tmp_path): + target = rig.file("clip.mp4") + elsewhere = tmp_path / "elsewhere.vtt" + elsewhere.write_text("WEBVTT\n", encoding="utf-8") + assert subtitle(client, target, file=str(elsewhere)).status_code == 400 + + +def test_a_missing_subtitle_file_and_a_request_naming_neither_index_nor_file_are_refused(client, rig): + target = rig.file("clip.mp4") + missing = subtitle(client, target, file="none.vtt") + assert (missing.status_code, missing.json()["error"]) == (404, "that subtitle file does not exist") + neither = subtitle(client, target) + assert (neither.status_code, neither.json()["error"]) == (400, "give index (an embedded subtitle stream) or file (a subtitle file beside the video)") + + +def test_an_srt_file_is_converted_to_webvtt_by_ffmpeg_reading_its_first_subtitle_stream(client, rig): + rig.ffmpeg(payload=b"WEBVTT\n\nconverted\n") + target = rig.file("clip.mp4") + srt = rig.file("clip.srt", b"1\n00:00:00,000 --> 00:00:01,000\nhi\n") + answer = subtitle(client, target, file="clip.srt") + assert answer.text == "WEBVTT\n\nconverted\n" + args = rig.calls("ffmpeg")[0] + assert args[args.index("-i") + 1] == str(srt) + assert args[args.index("-map") + 1] == "0:s:0" + assert args[-3:] == ["-f", "webvtt", "pipe:1"] + + +def test_an_embedded_text_stream_is_converted_by_its_index_and_a_picture_stream_is_refused(client, rig): + rig.ffprobe(probe_doc([video(), stream(2, "subtitle", "subrip"), stream(3, "subtitle", "hdmv_pgs_subtitle")])) + rig.ffmpeg(payload=b"WEBVTT\n") + target = rig.file("clip.mkv") + assert subtitle(client, target, index=2).text == "WEBVTT\n" + assert rig.calls("ffmpeg")[0][rig.calls("ffmpeg")[0].index("-map") + 1] == "0:2" + refused = subtitle(client, target, index=3) + assert (refused.status_code, refused.json()["error"]) == (400, "that stream is not a text subtitle stream") + + +def test_a_conversion_that_gives_nothing_is_refused(client, rig): + rig.ffmpeg(payload=b"") + target = rig.file("clip.mp4") + rig.file("clip.srt", b"x") + answer = subtitle(client, target, file="clip.srt") + assert (answer.status_code, answer.json()["error"]) == (400, "ffmpeg could not convert those subtitles to WebVTT") + + +def snapshot(client, path, at): + return client.post("/api/media/snapshot", json={"path": str(path), "time": at}) + + +def test_the_stamp_is_hours_minutes_seconds_and_milliseconds_and_carries_a_rounded_up_second(): + assert preview.stamp(3725.5) == "01-02-05.500" + assert preview.stamp(59.9996) == "00-01-00.000" + assert preview.stamp(0) == "00-00-00.000" + + +def test_a_snapshot_is_saved_beside_the_video_named_with_the_time(client, rig): + rig.ffprobe(probe_doc([video()], duration="10")) + rig.ffmpeg(payload=png(32, 32)) + target = rig.file("a.mp4") + body = snapshot(client, target, 5.25).json() + expected = rig.work / "a 00-00-05.250.png" + assert body == {"ok": True, "path": str(expected)} + assert expected.read_bytes() == png(32, 32) + args = rig.calls("ffmpeg")[0] + assert args[args.index("-ss") + 1] == "5.250" + assert args[args.index("-map") + 1] == "0:0" + assert args[args.index("-frames:v") + 1] == "1" + + +def test_a_second_snapshot_at_the_same_time_gets_a_numbered_name_instead_of_overwriting(client, rig): + rig.ffprobe(probe_doc([video()], duration="10")) + rig.ffmpeg(payload=png(8, 8)) + target = rig.file("a.mp4") + snapshot(client, target, 1) + second = snapshot(client, target, 1).json() + assert second["path"] == str(rig.work / "a 00-00-01.000 (2).png") + assert (rig.work / "a 00-00-01.000.png").exists() + + +def test_a_snapshot_after_the_end_of_the_video_is_refused(client, rig): + rig.ffprobe(probe_doc([video()], duration="10")) + rig.ffmpeg() + answer = snapshot(client, rig.file("a.mp4"), 10.5) + assert (answer.status_code, answer.json()["error"]) == (400, "time is outside the video") + assert not list(rig.work.glob("*.png")) + + +def test_a_negative_snapshot_time_is_refused_by_the_request_check(client, rig): + rig.ffprobe(probe_doc([video()], duration="10")) + answer = snapshot(client, rig.file("a.mp4"), -1) + assert answer.status_code == 400 + assert answer.json()["ok"] is False + assert not list(rig.work.glob("*.png")) + + +def test_a_snapshot_of_an_audio_file_is_refused(client, rig): + rig.ffprobe(probe_doc([audio(0, "mp3")], names="mp3")) + rig.ffmpeg() + answer = snapshot(client, rig.file("a.mp3"), 0) + assert (answer.status_code, answer.json()["error"]) == (400, "that file has no video to take a picture of") + + +def test_a_snapshot_ffmpeg_fails_on_leaves_no_picture_file_behind(client, rig): + rig.ffprobe(probe_doc([video()], duration="10")) + rig.ffmpeg(fail="boom") + answer = snapshot(client, rig.file("a.mp4"), 2) + assert (answer.status_code, answer.json()["error"]) == (400, "ffmpeg could not take a picture at that time") + assert not list(rig.work.glob("*.png")) diff --git a/backend/tests/media/test_media_status_probe.py b/backend/tests/media/test_media_status_probe.py new file mode 100644 index 0000000..ade2166 --- /dev/null +++ b/backend/tests/media/test_media_status_probe.py @@ -0,0 +1,178 @@ +import os + +from app.tools.media import fetch + +from .tools import audio, probe_doc, rig, stream, video, script, FFMPEG + + +def info(client, path): + return client.get("/api/media/info", params={"path": str(path)}) + + +def test_status_with_no_ffmpeg_anywhere_reports_nothing_found_and_no_error(client, rig): + assert client.get("/api/media/status").json() == {"ffmpeg": None, "ffprobe": None, "version": None, "fetching": False, "error": None} + + +def test_status_finds_ffmpeg_and_ffprobe_on_path_and_reads_the_version_word(client, rig, monkeypatch): + rig.ffmpeg() + rig.ffprobe(probe_doc([video()])) + monkeypatch.setenv("FAKE_VERSION", "6.1.1") + body = client.get("/api/media/status").json() + assert body["ffmpeg"] == str(rig.bin / "ffmpeg") + assert body["ffprobe"] == str(rig.bin / "ffprobe") + assert body["version"] == "6.1.1" + + +def test_status_prefers_the_fetched_copy_and_puts_its_folder_first_on_path(client, rig): + where = fetch.folder() + where.mkdir(parents=True) + script(where, f"ffmpeg-{fetch.host_triple()}", FFMPEG) + rig.ffmpeg() + body = client.get("/api/media/status").json() + assert body["ffmpeg"] == str(where / "ffmpeg") + assert os.environ["PATH"].split(os.pathsep)[0] == str(where) + assert (where / "ffmpeg").exists() + + +def test_status_says_when_a_download_is_running_and_what_error_the_last_one_left(client, rig, monkeypatch): + monkeypatch.setitem(fetch.STATE, "fetching", True) + monkeypatch.setitem(fetch.STATE, "error", "ffmpeg could not be fetched: no network") + body = client.get("/api/media/status").json() + assert body["fetching"] is True + assert body["error"] == "ffmpeg could not be fetched: no network" + + +def test_info_without_ffprobe_is_refused_with_the_install_hint(client, rig): + target = rig.file("a.mp4") + answer = info(client, target) + assert answer.status_code == 503 + assert answer.json()["error"] == "ffmpeg is not installed; put it on PATH or start formtools with FORM_FFMPEG_AUTO=1" + + +def test_info_while_ffmpeg_is_downloading_asks_to_try_again(client, rig, monkeypatch): + monkeypatch.setitem(fetch.STATE, "fetching", True) + answer = info(client, rig.file("a.mp4")) + assert (answer.status_code, answer.json()["error"]) == (503, "ffmpeg is still being downloaded, try again in a minute") + + +def test_info_after_a_failed_download_repeats_the_download_error(client, rig, monkeypatch): + monkeypatch.setitem(fetch.STATE, "error", "ffmpeg 1 could not be fetched: offline") + answer = info(client, rig.file("a.mp4")) + assert (answer.status_code, answer.json()["error"]) == (503, "ffmpeg 1 could not be fetched: offline") + + +def test_info_names_a_missing_file_a_folder_and_a_relative_path_before_looking_for_tools(client, rig): + assert (info(client, rig.work / "none.mp4").status_code, info(client, rig.work / "none.mp4").json()["error"]) == (404, "that file does not exist") + folder = info(client, rig.work) + assert (folder.status_code, folder.json()["error"]) == (400, "that path is not a file") + relative = client.get("/api/media/info", params={"path": "clip.mp4"}) + assert (relative.status_code, relative.json()["error"]) == (400, "the path must be absolute") + + +def test_info_runs_ffprobe_with_json_output_streams_format_chapters_and_the_path(client, rig): + rig.ffprobe(probe_doc([video(), audio()])) + target = rig.file("a.mp4") + assert info(client, target).status_code == 200 + assert rig.calls("ffprobe") == [["-v", "error", "-print_format", "json", "-show_format", "-show_streams", "-show_chapters", "-i", str(target)]] + + +def test_info_describes_a_video_stream_with_fraction_frame_rate_and_ten_bit_depth(client, rig): + rig.ffprobe(probe_doc([video(avg_frame_rate="30000/1001", pix_fmt="yuv420p10le", profile="Main 10")])) + body = info(client, rig.file("a.mp4")).json() + first = body["streams"][0] + assert (first["type"], first["codec"], first["width"], first["height"]) == ("video", "h264", 1920, 1080) + assert first["fps"] == 29.97 + assert first["bit_depth"] == 10 + assert first["profile"] == "Main 10" + + +def test_info_reads_eight_bit_depth_from_a_plain_pixel_format(client, rig): + rig.ffprobe(probe_doc([video(pix_fmt="yuv420p")])) + assert info(client, rig.file("a.mp4")).json()["streams"][0]["bit_depth"] == 8 + + +def test_info_reports_hdr_only_for_pq_or_hlg_transfer(client, rig): + hdr = video(color_transfer="smpte2084", color_primaries="bt2020", color_space="bt2020nc") + plain = video(1, color_transfer="bt709") + rig.ffprobe(probe_doc([hdr, plain])) + streams = info(client, rig.file("a.mp4")).json()["streams"] + assert streams[0]["hdr"] == {"transfer": "smpte2084", "primaries": "bt2020", "matrix": "bt2020nc"} + assert streams[1]["hdr"] is None + + +def test_info_describes_audio_streams_with_rate_language_and_flags(client, rig): + track = audio(1, tags={"LANGUAGE": "eng", "title": "Main"}, disposition={"default": 1, "forced": 0}, bit_rate="128000") + rig.ffprobe(probe_doc([video(), track])) + second = info(client, rig.file("a.mp4")).json()["streams"][1] + assert (second["type"], second["channels"], second["layout"], second["sample_rate"], second["bit_rate"]) == ("audio", 2, "stereo", 48000, 128000) + assert (second["language"], second["title"], second["default"], second["forced"]) == ("eng", "Main", True, False) + assert second["width"] is None and second["fps"] is None + + +def test_info_marks_attached_pictures_as_cover_and_gives_them_no_frame_rate(client, rig): + cover = video(1, "mjpeg", disposition={"attached_pic": 1}, avg_frame_rate="90000/1") + rig.ffprobe(probe_doc([audio(0, "mp3"), cover], names="mp3")) + second = info(client, rig.file("a.mp3")).json()["streams"][1] + assert second["cover"] is True + assert second["fps"] is None + + +def test_info_maps_chapters_and_format_numbers(client, rig): + chapters = [{"start_time": "0.000000", "end_time": "4.500000", "tags": {"title": "Intro"}}, {"start_time": "4.5", "end_time": "10", "tags": {}}] + rig.ffprobe(probe_doc([video()], duration="10.5", chapters=chapters, tags={"title": "Clip"})) + body = info(client, rig.file("a.mp4")).json() + assert body["chapters"] == [{"start": 0.0, "end": 4.5, "title": "Intro"}, {"start": 4.5, "end": 10.0, "title": None}] + assert body["format"]["duration"] == 10.5 + assert body["format"]["tags"] == {"title": "Clip"} + assert (body["format"]["bit_rate"], body["format"]["size"]) == (1000, 5) + + +def test_info_calls_h264_and_aac_in_an_mp4_file_playable_as_is(client, rig): + rig.ffprobe(probe_doc([video(), audio()])) + assert info(client, rig.file("a.mp4")).json()["playable"] == {"native": True, "remux": True} + + +def test_info_calls_h264_in_matroska_playable_only_after_a_stream_copy(client, rig): + rig.ffprobe(probe_doc([video(), audio()], names="matroska,webm")) + assert info(client, rig.file("a.mkv")).json()["playable"] == {"native": False, "remux": True} + + +def test_info_calls_vp9_and_opus_in_webm_playable_as_is(client, rig): + rig.ffprobe(probe_doc([video(0, "vp9"), audio(1, "opus")], names="matroska,webm")) + assert info(client, rig.file("a.webm")).json()["playable"] == {"native": True, "remux": True} + + +def test_info_calls_hevc_unplayable_even_by_copying(client, rig): + rig.ffprobe(probe_doc([video(0, "hevc"), audio()])) + assert info(client, rig.file("a.mp4")).json()["playable"] == {"native": False, "remux": False} + + +def test_info_calls_an_mp3_file_playable_and_a_flac_file_native_but_not_copyable_to_mp4_or_webm(client, rig): + rig.ffprobe(probe_doc([audio(0, "mp3")], names="mp3")) + assert info(client, rig.file("a.mp3")).json()["playable"] == {"native": True, "remux": True} + rig.ffprobe(probe_doc([audio(0, "flac")], names="flac")) + assert info(client, rig.file("b.flac")).json()["playable"] == {"native": True, "remux": False} + + +def test_info_refuses_a_file_ffprobe_cannot_read(client, rig, monkeypatch): + rig.ffprobe(probe_doc([video()])) + monkeypatch.setenv("FAKE_PROBE_CODE", "1") + answer = info(client, rig.file("junk.mp4")) + assert (answer.status_code, answer.json()["error"]) == (415, "that file is not a media file ffmpeg can read") + + +def test_info_refuses_a_file_with_no_streams(client, rig): + rig.ffprobe(probe_doc([])) + answer = info(client, rig.file("empty.mp4")) + assert (answer.status_code, answer.json()["error"]) == (415, "that file has no audio or video streams") + + +def test_info_asks_ffprobe_once_per_unchanged_file_and_again_after_the_file_changes(client, rig): + rig.ffprobe(probe_doc([video()])) + target = rig.file("a.mp4", b"one") + info(client, target) + info(client, target) + assert len(rig.calls("ffprobe")) == 1 + target.write_bytes(b"longer content") + info(client, target) + assert len(rig.calls("ffprobe")) == 2 diff --git a/backend/tests/media/test_model_assets_convert.py b/backend/tests/media/test_model_assets_convert.py new file mode 100644 index 0000000..ad592c0 --- /dev/null +++ b/backend/tests/media/test_model_assets_convert.py @@ -0,0 +1,275 @@ +import json +import struct + +import pytest + +from .support import TRIANGLE, binary_stl, document, read_binary_stl, read_glb, write_glb, write_gltf +from .tools import wait_job + +OBJ_QUAD = "# a unit quad\nv 0 0 0\nv 2 0 0\nv 2 3 0\nv 0 3 0\nf 1 2 3\nf 1 3 4\n" +PLY_TRIANGLE = "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n" +OFF_TRIANGLE = "OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n" + + +def info(client, path): + return client.get("/api/model/info", params={"path": str(path)}) + + +def convert(client, path, fmt, **more): + answer = client.post("/api/model/convert", json={"path": str(path), "format": fmt, **more}) + assert answer.status_code == 200, answer.text + return wait_job(client, answer.json()["id"]) + + +def triangle_set(points): + return sorted(tuple(round(v, 5) for v in p) for p in points) + + +@pytest.mark.parametrize( + "name,text,counts,box", + [ + ("quad.obj", OBJ_QUAD, (4, 2), ([0, 0, 0], [2, 3, 0])), + ("tri.ply", PLY_TRIANGLE, (3, 1), ([0, 0, 0], [1, 1, 0])), + ("tri.off", OFF_TRIANGLE, (3, 1), ([0, 0, 0], [1, 1, 0])), + ], + ids=["obj", "ply", "off"], +) +def test_text_meshes_report_the_vertex_and_triangle_counts_and_box_their_format_defines(client, tmp_path, name, text, counts, box): + target = tmp_path / name + target.write_text(text, encoding="utf-8") + body = info(client, target).json() + assert (body["vertices"], body["triangles"]) == counts + assert body["bbox"] == {"min": [float(v) for v in box[0]], "max": [float(v) for v in box[1]]} + assert body["format"] == name.split(".")[1] + + +def test_a_binary_stl_with_two_triangles_sharing_an_edge_reports_four_vertices_after_merging(client, tmp_path): + target = tmp_path / "quad.stl" + target.write_bytes(binary_stl([[(0, 0, 0), (1, 0, 0), (1, 1, 0)], [(0, 0, 0), (1, 1, 0), (0, 1, 0)]])) + body = info(client, target).json() + assert (body["vertices"], body["triangles"]) == (4, 2) + assert body["bbox"] == {"min": [0.0, 0.0, 0.0], "max": [1.0, 1.0, 0.0]} + + +def test_a_model_format_the_engine_cannot_read_is_refused_with_the_window_hint(client, tmp_path): + target = tmp_path / "thing.fbx" + target.write_bytes(b"x") + answer = info(client, target) + assert (answer.status_code, answer.json()["error"]) == (415, "this engine cannot read fbx models; the window opens it directly when its loader supports it") + + +def test_a_missing_model_a_folder_and_a_relative_path_are_named(client, tmp_path): + missing = info(client, tmp_path / "none.glb") + assert (missing.status_code, missing.json()["error"]) == (404, "that file does not exist") + folder = info(client, tmp_path) + assert (folder.status_code, folder.json()["error"]) == (400, "that path is not a file") + relative = client.get("/api/model/info", params={"path": "a.glb"}) + assert (relative.status_code, relative.json()["error"]) == (400, "the path must be absolute") + + +def test_an_obj_with_no_geometry_is_refused(client, tmp_path): + target = tmp_path / "empty.obj" + target.write_text("# nothing here\n", encoding="utf-8") + answer = info(client, target) + assert answer.status_code == 422 + assert "obj" in answer.json()["error"] + + +def test_the_view_route_serves_an_stl_as_a_glb_with_the_same_triangle(client, tmp_path): + target = tmp_path / "tri.stl" + target.write_bytes(binary_stl([TRIANGLE])) + answer = client.get("/api/model/view", params={"path": str(target)}) + assert answer.status_code == 200 + doc, blob = read_glb(answer.content) + accessor = doc["accessors"][doc["meshes"][0]["primitives"][0]["attributes"]["POSITION"]] + view = doc["bufferViews"][accessor["bufferView"]] + start = view.get("byteOffset", 0) + accessor.get("byteOffset", 0) + corners = [struct.unpack("<3f", blob[start + 12 * k:start + 12 * k + 12]) for k in range(accessor["count"])] + assert triangle_set(corners) == triangle_set(TRIANGLE) + + +def test_viewing_the_same_unchanged_model_twice_gives_the_same_bytes(client, tmp_path): + target = tmp_path / "tri.stl" + target.write_bytes(binary_stl([TRIANGLE])) + first = client.get("/api/model/view", params={"path": str(target)}).content + second = client.get("/api/model/view", params={"path": str(target)}).content + assert first == second + + +def test_viewing_a_model_the_engine_cannot_read_is_refused(client, tmp_path): + target = tmp_path / "scene.dae" + target.write_bytes(b"x") + answer = client.get("/api/model/view", params={"path": str(target)}) + assert answer.status_code == 415 + + +def test_converting_a_gltf_to_stl_writes_one_triangle_beside_the_source(client, tmp_path): + source = write_gltf(tmp_path) + job = convert(client, source, "stl") + destination = tmp_path / "tri.stl" + assert job["state"] == "done" + assert job["result"] == {"path": str(destination)} + assert (job["done"], job["total"]) == (3, 3) + triangles = read_binary_stl(destination.read_bytes()) + assert len(triangles) == 1 + assert triangle_set(triangles[0]) == triangle_set(TRIANGLE) + + +def test_converting_a_gltf_to_obj_writes_three_vertices_and_one_face_with_one_based_indexes(client, tmp_path): + job = convert(client, write_gltf(tmp_path), "obj") + lines = (tmp_path / "tri.obj").read_text(encoding="utf-8").splitlines() + vertices = [tuple(float(x) for x in line.split()[1:4]) for line in lines if line.startswith("v ")] + faces = [line.split()[1:] for line in lines if line.startswith("f ")] + assert job["state"] == "done" + assert triangle_set(vertices) == triangle_set(TRIANGLE) + assert len(faces) == 1 + assert sorted(int(part.split("/")[0]) for part in faces[0]) == [1, 2, 3] + + +def test_converting_a_gltf_to_ply_writes_a_header_that_counts_three_vertices_and_one_face(client, tmp_path): + convert(client, write_gltf(tmp_path), "ply") + head = (tmp_path / "tri.ply").read_bytes().split(b"end_header")[0].decode("ascii") + assert head.startswith("ply\n") + assert "element vertex 3" in head + assert "element face 1" in head + + +def test_converting_a_gltf_to_off_writes_the_off_counts_line_and_the_vertices(client, tmp_path): + convert(client, write_gltf(tmp_path), "off") + tokens = (tmp_path / "tri.off").read_text(encoding="utf-8").split() + assert tokens[0] == "OFF" + assert tokens[1:3] == ["3", "1"] + numbers = [float(t) for t in tokens[4:13]] + corners = [tuple(numbers[i:i + 3]) for i in range(0, 9, 3)] + assert triangle_set(corners) == triangle_set(TRIANGLE) + + +@pytest.mark.parametrize("fmt", ["glb", "obj", "stl", "ply", "off"]) +def test_a_converted_file_reports_the_same_counts_and_box_as_its_source(client, tmp_path, fmt): + source = write_gltf(tmp_path, nodes=[{"mesh": 0, "translation": [1, 2, 3]}]) + first = info(client, source).json() + job = convert(client, source, fmt) + again = info(client, job["result"]["path"]).json() + assert (again["vertices"], again["triangles"]) == (first["vertices"], first["triangles"]) + assert again["bbox"]["min"] == pytest.approx(first["bbox"]["min"], abs=1e-5) + assert again["bbox"]["max"] == pytest.approx(first["bbox"]["max"], abs=1e-5) + + +def test_a_second_conversion_to_the_same_format_gets_a_numbered_name(client, tmp_path): + source = write_gltf(tmp_path) + convert(client, source, "stl") + second = convert(client, source, "stl") + assert second["result"]["path"] == str(tmp_path / "tri (2).stl") + + +def test_an_output_name_without_the_extension_gets_it_added_and_a_missing_folder_is_refused(client, tmp_path): + source = write_gltf(tmp_path) + (tmp_path / "out").mkdir() + job = convert(client, source, "stl", out=str(tmp_path / "out" / "result")) + assert job["result"]["path"] == str(tmp_path / "out" / "result.stl") + answer = client.post("/api/model/convert", json={"path": str(source), "format": "stl", "out": str(tmp_path / "gone" / "x")}) + assert (answer.status_code, answer.json()["error"]) == (400, "the output folder does not exist") + + +def test_a_format_outside_the_five_writable_ones_is_refused(client, tmp_path): + answer = client.post("/api/model/convert", json={"path": str(write_gltf(tmp_path)), "format": "fbx"}) + assert answer.status_code == 400 + assert not list(tmp_path.glob("*.fbx")) + + +def test_a_point_cloud_cannot_become_an_stl_and_no_empty_file_is_left(client, tmp_path): + source = tmp_path / "cloud.ply" + source.write_text("ply\nformat ascii 1.0\nelement vertex 2\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 1 1\n", encoding="utf-8") + job = convert(client, source, "stl") + assert job["state"] == "failed" + assert job["errors"][0]["error"] == "that model has no faces, so it cannot be written as STL" + assert not (tmp_path / "cloud.stl").exists() + + +def test_converting_a_model_the_engine_cannot_read_is_refused(client, tmp_path): + source = tmp_path / "m.fbx" + source.write_bytes(b"x") + answer = client.post("/api/model/convert", json={"path": str(source), "format": "glb"}) + assert answer.status_code == 415 + + +def asset(client, model, uri): + return client.get("/api/model/asset", params={"path": str(model), "uri": uri}) + + +@pytest.fixture +def folder(tmp_path): + inner = tmp_path / "inner" + inner.mkdir() + doc, blob = document(uri=False) + doc["buffers"][0]["uri"] = "tri.bin" + (inner / "tri.gltf").write_text(json.dumps(doc), encoding="utf-8") + (inner / "tri.bin").write_bytes(blob) + (inner / "tex.png").write_bytes(b"\x89PNG\r\n\x1a\nxx") + (inner / "m.mtl").write_text("newmtl a\n", encoding="utf-8") + (tmp_path / "secret.txt").write_text("secret", encoding="utf-8") + return inner + + +def test_a_buffer_beside_the_model_is_served_with_its_bytes_and_a_no_sniff_header(client, folder): + answer = asset(client, folder / "tri.gltf", "tri.bin") + assert answer.status_code == 200 + assert answer.content == (folder / "tri.bin").read_bytes() + assert answer.headers["content-type"] == "application/octet-stream" + assert answer.headers["x-content-type-options"] == "nosniff" + + +def test_a_png_and_an_mtl_beside_the_model_are_served_with_their_own_types(client, folder): + assert asset(client, folder / "tri.gltf", "tex.png").headers["content-type"] == "image/png" + assert asset(client, folder / "tri.gltf", "m.mtl").headers["content-type"].startswith("text/plain") + + +def test_a_query_string_or_fragment_on_the_uri_is_ignored_and_percent_escapes_are_decoded(client, folder): + (folder / "my tex.png").write_bytes(b"p") + assert asset(client, folder / "tri.gltf", "tri.bin?v=2#x").content == (folder / "tri.bin").read_bytes() + assert asset(client, folder / "tri.gltf", "my%20tex.png").content == b"p" + + +@pytest.mark.parametrize("uri", ["../secret.txt", "%2e%2e/secret.txt", "..%2fsecret.txt", "sub/../../secret.txt", "..\\secret.txt"]) +def test_a_uri_that_climbs_out_of_the_models_folder_is_refused_and_the_secret_not_served(client, folder, uri): + answer = asset(client, folder / "tri.gltf", uri) + assert answer.status_code in (403, 404) + assert b"secret" not in answer.content + + +def test_a_symbolic_link_leading_outside_the_folder_is_refused(client, folder, tmp_path): + (folder / "link.txt").symlink_to(tmp_path / "secret.txt") + answer = asset(client, folder / "tri.gltf", "link.txt") + assert (answer.status_code, answer.json()["error"]) == (403, "that file is outside the model's folder") + + +@pytest.mark.parametrize( + "uri,status,message", + [ + ("data:application/octet-stream;base64,AAAA", 403, "only files beside the model can be served, not data or network addresses"), + ("http://example.invalid/x.bin", 403, "only files beside the model can be served, not data or network addresses"), + ("//host/share/x", 403, "only files beside the model can be served, not data or network addresses"), + ("/etc/passwd", 403, "absolute paths are not served"), + ("C:/Windows/win.ini", 403, "only files beside the model can be served, not data or network addresses"), + ("nothere.bin", 404, "that file does not exist beside the model"), + ("", 400, "a uri is needed"), + ], +) +def test_assets_that_are_not_plain_files_beside_the_model_are_refused_with_the_reason(client, folder, uri, status, message): + answer = asset(client, folder / "tri.gltf", uri) + assert (answer.status_code, answer.json()["error"]) == (status, message) + + +def test_assets_are_only_served_for_model_files_and_never_for_a_text_file(client, folder): + answer = asset(client, folder.parent / "secret.txt", "secret.txt") + assert (answer.status_code, answer.json()["error"]) == (400, "assets are served only for gltf, obj, mtl, dae and fbx models") + + +def test_an_asset_request_for_a_model_that_is_gone_is_a_404(client, folder): + answer = asset(client, folder / "gone.gltf", "tri.bin") + assert (answer.status_code, answer.json()["error"]) == (404, "that model does not exist") + + +def test_a_folder_named_as_the_asset_is_not_served(client, folder): + (folder / "textures").mkdir() + assert asset(client, folder / "tri.gltf", "textures").status_code == 404 diff --git a/backend/tests/media/tools.py b/backend/tests/media/tools.py new file mode 100644 index 0000000..8bd1d4e --- /dev/null +++ b/backend/tests/media/tools.py @@ -0,0 +1,219 @@ +import json +import os +import sys +from collections import OrderedDict +from pathlib import Path + +import pytest + +FFPROBE = """#!{py} +import json, os, sys +log = os.environ.get("FAKE_LOG") +if log: + open(log, "a").write(json.dumps(["ffprobe"] + sys.argv[1:]) + "\\n") +code = int(os.environ.get("FAKE_PROBE_CODE", "0")) +if code: + sys.exit(code) +sys.stdout.write(open(os.environ["FAKE_PROBE_JSON"]).read()) +""" + +FFMPEG = """#!{py} +import json, os, sys +args = sys.argv[1:] +if args[:2] == ["-hide_banner", "-version"]: + print("ffmpeg version " + os.environ.get("FAKE_VERSION", "1.2.3") + " Copyright (c) test") + sys.exit(0) +log = os.environ.get("FAKE_LOG") +if log: + open(log, "a").write(json.dumps(["ffmpeg"] + args) + "\\n") +if os.environ.get("FAKE_FFMPEG_FAIL"): + sys.stderr.write(os.environ["FAKE_FFMPEG_FAIL"] + "\\n") + sys.exit(1) +payload = b"" +if os.environ.get("FAKE_PAYLOAD"): + payload = open(os.environ["FAKE_PAYLOAD"], "rb").read() +last = args[-1] +if "-progress" in args: + sys.stdout.write("out_time_us=2500000\\nprogress=continue\\n") + sys.stdout.flush() +if last == "pipe:1": + sys.stdout.buffer.write(payload) + sys.stdout.buffer.flush() +else: + open(last, "wb").write(payload) +""" + +EXIFTOOL = """#!{py} +import json, os, sys, time +args = sys.argv[1:] +if args == ["-ver"]: + print(os.environ.get("FAKE_EXIF_VERSION", "12.76")) + sys.exit(0) +log = os.environ.get("FAKE_EXIF_LOG") +pending = [] +lines = iter(sys.stdin.readline, "") +for line in lines: + line = line.rstrip("\\n") + if line == "-stay_open": + sys.stdin.readline() + break + if not line.startswith("-execute"): + pending.append(line) + continue + seq = line[len("-execute"):] + name = os.path.basename(pending[-1]) + if log: + open(log, "a").write(json.dumps(pending) + "\\n") + if "crash" in name: + sys.stderr.write("boom\\n") + sys.stderr.flush() + os._exit(1) + if "slow" in name: + time.sleep(3) + if "garbage" in name: + body = "this is not json" + else: + body = open(os.environ["FAKE_EXIF_JSON"]).read() + sys.stdout.write(body + "\\n{ready" + seq + "}\\n") + sys.stdout.flush() + pending = [] +""" + + +def script(folder: Path, name: str, body: str) -> Path: + target = folder / name + target.write_text(body.replace("{py}", sys.executable), encoding="utf-8") + target.chmod(0o755) + return target + + +def stream(index, kind, codec, **more) -> dict: + return {"index": index, "codec_type": kind, "codec_name": codec, **more} + + +def video(index=0, codec="h264", **more) -> dict: + return stream(index, "video", codec, **{"width": 1920, "height": 1080, "avg_frame_rate": "30/1", "pix_fmt": "yuv420p", **more}) + + +def audio(index=1, codec="aac", **more) -> dict: + return stream(index, "audio", codec, **{"channels": 2, "channel_layout": "stereo", "sample_rate": "48000", **more}) + + +def probe_doc(streams, names="mov,mp4,m4a,3gp,3g2,mj2", duration="10.000000", chapters=None, tags=None) -> dict: + return { + "streams": streams, + "format": {"format_name": names, "format_long_name": "x", "duration": duration, "bit_rate": "1000", "size": "5", "tags": tags or {}}, + "chapters": chapters or [], + } + + +class Rig: + def __init__(self, folder: Path, monkeypatch) -> None: + self.folder = folder + self.bin = folder / "bin" + self.bin.mkdir() + self.work = folder / "work" + self.work.mkdir() + self.log = folder / "calls.log" + self.mp = monkeypatch + monkeypatch.setenv("PATH", str(self.bin)) + monkeypatch.setenv("HOME", str(folder / "home")) + monkeypatch.setenv("XDG_DATA_HOME", str(folder / "share")) + monkeypatch.setenv("LOCALAPPDATA", str(folder / "share")) + monkeypatch.setenv("FORMTOOLS_DATA_DIR", str(folder / "data")) + monkeypatch.setenv("FAKE_LOG", str(self.log)) + for name in ("FAKE_FFMPEG_FAIL", "FAKE_PAYLOAD", "FAKE_PROBE_CODE", "FAKE_VERSION", "FORMCUT_FFMPEG_RELEASE"): + monkeypatch.delenv(name, raising=False) + from app.tools.media import exe, fetch, probe + + monkeypatch.setitem(fetch.STATE, "fetching", False) + monkeypatch.setitem(fetch.STATE, "error", None) + monkeypatch.setattr(exe, "_versions", {}) + monkeypatch.setattr(probe, "_cache", OrderedDict()) + self.count = 0 + + def ffmpeg(self, payload: bytes | None = None, fail: str | None = None) -> None: + script(self.bin, "ffmpeg", FFMPEG) + if payload is not None: + holder = self.folder / "payload.bin" + holder.write_bytes(payload) + self.mp.setenv("FAKE_PAYLOAD", str(holder)) + if fail: + self.mp.setenv("FAKE_FFMPEG_FAIL", fail) + + def ffprobe(self, doc: dict) -> None: + script(self.bin, "ffprobe", FFPROBE) + holder = self.folder / "probe.json" + holder.write_text(json.dumps(doc), encoding="utf-8") + self.mp.setenv("FAKE_PROBE_JSON", str(holder)) + + def file(self, name: str, data: bytes = b"media") -> Path: + target = self.work / name + target.write_bytes(data) + return target + + def calls(self, program: str) -> list[list[str]]: + if not self.log.exists(): + return [] + rows = [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()] + return [row[1:] for row in rows if row[0] == program] + + +@pytest.fixture +def rig(tmp_path, monkeypatch): + return Rig(tmp_path, monkeypatch) + + +class ExifRig: + def __init__(self, folder: Path, monkeypatch) -> None: + self.folder = folder + self.bin = folder / "bin" + self.bin.mkdir() + self.mp = monkeypatch + self.log = folder / "exif.log" + monkeypatch.setenv("PATH", str(self.bin)) + monkeypatch.setenv("FORMTOOLS_DATA_DIR", str(folder / "data")) + monkeypatch.setenv("FAKE_EXIF_LOG", str(self.log)) + for name in ("FORMTOOLS_EXIFTOOL", "FORMTOOLS_EXIFTOOL_REGISTRY", "FAKE_EXIF_VERSION"): + monkeypatch.delenv(name, raising=False) + from app.tools.exif import fetch, locate + + monkeypatch.setitem(fetch.STATE, "fetching", False) + monkeypatch.setitem(fetch.STATE, "error", None) + monkeypatch.setitem(fetch.STATE, "job", None) + monkeypatch.setattr(locate, "_versions", {}) + + def perl(self) -> Path: + return script(self.bin, "perl", '#!/bin/sh\nexec "{py}" "$@"\n') + + def tool(self, answer: dict | str, where: Path | None = None, name: str = "exiftool") -> Path: + target = script(where or self.bin, name, EXIFTOOL) + holder = self.folder / "answer.json" + holder.write_text(answer if isinstance(answer, str) else json.dumps([answer]), encoding="utf-8") + self.mp.setenv("FAKE_EXIF_JSON", str(holder)) + return target + + def calls(self) -> list[list[str]]: + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()] + + +@pytest.fixture +def exif_rig(tmp_path, monkeypatch): + from app.tools.exif import runner + + made = ExifRig(tmp_path, monkeypatch) + yield made + runner.stop() + + +def wait_job(client, job_id: str) -> dict: + import time + + for _ in range(250): + body = client.get(f"/api/jobs/{job_id}").json() + if body["state"] != "running": + return body + time.sleep(0.02) + raise AssertionError("the job did not finish") diff --git a/backend/tests/utilities/__init__.py b/backend/tests/utilities/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/utilities/support.py b/backend/tests/utilities/support.py new file mode 100644 index 0000000..d3cab56 --- /dev/null +++ b/backend/tests/utilities/support.py @@ -0,0 +1,74 @@ +import os +import time +from pathlib import Path + +import pytest + + +def finish(client, started: dict, seconds: float = 20.0) -> dict: + job = started + deadline = time.monotonic() + seconds + while job["state"] == "running": + if time.monotonic() > deadline: + raise AssertionError(f"job {job['id']} did not finish") + time.sleep(0.02) + job = client.get(f"/api/jobs/{job['id']}").json() + return job + + +def run_job(client, url: str, body: dict) -> dict: + reply = client.post(url, json=body) + assert reply.status_code == 200, reply.text + return finish(client, reply.json()) + + +def disk(client, root: Path, **extra) -> dict: + job = run_job(client, "/api/diskusage/scan", {"root": str(root), **extra}) + assert job["state"] == "done", job + return job["result"] + + +def dupes(client, roots, **extra) -> dict: + job = run_job(client, "/api/dupes/scan", {"roots": [str(r) for r in roots], **extra}) + assert job["state"] == "done", job + return job["result"] + + +def put(path: Path, data: bytes) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path + + +def pattern(size: int, seed: int) -> bytes: + return bytes((i * 31 + seed) % 251 for i in range(size)) + + +def group_sets(result: dict) -> set: + return {frozenset(Path(f["path"]).name for f in group["files"]) for group in result["groups"]} + + +def can_link(tmp_path: Path) -> bool: + probe = tmp_path / "probe" + probe.write_bytes(b"x") + try: + os.symlink(probe, tmp_path / "probe-link") + except (OSError, NotImplementedError): + return False + return True + + +@pytest.fixture +def hosts_file(tmp_path, monkeypatch): + path = tmp_path / "etc" / "hosts" + path.parent.mkdir() + monkeypatch.setenv("FORMTOOLS_HOSTS_PATH", str(path)) + return path + + +@pytest.fixture +def profile(tmp_path, monkeypatch): + home = tmp_path / "profile-config" + home.mkdir() + monkeypatch.setenv("XDG_CONFIG_HOME", str(home)) + return home / "environment.d" / "60-formtools.conf" diff --git a/backend/tests/utilities/test_utilities_desktop.py b/backend/tests/utilities/test_utilities_desktop.py new file mode 100644 index 0000000..45a47c1 --- /dev/null +++ b/backend/tests/utilities/test_utilities_desktop.py @@ -0,0 +1,292 @@ +import json +import os +import re +import sys + +import pytest +from PIL import Image + +from app.core.errors import ApiError +from app.tools.desktop import elevate, envvars, thumbnail +from .support import profile, put + +posix_only = pytest.mark.skipif(sys.platform == "darwin" or os.name == "nt", reason="the user scope is a file only on Linux") + + +def user_vars(client): + scope = [s for s in client.get("/api/env").json()["scopes"] if s["id"] == "user"][0] + return {row["name"]: row["value"] for row in scope["vars"] if not row.get("readonly")} + + +@posix_only +def test_a_user_variable_is_written_to_the_profile_file_and_read_back(client, profile): + reply = client.post("/api/env", json={"scope": "user", "name": "FORM_TEST_ONE", "value": "hello"}) + assert reply.status_code == 200 + body = reply.json() + assert body["ok"] is True and body["name"] == "FORM_TEST_ONE" and body["elevated"] is False + assert "FORM_TEST_ONE=hello\n" in profile.read_text(encoding="utf-8") + assert user_vars(client) == {"FORM_TEST_ONE": "hello"} + + +@posix_only +def test_the_profile_file_follows_the_environment_d_format(client, profile): + client.post("/api/env", json={"scope": "user", "name": "PLAIN", "value": "a/b:c.d"}) + client.post("/api/env", json={"scope": "user", "name": "SPACED", "value": 'two words and a "quote" and \\slash'}) + text = profile.read_text(encoding="utf-8") + assert text.startswith("# ") + assert "PLAIN=a/b:c.d\n" in text + assert 'SPACED="two words and a \\"quote\\" and \\\\slash"\n' in text + values = {} + for line in text.splitlines(): + if line and not line.startswith("#"): + name, _, raw = line.partition("=") + if raw.startswith('"'): + raw = re.sub(r"\\(.)", r"\1", raw[1:-1]) + values[name] = raw + assert values == {"PLAIN": "a/b:c.d", "SPACED": 'two words and a "quote" and \\slash'} + assert user_vars(client) == values + + +@posix_only +def test_setting_a_variable_again_replaces_it_in_place(client, profile): + for name, value in (("AAA", "1"), ("BBB", "2"), ("CCC", "3")): + client.post("/api/env", json={"scope": "user", "name": name, "value": value}) + client.post("/api/env", json={"scope": "user", "name": "BBB", "value": "two"}) + lines = [line for line in profile.read_text(encoding="utf-8").splitlines() if not line.startswith("#")] + assert lines == ["AAA=1", "BBB=two", "CCC=3"] + + +@posix_only +def test_a_null_value_removes_the_variable_and_keeps_the_others(client, profile): + for name, value in (("AAA", "1"), ("BBB", "2")): + client.post("/api/env", json={"scope": "user", "name": name, "value": value}) + assert client.post("/api/env", json={"scope": "user", "name": "AAA", "value": None}).json()["ok"] is True + assert user_vars(client) == {"BBB": "2"} + assert "AAA" not in profile.read_text(encoding="utf-8") + + +@posix_only +def test_other_lines_in_the_profile_file_are_left_alone(client, profile): + profile.parent.mkdir(parents=True) + profile.write_text("# mine\nKEEP=yes\n\n; semicolon remark\nOLD=1", encoding="utf-8") + client.post("/api/env", json={"scope": "user", "name": "OLD", "value": "2"}) + client.post("/api/env", json={"scope": "user", "name": "NEW", "value": "3"}) + assert profile.read_text(encoding="utf-8") == "# mine\nKEEP=yes\n\n; semicolon remark\nOLD=2\nNEW=3\n" + + +@posix_only +def test_other_environment_d_files_are_listed_read_only_and_never_changed(client, profile): + other = profile.parent / "10-other.conf" + other.parent.mkdir(parents=True) + other.write_text("FROM_OTHER=zzz\n", encoding="utf-8") + scope = [s for s in client.get("/api/env").json()["scopes"] if s["id"] == "user"][0] + rows = [row for row in scope["vars"] if row["name"] == "FROM_OTHER"] + assert rows == [{"name": "FROM_OTHER", "value": "zzz", "readonly": True, "source": str(other)}] + client.post("/api/env", json={"scope": "user", "name": "FROM_OTHER", "value": "mine"}) + assert other.read_text(encoding="utf-8") == "FROM_OTHER=zzz\n" + + +@posix_only +def test_the_user_scope_says_where_it_is_stored(client, profile): + scope = [s for s in client.get("/api/env").json()["scopes"] if s["id"] == "user"][0] + assert scope["editable"] is True + assert str(profile) in scope["where"] + + +def test_the_process_scope_lists_the_engine_environment_and_is_read_only(client, monkeypatch): + monkeypatch.setenv("FORM_PROCESS_MARK", "present") + scope = [s for s in client.get("/api/env").json()["scopes"] if s["id"] == "process"][0] + assert scope["editable"] is False + assert {"name": "FORM_PROCESS_MARK", "value": "present"} in scope["vars"] + reply = client.post("/api/env", json={"scope": "process", "name": "X", "value": "1"}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the process scope is read only" + + +def test_a_scope_can_be_asked_for_alone_through_the_tool(client, monkeypatch): + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "env_read", "arguments": {"scope": "process"}}}) + body = json.loads(reply.json()["result"]["content"][0]["text"]) + assert [s["id"] for s in body["scopes"]] == ["process"] + + +def test_asking_for_a_scope_the_system_does_not_have_is_refused(client): + with pytest.raises(ApiError) as caught: + envvars.scopes("nonsense") + assert caught.value.status == 400 + assert caught.value.message == "that scope does not exist on this system" + + +@pytest.mark.parametrize("name", ["1BAD", "has space", "a-b", "x=y", "", "d\u00e9j\u00e0"]) +@posix_only +def test_an_invalid_variable_name_is_refused_and_the_profile_untouched(client, profile, name): + reply = client.post("/api/env", json={"scope": "user", "name": name, "value": "v"}) + assert reply.status_code == 400 + assert reply.json()["error"] == f"{name or 'an empty name'} is not a valid variable name" + assert not profile.exists() + + +@pytest.mark.parametrize("value", ["one\ntwo", "a\rb", "nul\u0000byte"]) +@posix_only +def test_a_value_with_a_line_break_is_refused(client, profile, value): + reply = client.post("/api/env", json={"scope": "user", "name": "GOOD", "value": value}) + assert reply.status_code == 400 + assert reply.json()["error"] == "a value must stay on one line" + assert not profile.exists() + + +def test_an_unknown_scope_is_refused(client): + reply = client.post("/api/env", json={"scope": "galaxy", "name": "A", "value": "1"}) + assert reply.status_code == 400 + assert reply.json()["error"] == "scope must be user or system" + + +@posix_only +def test_the_system_scope_cannot_be_edited_on_this_system(client, profile): + reply = client.post("/api/env", json={"scope": "system", "name": "A", "value": "1"}) + assert reply.status_code == 400 + assert reply.json()["error"] == "that scope cannot be edited on this system" + assert not profile.exists() + + +def test_an_edit_never_changes_the_running_engine_environment(client, profile): + before = dict(os.environ) + client.post("/api/env", json={"scope": "user", "name": "FORM_NEVER_SET", "value": "1"}) + assert "FORM_NEVER_SET" not in os.environ + assert dict(os.environ) == before + + +def test_elevation_is_refused_when_no_prompt_program_exists_and_the_target_is_untouched(tmp_path, monkeypatch): + if sys.platform == "darwin" or sys.platform.startswith("win"): + pytest.skip("this check is for the pkexec path of Linux") + monkeypatch.setenv("PATH", str(tmp_path / "empty")) + target = tmp_path / "protected" + target.write_bytes(b"old") + with pytest.raises(ApiError) as caught: + elevate.write_file(target, b"new") + assert caught.value.status == 403 + assert caught.value.message == "administrator permission was not given, so nothing was changed (pkexec is not installed; edit the file as an administrator instead)" + assert target.read_bytes() == b"old" + + +def test_saving_a_hosts_file_that_needs_administrator_rights_is_refused_not_performed(client, tmp_path, monkeypatch): + if sys.platform == "darwin" or sys.platform.startswith("win"): + pytest.skip("this check is for the pkexec path of Linux") + target = tmp_path / "no-such-folder" / "hosts" + monkeypatch.setenv("FORMTOOLS_HOSTS_PATH", str(target)) + monkeypatch.setenv("PATH", str(tmp_path / "empty")) + reply = client.post("/api/hosts", json={"entries": [{"address": "10.0.0.1", "names": ["a.lan"]}]}) + assert reply.status_code == 403 + assert reply.json()["error"].startswith("administrator permission was not given, so nothing was changed") + assert not target.exists() + assert not (tmp_path / "no-such-folder").exists() + + +def test_elevation_leaves_no_staged_copy_behind(tmp_path, monkeypatch): + if sys.platform == "darwin" or sys.platform.startswith("win"): + pytest.skip("this check is for the pkexec path of Linux") + import tempfile + + scratch = tmp_path / "scratch" + scratch.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(scratch)) + monkeypatch.setenv("PATH", str(tmp_path / "empty")) + with pytest.raises(ApiError): + elevate.write_file(tmp_path / "t", b"data") + assert list(scratch.iterdir()) == [] + + +def test_a_refusal_carries_the_reason_when_one_is_given(): + assert elevate.refuse().message == "administrator permission was not given, so nothing was changed" + assert elevate.refuse("timed out").message == "administrator permission was not given, so nothing was changed (timed out)" + assert elevate.refuse().status == 403 + + +def test_a_missing_helper_program_is_a_refusal_not_a_crash(): + with pytest.raises(ApiError) as caught: + elevate.run(["/nonexistent/helper-program"]) + assert caught.value.status == 403 + + +def test_quoting_for_the_prompt_scripts_escapes_the_characters_that_would_end_a_string(): + assert elevate.applescript_literal('a"b\\c') == '"a\\"b\\\\c"' + assert elevate.powershell_literal("it's") == "'it''s'" + assert elevate.powershell_literal("\u2018x\u2019") == "'\u2018\u2018x\u2019\u2019'" + + +def test_the_copy_command_installs_a_new_file_and_overwrites_an_existing_one(tmp_path): + existing = tmp_path / "there" + existing.write_bytes(b"1") + assert elevate.copy_command(tmp_path / "s", existing) == ["/bin/cp", "-f", str(tmp_path / "s"), str(existing)] + assert elevate.copy_command(tmp_path / "s", tmp_path / "new")[:3] == ["/usr/bin/install", "-m", "644"] + + +def make_picture(path, size=(200, 100)): + Image.new("RGB", size, (10, 120, 200)).save(path) + + +def test_a_thumbnail_fits_the_requested_size_and_keeps_the_proportions(tmp_path): + make_picture(tmp_path / "in.png", (200, 100)) + code = thumbnail.main([str(tmp_path / "in.png"), str(tmp_path / "out.png"), "64"]) + assert code == 0 + with Image.open(tmp_path / "out.png") as out: + assert out.format == "PNG" + assert out.size == (64, 32) + assert out.convert("RGB").getpixel((10, 10)) == (10, 120, 200) + + +def test_a_thumbnail_is_never_made_larger_than_the_picture(tmp_path): + make_picture(tmp_path / "in.png", (40, 20)) + assert thumbnail.main([str(tmp_path / "in.png"), str(tmp_path / "out.png"), "512"]) == 0 + with Image.open(tmp_path / "out.png") as out: + assert max(out.size) <= 512 + assert out.size[0] == 2 * out.size[1] + + +def test_thumbnail_size_is_clamped_to_the_allowed_range(tmp_path): + make_picture(tmp_path / "in.png", (400, 400)) + assert thumbnail.main([str(tmp_path / "in.png"), str(tmp_path / "small.png"), "2"]) == 0 + with Image.open(tmp_path / "small.png") as out: + assert out.size == (thumbnail.MIN_SIZE, thumbnail.MIN_SIZE) + + +def test_thumbnail_of_a_missing_input_fails_with_a_message(tmp_path, capsys): + code = thumbnail.main([str(tmp_path / "none.png"), str(tmp_path / "out.png"), "64"]) + assert code == 1 + assert capsys.readouterr().err.strip() == "the input file does not exist" + assert not (tmp_path / "out.png").exists() + + +def test_thumbnail_with_the_wrong_number_of_arguments_prints_usage(capsys): + assert thumbnail.main(["only-one"]) == 2 + assert "usage: formtools-engine --thumbnail " in capsys.readouterr().err + + +def test_thumbnail_with_a_size_that_is_not_a_number_is_refused(tmp_path, capsys): + make_picture(tmp_path / "in.png") + assert thumbnail.main([str(tmp_path / "in.png"), str(tmp_path / "o.png"), "big"]) == 2 + assert capsys.readouterr().err.strip() == "the size big is not a number" + + +def test_thumbnail_of_a_damaged_picture_fails_without_writing_output(tmp_path, capsys): + put(tmp_path / "bad.png", b"not a picture") + code = thumbnail.main([str(tmp_path / "bad.png"), str(tmp_path / "o.png"), "64"]) + assert code == 1 + assert capsys.readouterr().err.strip() != "" + assert not (tmp_path / "o.png").exists() + + +def environment_d_value(line): + raw = line.partition("=")[2] + if raw.startswith('"') and raw.endswith('"'): + raw = re.sub(r"\\([\\\"$`])", r"\1", raw[1:-1]) + raw = raw.replace("$$", "\x00") + raw = re.sub(r"\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*", "", raw) + return raw.replace("\x00", "$") + + +@posix_only +@pytest.mark.xfail(strict=True, reason="DEFECT: a value holding a dollar sign is written with the dollar unescaped, so systemd expands it as a variable at login; environment.d(5) says a literal dollar sign must be doubled") +def test_a_value_with_a_dollar_sign_reads_back_literally_in_the_environment_d_format(client, profile): + client.post("/api/env", json={"scope": "user", "name": "PRICE", "value": "cost$HOME"}) + line = [row for row in profile.read_text(encoding="utf-8").splitlines() if row.startswith("PRICE=")][0] + assert environment_d_value(line) == "cost$HOME" diff --git a/backend/tests/utilities/test_utilities_diskusage.py b/backend/tests/utilities/test_utilities_diskusage.py new file mode 100644 index 0000000..df13a28 --- /dev/null +++ b/backend/tests/utilities/test_utilities_diskusage.py @@ -0,0 +1,203 @@ +import json +import os + +import pytest + +from .support import can_link, disk, finish, pattern, put + + +def build_tree(root): + sizes = {"a.txt": 10, "b.bin": 4096, "sub/c.jpg": 777, "sub/deep/d.mp4": 100000, "sub/deep/e.py": 1, "empty.dat": 0, "other/f.zip": 2048} + for name, size in sizes.items(): + put(root / name, pattern(size, size)) + return sizes + + +def test_disk_usage_total_equals_the_sum_of_the_file_sizes(client, tmp_path): + sizes = build_tree(tmp_path / "t") + result = disk(client, tmp_path / "t") + assert result["size"] == sum(sizes.values()) + assert result["files"] == len(sizes) + assert result["stats"]["apparent"] == sum(sizes.values()) + + +def test_disk_usage_counts_folders_beneath_the_root(client, tmp_path): + build_tree(tmp_path / "t") + result = disk(client, tmp_path / "t") + assert result["dirs"] == 3 + assert result["stats"]["folders"] == 3 + + +def test_every_folder_size_is_the_sum_of_what_is_inside_it(client, tmp_path): + sizes = build_tree(tmp_path / "t") + result = disk(client, tmp_path / "t") + by_name = {child["name"]: child for child in result["children"]} + assert by_name["sub"]["size"] == 777 + 100000 + 1 + assert by_name["other"]["size"] == 2048 + deep = {child["name"]: child for child in by_name["sub"]["children"]}["deep"] + assert deep["size"] == 100001 + assert by_name["b.bin"]["size"] == sizes["b.bin"] + + +def test_children_sizes_add_up_to_the_parent(client, tmp_path): + build_tree(tmp_path / "t") + result = disk(client, tmp_path / "t") + + def check(node): + if node.get("children"): + assert sum(c["size"] for c in node["children"]) == node["size"] + for child in node["children"]: + check(child) + + check(result) + + +def test_disk_usage_by_type_groups_files_by_extension_category(client, tmp_path): + build_tree(tmp_path / "t") + types = {row["category"]: row for row in disk(client, tmp_path / "t")["stats"]["by_type"]} + assert types["video"]["bytes"] == 100000 + assert types["images"]["bytes"] == 777 + assert types["archives"]["bytes"] == 2048 + assert types["code"]["bytes"] == 1 + assert types["video"]["files"] == 1 + assert sum(row["bytes"] for row in types.values()) == 10 + 4096 + 777 + 100000 + 1 + 2048 + + +def test_disk_usage_names_the_largest_files_biggest_first(client, tmp_path): + build_tree(tmp_path / "t") + largest = disk(client, tmp_path / "t")["stats"]["largest"] + assert [item["size"] for item in largest[:3]] == [100000, 4096, 2048] + assert largest[0]["path"].endswith("d.mp4") + assert [item["size"] for item in largest] == sorted((item["size"] for item in largest), reverse=True) + + +def test_disk_usage_of_an_empty_folder_is_zero(client, tmp_path): + (tmp_path / "void").mkdir() + result = disk(client, tmp_path / "void") + assert result["size"] == 0 and result["files"] == 0 + assert result["stats"]["average_file"] == 0 + assert result["stats"]["newest"] is None + + +def test_average_file_size_is_total_divided_by_file_count(client, tmp_path): + for index, size in enumerate((100, 200, 600)): + put(tmp_path / "t" / f"f{index}.dat", pattern(size, index)) + assert disk(client, tmp_path / "t")["stats"]["average_file"] == 300 + + +def test_hidden_files_are_left_out_unless_asked_for(client, tmp_path): + put(tmp_path / "t" / "seen.txt", b"x" * 50) + put(tmp_path / "t" / ".secret", b"y" * 70) + put(tmp_path / "t" / ".cfg" / "inner.txt", b"z" * 90) + assert disk(client, tmp_path / "t")["size"] == 50 + assert disk(client, tmp_path / "t", include_hidden=True)["size"] == 210 + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX hard links") +def test_a_hard_link_is_counted_once(client, tmp_path): + put(tmp_path / "t" / "one.bin", pattern(5000, 1)) + os.link(tmp_path / "t" / "one.bin", tmp_path / "t" / "two.bin") + result = disk(client, tmp_path / "t") + assert result["size"] == 5000 + assert result["stats"]["hardlinks_counted_once"] == 1 + + +def test_a_link_leading_out_of_the_tree_is_not_followed(client, tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + put(tmp_path / "outside" / "big.bin", pattern(90000, 3)) + put(tmp_path / "t" / "real.txt", b"r" * 40) + os.symlink(tmp_path / "outside" / "big.bin", tmp_path / "t" / "file-link") + os.symlink(tmp_path / "outside", tmp_path / "t" / "dir-link", target_is_directory=True) + result = disk(client, tmp_path / "t") + assert result["size"] == 40 + assert result["files"] == 1 + + +def test_a_link_pointing_back_up_does_not_make_the_scan_loop(client, tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + put(tmp_path / "t" / "a" / "x.txt", b"x" * 33) + os.symlink(tmp_path / "t", tmp_path / "t" / "a" / "loop", target_is_directory=True) + result = disk(client, tmp_path / "t") + assert result["size"] == 33 + assert result["dirs"] == 1 + + +def test_a_folder_with_more_than_sixty_children_folds_the_rest_into_other(client, tmp_path): + total = 0 + for index in range(75): + size = index + 1 + total += size + put(tmp_path / "t" / f"f{index:02}.dat", pattern(size, index)) + result = disk(client, tmp_path / "t") + assert result["size"] == total + assert len(result["children"]) == 61 + other = result["children"][-1] + assert other["other"] is True + assert other["name"] == "Other (15 items)" + assert other["size"] == sum(range(1, 16)) + assert sum(child["size"] for child in result["children"]) == total + assert {child["size"] for child in result["children"][:-1]} == set(range(16, 76)) + + +def test_a_tree_deeper_than_eight_levels_still_totals_every_byte(client, tmp_path): + folder = tmp_path / "t" + expected = 0 + for depth in range(12): + folder = folder / f"d{depth}" + put(folder / "leaf.txt", pattern(depth + 1, depth)) + expected += depth + 1 + result = disk(client, tmp_path / "t") + assert result["size"] == expected + assert result["files"] == 12 + assert result["dirs"] == 12 + + +def test_a_folder_named_like_a_cache_counts_its_files_as_system(client, tmp_path): + put(tmp_path / "t" / "node_modules" / "pkg" / "index.js", b"j" * 300) + put(tmp_path / "t" / "readme.txt", b"r" * 20) + types = {row["category"]: row["bytes"] for row in disk(client, tmp_path / "t")["stats"]["by_type"]} + assert types == {"system": 300, "documents": 20} + + +def test_a_file_without_extension_is_named_by_its_well_known_name(client, tmp_path): + put(tmp_path / "t" / "Makefile", b"all:\n" * 4) + put(tmp_path / "t" / "LICENSE", b"l" * 30) + put(tmp_path / "t" / "mystery", b"m" * 7) + types = {row["category"]: row["bytes"] for row in disk(client, tmp_path / "t")["stats"]["by_type"]} + assert types == {"code": 20, "documents": 30, "other": 7} + + +def test_disk_usage_of_a_missing_folder_is_refused_with_a_message(client, tmp_path): + reply = client.post("/api/diskusage/scan", json={"root": str(tmp_path / "nowhere")}) + assert reply.status_code == 404 + assert reply.json()["error"] == "that folder does not exist" + + +def test_disk_usage_of_a_file_is_refused_with_a_message(client, tmp_path): + put(tmp_path / "plain.txt", b"x") + reply = client.post("/api/diskusage/scan", json={"root": str(tmp_path / "plain.txt")}) + assert reply.status_code == 400 + assert reply.json()["error"] == "that path is not a folder" + + +def test_disk_usage_of_a_relative_path_is_refused(client): + reply = client.post("/api/diskusage/scan", json={"root": "relative/dir"}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the path must be absolute" + + +def test_the_disk_usage_tool_reports_the_same_total_as_the_route(client, tmp_path): + sizes = build_tree(tmp_path / "t") + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "disk_usage", "arguments": {"root": str(tmp_path / "t")}}}) + started = reply.json()["result"]["content"][0]["text"] + job = finish(client, json.loads(started)) + assert job["result"]["size"] == sum(sizes.values()) + + +def test_allocated_space_is_never_less_than_zero_and_covers_nonempty_files(client, tmp_path): + put(tmp_path / "t" / "a.dat", pattern(10, 1)) + stats = disk(client, tmp_path / "t")["stats"] + assert stats["apparent"] == 10 + assert stats["allocated"] >= 10 diff --git a/backend/tests/utilities/test_utilities_dupes.py b/backend/tests/utilities/test_utilities_dupes.py new file mode 100644 index 0000000..f23a05f --- /dev/null +++ b/backend/tests/utilities/test_utilities_dupes.py @@ -0,0 +1,234 @@ +import os + +import pytest +from PIL import Image + +from .support import can_link, dupes, group_sets, pattern, put + + +def test_files_with_the_same_bytes_and_different_names_are_one_group(client, tmp_path): + data = pattern(5000, 1) + put(tmp_path / "t" / "alpha.dat", data) + put(tmp_path / "t" / "sub" / "beta.bin", data) + put(tmp_path / "t" / "gamma.txt", data) + result = dupes(client, [tmp_path / "t"]) + assert group_sets(result) == {frozenset({"alpha.dat", "beta.bin", "gamma.txt"})} + assert result["groups"][0]["size"] == 5000 + assert result["groups"][0]["wasted"] == 10000 + assert result["wasted"] == 10000 + + +def test_same_size_but_different_content_is_never_paired(client, tmp_path): + put(tmp_path / "t" / "a.dat", pattern(5000, 1)) + put(tmp_path / "t" / "b.dat", pattern(5000, 2)) + result = dupes(client, [tmp_path / "t"]) + assert result["groups"] == [] + assert result["wasted"] == 0 + + +def test_a_single_changed_byte_in_the_middle_of_a_large_file_is_not_a_duplicate(client, tmp_path): + data = bytearray(pattern(300000, 5)) + other = bytearray(data) + other[150000] ^= 0xFF + put(tmp_path / "t" / "one.big", bytes(data)) + put(tmp_path / "t" / "two.big", bytes(other)) + put(tmp_path / "t" / "three.big", bytes(data)) + assert group_sets(dupes(client, [tmp_path / "t"])) == {frozenset({"one.big", "three.big"})} + + +def test_a_changed_last_byte_is_not_a_duplicate(client, tmp_path): + data = pattern(2000, 9) + put(tmp_path / "t" / "a", data) + put(tmp_path / "t" / "b", data[:-1] + bytes([data[-1] ^ 1])) + assert dupes(client, [tmp_path / "t"])["groups"] == [] + + +def test_two_separate_pairs_make_two_groups_and_wasted_is_their_sum(client, tmp_path): + put(tmp_path / "t" / "p1.a", pattern(1000, 1)) + put(tmp_path / "t" / "p1.b", pattern(1000, 1)) + put(tmp_path / "t" / "q1.a", pattern(3000, 2)) + put(tmp_path / "t" / "q1.b", pattern(3000, 2)) + put(tmp_path / "t" / "unique.c", pattern(3000, 3)) + result = dupes(client, [tmp_path / "t"]) + assert group_sets(result) == {frozenset({"p1.a", "p1.b"}), frozenset({"q1.a", "q1.b"})} + assert [group["wasted"] for group in result["groups"]] == [3000, 1000] + assert result["wasted"] == 4000 + + +def test_a_group_of_four_wastes_three_copies(client, tmp_path): + for name in "abcd": + put(tmp_path / "t" / f"{name}.dat", pattern(800, 4)) + result = dupes(client, [tmp_path / "t"]) + assert result["groups"][0]["wasted"] == 2400 + assert len(result["groups"][0]["files"]) == 4 + + +def test_empty_files_are_ignored_by_default(client, tmp_path): + put(tmp_path / "t" / "e1", b"") + put(tmp_path / "t" / "e2", b"") + assert dupes(client, [tmp_path / "t"])["groups"] == [] + + +def test_min_size_hides_small_duplicates(client, tmp_path): + put(tmp_path / "t" / "s1", pattern(100, 1)) + put(tmp_path / "t" / "s2", pattern(100, 1)) + put(tmp_path / "t" / "l1", pattern(1000, 2)) + put(tmp_path / "t" / "l2", pattern(1000, 2)) + assert group_sets(dupes(client, [tmp_path / "t"], min_size=101)) == {frozenset({"l1", "l2"})} + assert len(dupes(client, [tmp_path / "t"], min_size=0)["groups"]) == 2 + + +def test_not_recursive_looks_only_at_the_top_folder(client, tmp_path): + put(tmp_path / "t" / "top.dat", pattern(500, 1)) + put(tmp_path / "t" / "sub" / "deep.dat", pattern(500, 1)) + put(tmp_path / "t" / "twin.dat", pattern(500, 1)) + assert group_sets(dupes(client, [tmp_path / "t"], recursive=False)) == {frozenset({"top.dat", "twin.dat"})} + assert len(group_sets(dupes(client, [tmp_path / "t"])).pop()) == 3 + + +def test_hidden_files_are_skipped_unless_asked_for(client, tmp_path): + put(tmp_path / "t" / "seen.dat", pattern(500, 1)) + put(tmp_path / "t" / ".hidden.dat", pattern(500, 1)) + put(tmp_path / "t" / ".cache" / "inner.dat", pattern(500, 1)) + assert dupes(client, [tmp_path / "t"])["groups"] == [] + assert group_sets(dupes(client, [tmp_path / "t"], include_hidden=True)) == {frozenset({"seen.dat", ".hidden.dat", "inner.dat"})} + + +def test_duplicates_are_found_across_two_roots(client, tmp_path): + put(tmp_path / "one" / "a.dat", pattern(700, 1)) + put(tmp_path / "two" / "b.dat", pattern(700, 1)) + assert group_sets(dupes(client, [tmp_path / "one", tmp_path / "two"])) == {frozenset({"a.dat", "b.dat"})} + + +def test_a_folder_listed_twice_or_inside_another_root_is_not_scanned_twice(client, tmp_path): + put(tmp_path / "t" / "a.dat", pattern(700, 1)) + put(tmp_path / "t" / "inner" / "b.dat", pattern(700, 2)) + result = dupes(client, [tmp_path / "t", tmp_path / "t" / "inner", tmp_path / "t"]) + assert result["scanned"] == 2 + assert result["groups"] == [] + + +def test_a_symbolic_link_to_a_file_is_not_a_duplicate_of_it(client, tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + put(tmp_path / "t" / "real.dat", pattern(900, 1)) + os.symlink(tmp_path / "t" / "real.dat", tmp_path / "t" / "alias.dat") + result = dupes(client, [tmp_path / "t"]) + assert result["groups"] == [] + assert result["scanned"] == 1 + + +def test_a_link_to_an_identical_file_outside_the_tree_is_not_paired(client, tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + put(tmp_path / "outside" / "same.dat", pattern(900, 1)) + put(tmp_path / "t" / "mine.dat", pattern(900, 1)) + os.symlink(tmp_path / "outside", tmp_path / "t" / "out", target_is_directory=True) + assert dupes(client, [tmp_path / "t"])["groups"] == [] + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX hard links") +def test_hard_links_to_one_file_hold_no_wasted_space(client, tmp_path): + put(tmp_path / "t" / "one.dat", pattern(900, 1)) + os.link(tmp_path / "t" / "one.dat", tmp_path / "t" / "two.dat") + result = dupes(client, [tmp_path / "t"]) + assert result["groups"] == [] + assert result["wasted"] == 0 + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX hard links") +def test_hard_links_of_a_copy_are_listed_with_it_and_the_waste_is_one_file(client, tmp_path): + put(tmp_path / "t" / "one.dat", pattern(900, 1)) + os.link(tmp_path / "t" / "one.dat", tmp_path / "t" / "one-link.dat") + put(tmp_path / "t" / "copy.dat", pattern(900, 1)) + result = dupes(client, [tmp_path / "t"]) + assert len(result["groups"]) == 1 + assert group_sets(result) == {frozenset({"one.dat", "one-link.dat", "copy.dat"})} + assert result["groups"][0]["wasted"] == 900 + + +def test_nothing_is_deleted_or_changed_by_a_scan(client, tmp_path): + for name in ("a", "b"): + put(tmp_path / "t" / name, pattern(600, 1)) + before = {p.name: p.read_bytes() for p in (tmp_path / "t").iterdir()} + dupes(client, [tmp_path / "t"]) + assert {p.name: p.read_bytes() for p in (tmp_path / "t").iterdir()} == before + + +def test_every_listed_file_carries_its_size_and_the_group_key_is_shared_content(client, tmp_path): + put(tmp_path / "t" / "x1", pattern(1234, 1)) + put(tmp_path / "t" / "x2", pattern(1234, 1)) + put(tmp_path / "t" / "y1", pattern(1234, 2)) + put(tmp_path / "t" / "y2", pattern(1234, 2)) + result = dupes(client, [tmp_path / "t"]) + assert len({group["key"] for group in result["groups"]}) == 2 + for group in result["groups"]: + assert all(item["size"] == 1234 for item in group["files"]) + + +def test_a_scan_without_roots_is_refused(client): + reply = client.post("/api/dupes/scan", json={"roots": []}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the request is missing or has a bad value for roots" + + +def test_a_missing_root_is_refused_with_a_message(client, tmp_path): + reply = client.post("/api/dupes/scan", json={"roots": [str(tmp_path / "gone")]}) + assert reply.status_code == 404 + assert reply.json()["error"] == "that folder does not exist" + + +def test_an_unknown_mode_is_refused(client, tmp_path): + reply = client.post("/api/dupes/scan", json={"roots": [str(tmp_path)], "mode": "fuzzy"}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the request is missing or has a bad value for mode" + + +def test_the_dupes_tool_refuses_roots_that_are_not_a_list(client): + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "dupes_scan", "arguments": {"roots": "/tmp"}}}) + result = reply.json()["result"] + assert result["isError"] is True + assert result["content"][0]["text"] == "roots must be a list of folder paths" + + +def gradient(path, size, flip=False): + image = Image.new("RGB", size) + width, height = size + pixels = image.load() + for x in range(width): + for y in range(height): + level = int(255 * (x / (width - 1))) + pixels[x, y] = (255 - level if flip else level, 40, 90) + image.save(path) + + +def blocks(path, size): + image = Image.new("RGB", size, (250, 250, 250)) + for x in range(size[0]): + for y in range(size[1]): + if (x // (size[0] // 4) + y // (size[1] // 4)) % 2 == 0: + image.putpixel((x, y), (10, 10, 10)) + image.save(path) + + +def test_similar_images_pairs_a_picture_with_its_smaller_copy_and_not_with_a_different_one(client, tmp_path): + (tmp_path / "t").mkdir() + gradient(tmp_path / "t" / "big.png", (256, 192)) + gradient(tmp_path / "t" / "small.png", (128, 96)) + blocks(tmp_path / "t" / "checks.png", (128, 96)) + result = dupes(client, [tmp_path / "t"], mode="similar-images") + assert result["mode"] == "similar-images" + assert group_sets(result) == {frozenset({"big.png", "small.png"})} + names = [item["path"].rsplit(os.sep, 1)[-1] for item in result["groups"][0]["files"]] + assert names[0] == "big.png" + assert result["groups"][0]["files"][0]["width"] == 256 + + +def test_similar_images_ignores_files_that_are_not_pictures(client, tmp_path): + (tmp_path / "t").mkdir() + gradient(tmp_path / "t" / "a.png", (64, 48)) + put(tmp_path / "t" / "notes.txt", pattern(500, 1)) + put(tmp_path / "t" / "notes2.txt", pattern(500, 1)) + result = dupes(client, [tmp_path / "t"], mode="similar-images") + assert result["groups"] == [] + assert result["scanned"] == 1 diff --git a/backend/tests/utilities/test_utilities_hosts.py b/backend/tests/utilities/test_utilities_hosts.py new file mode 100644 index 0000000..dbbaf94 --- /dev/null +++ b/backend/tests/utilities/test_utilities_hosts.py @@ -0,0 +1,234 @@ +import hashlib +import os +import re +from ipaddress import ip_address + +import pytest + +from .support import hosts_file # noqa: F401 + +SAMPLE = ( + "# Host database\n" + "127.0.0.1\tlocalhost\n" + "::1 localhost ip6-localhost # loopback v6\n" + "\n" + "#192.168.1.5 printer.lan\n" + "10.0.0.2 db.internal cache.internal\n" + "# just a remark about 10.0.0.9\n" + "not an entry at all\n" +) + + +def independent_entries(text): + found = [] + for number, line in enumerate(text.splitlines(), start=1): + body = line.strip() + enabled = True + if body.startswith("#"): + enabled = False + body = body[1:].strip() + code, _, comment = body.partition("#") + parts = code.split() + if len(parts) < 2: + continue + try: + ip_address(parts[0]) + except ValueError: + continue + if not all(re.fullmatch(r"[A-Za-z0-9.-]+", name) for name in parts[1:]): + continue + found.append((number, enabled, parts[0], parts[1:], comment.strip())) + return found + + +def entry(row): + return {"line": row["line"], "enabled": row["enabled"], "address": row["address"], "names": row["names"], "comment": row["comment"]} + + +def test_a_hosts_file_is_parsed_into_the_entries_the_format_defines(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + body = client.get("/api/hosts").json() + got = [(e["line"], e["enabled"], e["address"], e["names"], e["comment"]) for e in body["entries"]] + assert got == independent_entries(SAMPLE) + assert got[0] == (2, True, "127.0.0.1", ["localhost"], "") + assert got[1] == (3, True, "::1", ["localhost", "ip6-localhost"], "loopback v6") + assert got[2] == (5, False, "192.168.1.5", ["printer.lan"], "") + assert got[3][3] == ["db.internal", "cache.internal"] + + +def test_read_returns_the_raw_text_the_path_and_a_content_version(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + body = client.get("/api/hosts").json() + assert body["raw"] == SAMPLE + assert body["path"] == str(hosts_file) + assert body["version"] == hashlib.sha256(SAMPLE.encode()).hexdigest() + assert body["writable"] is True + + +def test_remarks_and_junk_lines_are_not_entries(client, hosts_file): + hosts_file.write_text("# comment only\nnot an entry\n999.1.1.1 badaddr\n1.2.3.4 -bad-.name\n1.2.3.4\n", encoding="utf-8") + assert client.get("/api/hosts").json()["entries"] == [] + + +def test_a_missing_hosts_file_reads_as_empty(client, hosts_file): + body = client.get("/api/hosts").json() + assert body["entries"] == [] and body["raw"] == "" + + +def test_saving_the_entries_unchanged_writes_nothing_and_makes_no_backup(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + rows = client.get("/api/hosts").json()["entries"] + reply = client.post("/api/hosts", json={"entries": [entry(r) for r in rows]}).json() + assert reply == {"ok": True, "backup": None, "elevated": False, "changed": False} + assert hosts_file.read_text(encoding="utf-8") == SAMPLE + + +def test_editing_one_entry_changes_only_that_line(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[3]["names"] = ["db.internal", "replica.internal"] + reply = client.post("/api/hosts", json={"entries": rows}).json() + assert reply["ok"] is True and reply["changed"] is True + lines = hosts_file.read_text(encoding="utf-8").split("\n") + old = SAMPLE.split("\n") + assert lines[5] == "10.0.0.2\tdb.internal replica.internal" + assert [line for i, line in enumerate(lines) if i != 5] == [line for i, line in enumerate(old) if i != 5] + + +def test_a_saved_file_is_read_back_as_the_same_entries(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[1]["comment"] = "changed note" + rows[2]["enabled"] = True + client.post("/api/hosts", json={"entries": rows}) + back = client.get("/api/hosts").json()["entries"] + assert back[1]["comment"] == "changed note" + assert back[2]["enabled"] is True + assert [(e["address"], e["names"]) for e in back] == [(r["address"], r["names"]) for r in rows] + assert [(n, en, a, nm, c) for n, en, a, nm, c in independent_entries(hosts_file.read_text(encoding="utf-8"))] == [(e["line"], e["enabled"], e["address"], e["names"], e["comment"]) for e in back] + + +def test_a_disabled_entry_is_written_as_a_commented_out_line(client, hosts_file): + hosts_file.write_text("127.0.0.1\tlocalhost\n10.1.1.1\tnas.lan\n", encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[1]["enabled"] = False + client.post("/api/hosts", json={"entries": rows}) + assert hosts_file.read_text(encoding="utf-8") == "127.0.0.1\tlocalhost\n# 10.1.1.1\tnas.lan\n" + + +def test_a_new_entry_is_appended_on_its_own_line(client, hosts_file): + hosts_file.write_text("127.0.0.1\tlocalhost", encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows.append({"address": "10.9.9.9", "names": ["new.example"], "comment": "added", "enabled": True}) + client.post("/api/hosts", json={"entries": rows}) + assert hosts_file.read_text(encoding="utf-8") == "127.0.0.1\tlocalhost\n10.9.9.9\tnew.example # added\n" + + +def test_an_entry_left_out_of_the_save_is_removed_and_everything_else_is_kept(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + client.post("/api/hosts", json={"entries": rows[:1] + rows[2:]}) + assert hosts_file.read_text(encoding="utf-8") == SAMPLE.replace("::1 localhost ip6-localhost # loopback v6\n", "") + + +def test_windows_line_endings_survive_an_edit(client, hosts_file): + original = "127.0.0.1\tlocalhost\r\n# keep me\r\n10.0.0.2\tapp.lan\r\n" + hosts_file.write_bytes(original.encode()) + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[1]["address"] = "10.0.0.3" + rows.append({"address": "10.0.0.4", "names": ["x.lan"], "enabled": True}) + client.post("/api/hosts", json={"entries": rows}) + assert hosts_file.read_bytes() == b"127.0.0.1\tlocalhost\r\n# keep me\r\n10.0.0.3\tapp.lan\r\n10.0.0.4\tx.lan\r\n" + + +def test_a_byte_order_mark_is_kept(client, hosts_file): + hosts_file.write_bytes(b"\xef\xbb\xbf127.0.0.1\tlocalhost\n") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[0]["names"] = ["localhost", "home"] + client.post("/api/hosts", json={"entries": rows}) + assert hosts_file.read_bytes() == b"\xef\xbb\xbf127.0.0.1\tlocalhost home\n" + + +def test_an_indented_entry_keeps_its_indentation_when_edited(client, hosts_file): + hosts_file.write_text(" 10.0.0.1\told.lan\n", encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[0]["names"] = ["new.lan"] + client.post("/api/hosts", json={"entries": rows}) + assert hosts_file.read_text(encoding="utf-8") == " 10.0.0.1\tnew.lan\n" + + +def test_a_backup_of_the_old_content_is_made_before_a_change(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + rows = [entry(r) for r in client.get("/api/hosts").json()["entries"]] + rows[0]["names"] = ["localhost", "me"] + reply = client.post("/api/hosts", json={"entries": rows}).json() + assert os.path.isfile(reply["backup"]) + assert open(reply["backup"], encoding="utf-8").read() == SAMPLE + + +def test_a_save_with_an_old_version_is_refused_and_leaves_the_file_alone(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + body = client.get("/api/hosts").json() + hosts_file.write_text(SAMPLE + "10.5.5.5\tlate.lan\n", encoding="utf-8") + reply = client.post("/api/hosts", json={"entries": [entry(r) for r in body["entries"]], "version": body["version"]}) + assert reply.status_code == 409 + assert reply.json()["error"] == "the hosts file changed since it was read; reload it and try again" + assert hosts_file.read_text(encoding="utf-8") == SAMPLE + "10.5.5.5\tlate.lan\n" + + +def test_a_save_with_the_current_version_goes_through(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + body = client.get("/api/hosts").json() + rows = [entry(r) for r in body["entries"]] + rows[0]["comment"] = "me" + assert client.post("/api/hosts", json={"entries": rows, "version": body["version"]}).json()["changed"] is True + + +@pytest.mark.parametrize( + "bad,message", + [ + ({"address": "300.1.1.1", "names": ["a.lan"]}, "300.1.1.1 is not a valid IPv4 or IPv6 address"), + ({"address": "", "names": ["a.lan"]}, "an empty value is not a valid IPv4 or IPv6 address"), + ({"address": "10.0.0.1", "names": []}, "the entry for 10.0.0.1 needs at least one host name"), + ({"address": "10.0.0.1", "names": ["bad_name"]}, "bad_name is not a valid host name"), + ({"address": "10.0.0.1", "names": ["-lead.lan"]}, "-lead.lan is not a valid host name"), + ({"address": "10.0.0.1", "names": ["a.lan"], "comment": "two\nlines"}, "a comment must stay on one line"), + ], +) +def test_an_invalid_entry_is_refused_with_a_message_and_nothing_is_written(client, hosts_file, bad, message): + hosts_file.write_text(SAMPLE, encoding="utf-8") + reply = client.post("/api/hosts", json={"entries": [bad]}) + assert reply.status_code == 400 + assert reply.json()["error"] == message + assert hosts_file.read_text(encoding="utf-8") == SAMPLE + + +def test_an_entry_pointing_at_a_line_that_is_not_an_entry_is_refused_as_stale(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + reply = client.post("/api/hosts", json={"entries": [{"line": 1, "address": "10.0.0.1", "names": ["a.lan"]}]}) + assert reply.status_code == 400 + assert hosts_file.read_text(encoding="utf-8") == SAMPLE + + +def test_the_same_line_twice_in_one_save_is_refused(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + one = entry(client.get("/api/hosts").json()["entries"][0]) + reply = client.post("/api/hosts", json={"entries": [one, one]}) + assert reply.status_code == 400 + assert reply.json()["error"] == "line 2 appears twice in the request" + + +def test_ipv6_addresses_and_several_names_are_accepted(client, hosts_file): + reply = client.post("/api/hosts", json={"entries": [{"address": "fe80::1", "names": ["a.lan b.lan"], "enabled": True}]}) + assert reply.json()["ok"] is True + assert hosts_file.read_text(encoding="utf-8") == "fe80::1\ta.lan b.lan\n" + + +def test_the_hosts_tool_reads_the_same_entries_as_the_route(client, hosts_file): + hosts_file.write_text(SAMPLE, encoding="utf-8") + import json + + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "hosts_read", "arguments": {}}}) + body = json.loads(reply.json()["result"]["content"][0]["text"]) + assert body["entries"] == client.get("/api/hosts").json()["entries"] + assert body["raw"] == SAMPLE diff --git a/backend/tests/utilities/test_utilities_templates_trash.py b/backend/tests/utilities/test_utilities_templates_trash.py new file mode 100644 index 0000000..3841e09 --- /dev/null +++ b/backend/tests/utilities/test_utilities_templates_trash.py @@ -0,0 +1,183 @@ +import json +import os +import sys +from pathlib import Path + +import pytest + +from .support import put + + +def listed(client): + return {item["name"]: item for item in client.get("/api/templates").json()["templates"]} + + +def test_the_templates_folder_offers_the_starter_items_folders_first(client): + body = client.get("/api/templates").json() + names = [item["name"] for item in body["templates"]] + assert {"Text file.txt", "Markdown note.md", "Data.csv", "Config.json", "Project"} <= set(names) + kinds = [item["kind"] for item in body["templates"]] + assert kinds == sorted(kinds, key=lambda kind: kind != "folder") + assert listed(client)["Project"]["kind"] == "folder" + assert not any(name.startswith(".") for name in names) + + +def test_a_new_file_from_a_template_has_the_template_content(client, tmp_path): + reply = client.post("/api/templates/create", json={"template": "Config.json", "folder": str(tmp_path)}) + assert reply.status_code == 200 + made = Path(reply.json()["path"]) + assert made == tmp_path / "Config.json" + assert json.loads(made.read_text(encoding="utf-8")) == {} + + +def test_a_new_file_is_given_the_template_extension_when_the_name_has_none(client, tmp_path): + made = Path(client.post("/api/templates/create", json={"template": "Markdown note.md", "folder": str(tmp_path), "name": "journal"}).json()["path"]) + assert made.name == "journal.md" + assert made.read_text(encoding="utf-8") == "# Title\n\n" + + +def test_a_taken_name_gets_a_number_and_the_old_file_is_not_overwritten(client, tmp_path): + put(tmp_path / "Data.csv", b"mine,precious\n") + first = Path(client.post("/api/templates/create", json={"template": "Data.csv", "folder": str(tmp_path)}).json()["path"]) + second = Path(client.post("/api/templates/create", json={"template": "Data.csv", "folder": str(tmp_path)}).json()["path"]) + assert (tmp_path / "Data.csv").read_bytes() == b"mine,precious\n" + assert first.name == "Data (2).csv" + assert second.name == "Data (3).csv" + assert first.read_text(encoding="utf-8") == "column1,column2\n" + + +def test_a_folder_template_is_copied_with_everything_in_it(client, tmp_path): + made = Path(client.post("/api/templates/create", json={"template": "Project", "folder": str(tmp_path), "name": "Site"}).json()["path"]) + assert made == tmp_path / "Site" + assert (made / "assets").is_dir() and (made / "exports").is_dir() + assert (made / "README.md").read_text(encoding="utf-8") == "# Project\n\nWhat this project is for.\n" + + +def test_a_taken_folder_name_also_gets_a_number(client, tmp_path): + (tmp_path / "Project").mkdir() + made = Path(client.post("/api/templates/create", json={"template": "Project", "folder": str(tmp_path)}).json()["path"]) + assert made.name == "Project (2)" + assert (tmp_path / "Project").is_dir() and list((tmp_path / "Project").iterdir()) == [] + + +def test_an_unknown_template_is_refused(client, tmp_path): + reply = client.post("/api/templates/create", json={"template": "Nothing here.txt", "folder": str(tmp_path)}) + assert reply.status_code == 404 + assert reply.json()["error"] == "there is no template with that name" + + +def test_a_destination_that_is_not_a_folder_is_refused(client, tmp_path): + reply = client.post("/api/templates/create", json={"template": "Data.csv", "folder": str(tmp_path / "gone")}) + assert reply.status_code == 400 + assert reply.json()["error"] == "the destination folder does not exist" + + +@pytest.mark.parametrize("name", ["../escape", "a/b", "a\\b", "..", "."]) +def test_a_name_that_could_leave_the_folder_is_refused_and_nothing_is_created(client, tmp_path, name): + target = tmp_path / "dest" + target.mkdir() + reply = client.post("/api/templates/create", json={"template": "Data.csv", "folder": str(target), "name": name}) + assert reply.status_code == 400 + assert reply.json()["error"] == "that name cannot be used for a file or folder" + assert list(tmp_path.iterdir()) == [target] and list(target.iterdir()) == [] + + +def test_a_template_name_that_climbs_out_of_the_templates_folder_is_refused(client, tmp_path): + reply = client.post("/api/templates/create", json={"template": "../templates", "folder": str(tmp_path)}) + assert reply.status_code == 400 + + +def test_the_template_tool_lists_and_an_outside_agent_is_not_let_create_without_consent(client, tmp_path): + def call(name, arguments): + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}}) + return reply.json()["result"] + + listing = json.loads(call("templates_list", {})["content"][0]["text"]) + assert "Data.csv" in {item["name"] for item in listing["templates"]} + made = call("template_create", {"template": "Data.csv", "folder": str(tmp_path), "name": "report"}) + assert made["isError"] is True + assert made["content"][0]["text"].startswith("formtools asks the person before an outside agent changes anything") + assert list(tmp_path.iterdir()) == [] + + +def test_files_held_open_name_this_process_as_the_holder(client, tmp_path): + target = put(tmp_path / "held.bin", b"x") + with open(target, "rb"): + body = client.get("/api/files/locks", params={"path": str(target)}).json() + if not body["supported"]: + pytest.skip("this system does not let the process list be read") + assert os.getpid() in {item["pid"] for item in body["holders"]} + + +def test_a_file_nobody_holds_has_no_holders(client, tmp_path): + target = put(tmp_path / "free.bin", b"x") + body = client.get("/api/files/locks", params={"path": str(target)}).json() + assert os.getpid() not in {item["pid"] for item in body["holders"]} + + +def test_lock_lookup_of_a_missing_path_is_refused(client, tmp_path): + reply = client.get("/api/files/locks", params={"path": str(tmp_path / "none")}) + assert reply.status_code == 404 + assert reply.json()["error"] == "that path does not exist" + + +def test_trashing_the_home_folder_is_refused_and_it_stays(client): + home = str(Path.home()) + reply = client.post("/api/files/trash", json={"paths": [home]}).json() + assert reply["trashed"] == 0 + assert reply["errors"] == [{"path": home, "error": "formtools will not trash a drive root or your home folder"}] + assert Path(home).is_dir() + + +def test_trashing_a_drive_root_is_refused(client): + root = os.path.abspath(os.sep) + reply = client.post("/api/files/trash", json={"paths": [root]}).json() + assert reply["trashed"] == 0 + assert reply["errors"][0]["error"] == "formtools will not trash a drive root or your home folder" + + +def test_trashing_a_path_that_does_not_exist_reports_it_and_touches_nothing(client, tmp_path): + keep = put(tmp_path / "keep.txt", b"keep") + gone = str(tmp_path / "gone.txt") + reply = client.post("/api/files/trash", json={"paths": [gone]}).json() + assert reply == {"trashed": 0, "errors": [{"path": gone, "error": "that path does not exist"}]} + assert keep.read_bytes() == b"keep" + + +def test_a_relative_path_is_refused_per_path_and_the_others_are_still_judged(client, tmp_path): + gone = str(tmp_path / "gone.txt") + reply = client.post("/api/files/trash", json={"paths": ["rel/path.txt", gone]}).json() + assert reply["trashed"] == 0 + assert reply["errors"] == [{"path": "rel/path.txt", "error": "the path must be absolute"}, {"path": gone, "error": "that path does not exist"}] + + +def test_trash_with_no_paths_is_refused(client): + assert client.post("/api/files/trash", json={"paths": []}).status_code == 400 + + +def test_more_than_five_thousand_paths_at_once_is_refused(client): + reply = client.post("/api/files/trash", json={"paths": [f"/nope/{n}" for n in range(5001)]}) + assert reply.status_code == 400 + + +def test_a_file_sent_to_the_trash_leaves_its_folder_and_is_recoverable_from_the_trash(client, tmp_path): + import tempfile + from urllib.parse import unquote + + share = Path(os.environ["XDG_DATA_HOME"]) + if sys.platform != "linux" or not str(share).startswith(tempfile.gettempdir()): + pytest.skip("the trash is only exercised where it lies inside the temporary test sandbox") + name = f"victim-{tmp_path.name}.txt" + victim = put(tmp_path / "work" / name, b"recover me") + reply = client.post("/api/files/trash", json={"paths": [str(victim)]}).json() + kept = share / "Trash" / "files" / name + info = share / "Trash" / "info" / f"{name}.trashinfo" + try: + assert reply == {"trashed": 1, "errors": []} + assert not victim.exists() + assert kept.read_bytes() == b"recover me" + recorded = [line for line in info.read_text(encoding="utf-8").splitlines() if line.startswith("Path=")] + assert [unquote(line[5:]) for line in recorded] == [str(victim)] + finally: + kept.unlink(missing_ok=True) + info.unlink(missing_ok=True) diff --git a/backend/tests/utilities/test_utilities_walk_tidy.py b/backend/tests/utilities/test_utilities_walk_tidy.py new file mode 100644 index 0000000..c62c4f0 --- /dev/null +++ b/backend/tests/utilities/test_utilities_walk_tidy.py @@ -0,0 +1,145 @@ +import os + +import pytest +from PIL import Image + +from app.tools.utilities import walk +from .support import can_link, pattern, put, run_job + + +def collected(root, recursive=True, hidden=False): + errors = [] + found = {os.path.relpath(path, root): info.st_size for path, info in walk.walk(str(root), recursive, hidden, lambda p, e: errors.append(p))} + return found, errors + + +def test_walk_yields_every_regular_file_with_its_size(tmp_path): + put(tmp_path / "a.txt", b"x" * 3) + put(tmp_path / "s" / "b.txt", b"y" * 5) + put(tmp_path / "s" / "t" / "c.txt", b"") + found, errors = collected(tmp_path) + assert found == {"a.txt": 3, os.path.join("s", "b.txt"): 5, os.path.join("s", "t", "c.txt"): 0} + assert errors == [] + + +def test_walk_that_is_not_recursive_stays_in_the_top_folder(tmp_path): + put(tmp_path / "a.txt", b"x") + put(tmp_path / "s" / "b.txt", b"y") + assert set(collected(tmp_path, recursive=False)[0]) == {"a.txt"} + + +def test_walk_skips_dot_files_and_dot_folders_unless_hidden_are_wanted(tmp_path): + put(tmp_path / "a.txt", b"x") + put(tmp_path / ".h.txt", b"x") + put(tmp_path / ".git" / "cfg", b"x") + assert set(collected(tmp_path)[0]) == {"a.txt"} + assert set(collected(tmp_path, hidden=True)[0]) == {"a.txt", ".h.txt", os.path.join(".git", "cfg")} + + +def test_walk_skips_links_that_leave_the_tree(tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + put(tmp_path / "out" / "secret.txt", b"s") + put(tmp_path / "t" / "in.txt", b"i") + os.symlink(tmp_path / "out", tmp_path / "t" / "dirlink", target_is_directory=True) + os.symlink(tmp_path / "out" / "secret.txt", tmp_path / "t" / "filelink") + assert set(collected(tmp_path / "t")[0]) == {"in.txt"} + + +def test_walk_reports_a_vanished_folder_to_its_error_callback(tmp_path): + found, errors = collected(tmp_path / "missing") + assert found == {} + assert errors == [str(tmp_path / "missing")] + + +def test_folder_roots_drops_a_root_already_inside_another(tmp_path): + (tmp_path / "t" / "inner").mkdir(parents=True) + kept = walk.folder_roots([str(tmp_path / "t" / "inner"), str(tmp_path / "t")]) + assert kept == [str(tmp_path / "t")] + assert walk.folder_roots([str(tmp_path / "t"), str(tmp_path / "t" / "inner")], recursive=False) == [str(tmp_path / "t"), str(tmp_path / "t" / "inner")] + + +def test_folder_roots_refuses_a_list_with_nothing_in_it(): + from app.core.errors import ApiError + + with pytest.raises(ApiError) as caught: + walk.folder_roots([]) + assert caught.value.message == "at least one folder is needed" + + +def png_bytes(width=16, height=16): + from io import BytesIO + + buffer = BytesIO() + Image.new("RGB", (width, height), (200, 30, 30)).save(buffer, "PNG") + return buffer.getvalue() + + +def test_empty_folders_are_listed_with_the_top_most_ones_marked(client, tmp_path): + for name in ("t/empty1", "t/chain/a/b", "t/full/inner"): + (tmp_path / name).mkdir(parents=True) + put(tmp_path / "t" / "full" / "file.txt", b"x") + job = run_job(client, "/api/files/empty-folders", {"root": str(tmp_path / "t")}) + assert job["state"] == "done" + top = tmp_path / "t" + assert job["result"]["folders"] == sorted(str(top / name) for name in ("chain", "chain/a", "chain/a/b", "empty1", "full/inner")) + assert job["result"]["top"] == sorted(str(top / name) for name in ("chain", "empty1", "full/inner")) + + +def test_a_folder_holding_only_an_empty_file_is_not_empty(client, tmp_path): + put(tmp_path / "t" / "d" / "zero.dat", b"") + job = run_job(client, "/api/files/empty-folders", {"root": str(tmp_path / "t")}) + assert job["result"]["folders"] == [] + + +def test_the_root_itself_is_never_listed_as_empty(client, tmp_path): + (tmp_path / "t").mkdir() + assert run_job(client, "/api/files/empty-folders", {"root": str(tmp_path / "t")})["result"]["folders"] == [] + + +def test_empty_folder_search_never_removes_anything(client, tmp_path): + (tmp_path / "t" / "e").mkdir(parents=True) + run_job(client, "/api/files/empty-folders", {"root": str(tmp_path / "t")}) + assert (tmp_path / "t" / "e").is_dir() + + +def test_a_folder_holding_only_a_link_is_not_empty_and_is_not_followed(client, tmp_path): + if not can_link(tmp_path): + pytest.skip("this system does not allow symbolic links here") + (tmp_path / "t" / "d").mkdir(parents=True) + (tmp_path / "far").mkdir() + os.symlink(tmp_path / "far", tmp_path / "t" / "d" / "to-far", target_is_directory=True) + job = run_job(client, "/api/files/empty-folders", {"root": str(tmp_path / "t")}) + assert job["result"]["folders"] == [] + + +def test_empty_folder_search_of_a_missing_folder_is_refused(client, tmp_path): + reply = client.post("/api/files/empty-folders", json={"root": str(tmp_path / "none")}) + assert reply.status_code == 404 + assert reply.json()["error"] == "that folder does not exist" + + +def test_a_truncated_picture_is_reported_broken_and_a_sound_one_is_not(client, tmp_path): + good = png_bytes() + put(tmp_path / "t" / "good.png", good) + put(tmp_path / "t" / "bad.png", good[: len(good) // 2]) + put(tmp_path / "t" / "notes.txt", b"plain") + job = run_job(client, "/api/files/broken", {"root": str(tmp_path / "t")}) + assert job["state"] == "done" + assert [os.path.basename(item["path"]) for item in job["result"]["items"]] == ["bad.png"] + assert job["result"]["items"][0]["type"] == "image" + assert job["result"]["items"][0]["error"] + + +def test_a_picture_with_junk_inside_is_reported_broken(client, tmp_path): + put(tmp_path / "t" / "junk.jpg", b"this is not a jpeg at all" * 20) + items = run_job(client, "/api/files/broken", {"root": str(tmp_path / "t")})["result"]["items"] + assert [os.path.basename(item["path"]) for item in items] == ["junk.jpg"] + + +def test_a_folder_of_sound_pictures_has_nothing_broken(client, tmp_path): + for name in ("a.png", "b.png"): + put(tmp_path / "t" / name, png_bytes()) + result = run_job(client, "/api/files/broken", {"root": str(tmp_path / "t")})["result"] + assert result["items"] == [] + assert result["checked"] >= 2 diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..e9ca713 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,59 @@ +# Testing formtools + +formtools' tests run the app and check what a user or a calling program would notice. This page says how to run them, where they live and what a test must do to be accepted. + +## Running the tests + +```sh +./formtools test # every layer +./formtools test engine # one layer: unit or engine +./formtools test engine -k rename # the rest of the line goes to the runner +``` + +On Windows use `formtools.bat test`. Run `./formtools install` first. The engine tests need pytest and httpx in the backend venv, which the install does not add: + +```sh +backend/venv/bin/python -m pip install pytest httpx +``` + +## The layers + +| Layer | Tool | Where | What it runs against | +| --- | --- | --- | --- | +| unit | vitest, happy-dom | `frontend/tests/unit/` | exported interface functions and stores, no browser | +| engine | pytest | `backend/tests/` | the real FastAPI app in process, and the engine's public functions | + +The tests are grouped by area, one folder for each: `backend/tests//` (a package with its own `__init__.py`) and `frontend/tests/unit//`. The test files directly in `backend/tests/` are the older ones and run in the same layer. + +## What the shared base gives a test + +`backend/tests/conftest.py` holds the fixtures every engine test can use, next to pytest's own `tmp_path`. A test that writes files writes them under `tmp_path`, never into the repository or the person's folders. + +## The five rules + +1. The test runs the app through a public surface: an HTTP route, a command through the command runner, an MCP tool, a worker request, an exported interface function, or the visible interface in a browser. +2. It checks a result a user or a calling program would notice: geometry, a number, a saved or exported file, a refusal, an undo, something on screen. +3. Its expected value comes from outside the code under test: mathematics, the rules of a file format checked by an independent reader, the manual and the format documents in `docs/`, an invariant (undo then redo, save then open, export then import), two independent paths that must agree, or a fixture that states its own content. +4. It can fail. Change the expected value once, see the test fail, and change it back. +5. Its name says the behaviour in plain words. + +Not accepted: + +- reading source files to check text, spelling, comments or formatting; +- checks that a file, function, class or route merely exists; +- a check of the status code alone, with nothing checked in the answer; +- snapshot files made by running the code and saving what came out; +- replacing the thing under test with a stand-in and testing the stand-in; +- a skip or an expected failure without a written reason. + +## When a test shows the app is wrong + +Do not bend the test. Keep it and mark it as a strict expected failure with a reason that starts with `DEFECT:` and says what the app does, what it should do and where that is stated. `git grep -n "DEFECT:" backend/tests frontend/tests` lists the known ones. When the app is fixed, the strict mark makes the test fail until the mark is removed, so a fix cannot go unnoticed. + +## Changing behaviour + +A change in behaviour updates its tests in the same pull request. New test data is made by hand or by formtools itself; no third-party picture, font or model is added for a test. + +## CI + +Every pull request runs one job, `test`, on Linux. It installs the engine and the frontend the way the other jobs do, then runs the two layers one step each, so the step that fails names the layer. The tests do not run on macOS or Windows in CI. diff --git a/formtools b/formtools index 7d42925..422ebf7 100755 --- a/formtools +++ b/formtools @@ -30,6 +30,7 @@ usage: ./formtools [command] [options] agents sync | check write agents/manifest.json and mirror .claude/skills into .agents/skills; check the manifest, the mirror, the skills and the MCP configs (needs the backend venv) mcpb check | build DIR validate the Claude Desktop extension manifest; write formtools.mcpb into DIR sparkle fail if the banned three-star sparkle icon is back in the app + test [unit|engine] [args] run the tests (nothing or all runs every layer; the rest goes to the runner) doctor check the toolchain, installs and ports clean [--all] remove build output (--all also venv and node_modules) version the version and build (also --version) @@ -67,6 +68,7 @@ case "$cmd" in *) usage; exit 2 ;; esac ;; sparkle) exec python3 setup/sparkle.py --check ;; + test) exec setup/test "$@" ;; doctor) exec setup/doctor "$@" ;; clean) exec setup/clean "$@" ;; version|--version|-V) diff --git a/formtools.bat b/formtools.bat index a83309e..5ea8c3e 100644 --- a/formtools.bat +++ b/formtools.bat @@ -22,6 +22,7 @@ if /i "%CMD%"=="cli" ( call :cli %* & goto :eof ) if /i "%CMD%"=="agents" ( call :agents %* & goto :eof ) if /i "%CMD%"=="mcpb" ( call :mcpb %* & goto :eof ) if /i "%CMD%"=="sparkle" ( python setup\sparkle.py --check & goto :eof ) +if /i "%CMD%"=="test" ( call setup\test.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :eof ) if /i "%CMD%"=="doctor" ( call setup\doctor.bat & goto :eof ) if /i "%CMD%"=="clean" ( call setup\clean.bat %ARG% & goto :eof ) if /i "%CMD%"=="version" ( call :version & goto :eof ) @@ -67,5 +68,5 @@ exit /b 0 :usage echo formtools.bat [command] echo boot ^| install [--lite] ^| install-desktop ^| backend ^| frontend ^| build ^| serve ^| freeze -echo desktop dev ^| desktop build [--config F] [--target T] ^| mcp ^| cli ^| agents install^|sync^|check ^| mcpb check^|build DIR ^| sparkle ^| doctor ^| clean [--all] ^| version ^| help +echo desktop dev ^| desktop build [--config F] [--target T] ^| mcp ^| cli ^| agents install^|sync^|check ^| mcpb check^|build DIR ^| sparkle ^| test [unit^|engine] ^| doctor ^| clean [--all] ^| version ^| help exit /b 0 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 89d9c69..3dc0da8 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formtools", - "version": "0.13.0", + "version": "0.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formtools", - "version": "0.13.0", + "version": "0.14.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", @@ -24,8 +24,10 @@ "@tauri-apps/cli": "2.12.4", "@types/markdown-it": "14.2.0", "@types/three": "0.187.0", + "happy-dom": "21.0.4", "typescript": "7.0.2", - "vite": "8.3.5" + "vite": "8.3.5", + "vitest": "5.0.5" }, "engines": { "node": ">=20.19" @@ -56,6 +58,34 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@napi-rs/canvas": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.1.0.tgz", @@ -821,6 +851,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/linkify-it": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", @@ -846,6 +901,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, "node_modules/@types/stats.js": { "version": "0.17.4", "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", @@ -875,6 +940,23 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -1215,6 +1297,44 @@ "node": ">=16.20.0" } }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xterm/addon-fit": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", @@ -1246,6 +1366,39 @@ ], "license": "PSF-2.0" }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1268,6 +1421,33 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -1308,6 +1488,38 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/happy-dom": { + "version": "21.0.4", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz", + "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/happy-dom/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/highlight.js": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz", @@ -1597,6 +1809,16 @@ "uc.micro": "^3.0.0" } }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, "node_modules/markdown-it": { "version": "15.0.3", "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", @@ -1656,6 +1878,20 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/pdfjs-dist": { "version": "6.5.438", "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", @@ -1770,12 +2006,39 @@ "node": ">=0.10.0" } }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, "node_modules/three": { "version": "0.187.0", "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", "license": "MIT" }, + "node_modules/tinybench": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", + "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -1834,6 +2097,13 @@ "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", "license": "MIT" }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "8.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", @@ -1911,6 +2181,134 @@ "optional": true } } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } } } } diff --git a/frontend/package.json b/frontend/package.json index a37d95f..d2c40c3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "formtools", - "version": "0.13.0", + "version": "0.14.0", "description": "Viewers, batch image tools and file utilities for the Form family", "license": "Apache-2.0", "private": true, @@ -32,7 +32,9 @@ "@tauri-apps/cli": "2.12.4", "@types/markdown-it": "14.2.0", "@types/three": "0.187.0", + "happy-dom": "21.0.4", "typescript": "7.0.2", - "vite": "8.3.5" + "vite": "8.3.5", + "vitest": "5.0.5" } } diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 2816c07..bc75a42 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.13.0'; +export const VERSION = '0.14.0'; diff --git a/frontend/tests/unit/docview/helpers.ts b/frontend/tests/unit/docview/helpers.ts new file mode 100644 index 0000000..b604079 --- /dev/null +++ b/frontend/tests/unit/docview/helpers.ts @@ -0,0 +1,52 @@ +import { vi } from 'vitest'; +import type { Entry } from '../../../src/io/api'; +import type { DocDeps } from '../../../src/ui/docview/types'; + +export function entry(path: string, type: string, size = 0): Entry { + const name = path.split('/').pop() ?? path; + const dot = name.lastIndexOf('.'); + return { name, path, kind: 'file', ext: dot >= 0 ? name.slice(dot + 1).toLowerCase() : '', size, mtime: 0, type: type as Entry['type'] }; +} + +export function deps(): DocDeps & { said: string[] } { + const said: string[] = []; + return { said, status: (t: string) => { said.push(t); }, jobs: { track: () => undefined }, openInViewer: () => undefined }; +} + +export interface Routes { + text?: Record; + csv?: Record; + raw?: Uint8Array; +} + +export function stubEngine(routes: Routes): string[] { + const seen: string[] = []; + if (typeof (globalThis as { CSS?: unknown }).CSS === 'undefined') vi.stubGlobal('CSS', {}); + const proto = Element.prototype as unknown as { scrollIntoView?: () => void }; + if (typeof proto.scrollIntoView !== 'function') proto.scrollIntoView = () => undefined; + vi.stubGlobal('fetch', async (input: unknown, init?: RequestInit): Promise => { + const url = String(input); + seen.push(url); + const json = (body: unknown, status = 200): Response => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + if (url.startsWith('/api/text?') && routes.text) return json(routes.text); + if (url.startsWith('/api/data/csv?') && routes.csv) return json(routes.csv); + if (url.startsWith('/api/file/raw?') && routes.raw) { + const range = new Headers(init?.headers).get('Range') ?? ''; + const m = /bytes=(\d+)-(\d+)/.exec(range); + const a = m ? Number(m[1]) : 0, b = m ? Number(m[2]) + 1 : routes.raw.length; + return new Response(routes.raw.slice(a, b), { status: m ? 206 : 200 }); + } + return json({ ok: false, error: 'No such thing here.' }, 404); + }); + return seen; +} + +export const textDoc = (text: string, language: string | null = null, extra: Record = {}): Record => ({ + encoding: 'utf-8', bom: false, eol: 'lf', lines: text.split('\n').length, text, truncated: false, language, ...extra, +}); + +export async function settle(): Promise { + for (let i = 0; i < 4; i++) await new Promise((r) => setTimeout(r, 5)); +} + +export const txt = (root: ParentNode, sel: string): string => root.querySelector(sel)?.textContent ?? ''; diff --git a/frontend/tests/unit/docview/hex-md.test.ts b/frontend/tests/unit/docview/hex-md.test.ts new file mode 100644 index 0000000..af18469 --- /dev/null +++ b/frontend/tests/unit/docview/hex-md.test.ts @@ -0,0 +1,158 @@ +import { describe, it, expect } from 'vitest'; +import { HexView } from '../../../src/ui/docview/hex'; +import { MarkdownView } from '../../../src/ui/docview/markdown'; +import { deps, entry, settle, stubEngine, textDoc, txt } from './helpers'; + +function refHex(bytes: Uint8Array, off: number): { off: string; hex: string; asc: string } { + const slice = Array.from(bytes.slice(off, off + 16)); + const cells = Array.from({ length: 16 }, (_, k) => (k < slice.length ? slice[k].toString(16).padStart(2, '0') : ' ')); + return { + off: off.toString(16).toUpperCase().padStart(8, '0'), + hex: cells.slice(0, 8).join(' ') + ' ' + cells.slice(8).join(' '), + asc: slice.map((b) => (b >= 32 && b <= 126 ? String.fromCharCode(b) : '.')).join(''), + }; +} + +async function openHex(bytes: Uint8Array): Promise<{ v: HexView; said: string[]; seen: string[] }> { + const seen = stubEngine({ raw: bytes }); + const d = deps(); + const v = new HexView(d); + document.body.appendChild(v.root); + await v.open(entry('/w/blob.bin', 'other', bytes.length)); + await settle(); + return { v, said: d.said, seen }; +} + +const hexRows = (v: HexView): Array<{ off: string; hex: string; asc: string }> => + Array.from(v.root.querySelectorAll('.dv-hex-row')).map((r) => ({ off: r.children[0].textContent ?? '', hex: r.children[1].textContent ?? '', asc: r.children[2].textContent ?? '' })); + +function goTo(v: HexView, s: string): void { + const box = v.root.querySelector('.dv-goto'); + if (!box) throw new Error('no goto'); + box.value = s; + v.root.querySelector('[data-h="go"]')?.click(); +} + +const BYTES = new Uint8Array([0x48, 0x69, 0x21, 0x0a, 0x00, 0x7f, 0x20, 0x7e, 0x80, 0xff, 0x41, 0x42, 0x43, 0x09, 0x0d, 0x31, 0xde, 0xad, 0xbe, 0xef]); + +describe('hex viewer', () => { + it('shows offsets, bytes and printable text that match the input for every row', async () => { + const { v } = await openHex(BYTES); + expect(hexRows(v)).toEqual([refHex(BYTES, 0), refHex(BYTES, 16)]); + }); + it('writes the first row exactly in the classic 8 plus 8 layout', async () => { + const { v } = await openHex(BYTES); + expect(hexRows(v)[0]).toEqual({ off: '00000000', hex: '48 69 21 0a 00 7f 20 7e 80 ff 41 42 43 09 0d 31', asc: 'Hi!... ~..ABC..1' }); + }); + it('shows only the remaining bytes on a short last row', async () => { + const { v } = await openHex(BYTES); + const last = hexRows(v)[1]; + expect(last.off).toBe('00000010'); + expect(last.hex.trim()).toBe('de ad be ef'); + expect(last.asc).toBe('....'); + }); + it('fetches a small file in one single read', async () => { + const { seen } = await openHex(BYTES); + expect(seen.filter((u) => u.startsWith('/api/file/raw?')).length).toBe(1); + }); + it('labels the header columns with the sixteen column offsets', async () => { + const { v } = await openHex(BYTES); + expect(txt(v.root, '.dv-hexhead .dv-hx-hex')).toBe('00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f'); + }); + it('reports the size in short and exact form', async () => { + const { v } = await openHex(BYTES); + expect(txt(v.root, '.dv-info')).toBe('20 B \u00b7 20 bytes'); + }); + it('gives one row per sixteen bytes, rounding up', async () => { + const bytes = new Uint8Array(33).map((_, i) => i); + const { v } = await openHex(bytes); + expect(hexRows(v).map((r) => r.off)).toEqual(['00000000', '00000010', '00000020']); + expect(hexRows(v)[2]).toEqual(refHex(bytes, 32)); + }); + it('says an empty file is empty and draws no rows', async () => { + const { v } = await openHex(new Uint8Array(0)); + expect(txt(v.root, '.dv-note')).toBe('The file is empty.'); + expect(hexRows(v).length).toBe(0); + }); + it('jumps to the row holding an offset given as 0x hex, h suffix or decimal', async () => { + const bytes = new Uint8Array(160); + const { v } = await openHex(bytes); + const sc = v.root.querySelector('.dv-hexscroll') as HTMLElement; + goTo(v, '0x20'); + expect(sc.scrollTop).toBe(2 * 20); + goTo(v, '50h'); + expect(sc.scrollTop).toBe(5 * 20); + goTo(v, '17'); + expect(sc.scrollTop).toBe(1 * 20); + }); + it('refuses an offset past the end of the file or unreadable text', async () => { + const { v, said } = await openHex(BYTES); + goTo(v, '20'); + goTo(v, 'zz'); + expect(said).toEqual(['That offset is outside the file.', 'That offset is outside the file.']); + }); +}); + +async function openMd(text: string, path = '/docs/readme.md', extra: Record = {}): Promise { + stubEngine({ text: textDoc(text, 'markdown', extra) }); + const v = new MarkdownView(deps()); + document.body.appendChild(v.root); + await v.open(entry(path, 'text')); + await settle(); + return v; +} + +const article = (v: MarkdownView): HTMLElement => v.root.querySelector('.dv-md') as HTMLElement; + +describe('markdown viewer', () => { + it('renders headings, emphasis and lists as elements', async () => { + const v = await openMd('# Title\n\nSome *soft* text.\n\n- one\n- two\n'); + const a = article(v); + expect(a.querySelector('h1')?.textContent).toBe('Title'); + expect(a.querySelector('em')?.textContent).toBe('soft'); + expect(Array.from(a.querySelectorAll('li')).map((n) => n.textContent)).toEqual(['one', 'two']); + }); + it('never inserts or runs a script block written in the file', async () => { + const v = await openMd('Hello\n\n\n'); + expect(article(v).querySelector('script')).toBeNull(); + expect(article(v).textContent).toContain(''); + expect((window as unknown as { __ftmd?: number }).__ftmd).toBeUndefined(); + }); + it('shows raw HTML tags with event handlers as text instead of live elements', async () => { + const v = await openMd(' '); + expect(article(v).querySelector('img')).toBeNull(); + expect(article(v).querySelector('iframe')).toBeNull(); + expect(article(v).querySelector('[onerror]')).toBeNull(); + }); + it('does not turn a javascript: link into a live link', async () => { + const v = await openMd('[click](javascript:alert(1))'); + for (const a of Array.from(article(v).querySelectorAll('a'))) expect(a.getAttribute('href') ?? '').not.toMatch(/^javascript:/i); + }); + it('loads a relative image from the folder of the markdown file', async () => { + const v = await openMd('![pic](img/a.png) ![up](../up.png)'); + const imgs = Array.from(article(v).querySelectorAll('img')); + expect(imgs.map((i) => i.getAttribute('src'))).toEqual([ + `/api/file/raw?path=${encodeURIComponent('/docs/img/a.png')}&v=0`, + `/api/file/raw?path=${encodeURIComponent('/up.png')}&v=0`, + ]); + expect(imgs.map((i) => i.alt)).toEqual(['pic', 'up']); + }); + it('shows the alt text instead of fetching a remote image', async () => { + const v = await openMd('![remote logo](https://example.com/a.png)'); + expect(article(v).querySelector('img')).toBeNull(); + expect(txt(article(v), '.dv-md-noimg')).toBe('remote logo'); + }); + it('switches to the source lines and back with the mode buttons', async () => { + const v = await openMd('# A\nb'); + const scroll = v.root.querySelector('.dv-md-scroll') as HTMLElement; + v.root.querySelector('[data-m="source"]')?.click(); + expect(scroll.hidden).toBe(true); + expect(Array.from(v.root.querySelectorAll('.dv-ln')).map((n) => n.textContent)).toEqual(['# A', 'b']); + v.root.querySelector('[data-m="rendered"]')?.click(); + expect(scroll.hidden).toBe(false); + }); + it('notes when only the first 2 MB of a long file is rendered', async () => { + const v = await openMd('x', '/docs/readme.md', { truncated: true }); + expect(txt(v.root, '.dv-bar .dv-note')).toBe('The file is longer than the first 2 MB, which is what is shown.'); + }); +}); diff --git a/frontend/tests/unit/docview/model-load.test.ts b/frontend/tests/unit/docview/model-load.test.ts new file mode 100644 index 0000000..2820079 --- /dev/null +++ b/frontend/tests/unit/docview/model-load.test.ts @@ -0,0 +1,94 @@ +import { describe, it, expect, vi } from 'vitest'; +import { Box3, BufferGeometry, Mesh, Vector3 } from 'three'; +import { loadModel } from '../../../src/ui/model/loaders'; + +function serve(routes: Record): void { + vi.stubGlobal('fetch', async (input: unknown): Promise => { + const url = String(input); + for (const [prefix, body] of Object.entries(routes)) { + if (url.startsWith(prefix)) return new Response(typeof body === 'string' ? new TextEncoder().encode(body) : body, { status: 200 }); + } + return new Response(JSON.stringify({ ok: false, error: 'The engine cannot convert this.' }), { status: 404, headers: { 'Content-Type': 'application/json' } }); + }); +} + +function binaryStl(tris: number[][][]): Uint8Array { + const buf = new ArrayBuffer(84 + 50 * tris.length); + const dv = new DataView(buf); + dv.setUint32(80, tris.length, true); + tris.forEach((t, i) => { + const o = 84 + 50 * i; + t.forEach((p, k) => p.forEach((c, j) => dv.setFloat32(o + 12 + k * 12 + j * 4, c, true))); + }); + return new Uint8Array(buf); +} + +const box = (o: import('three').Object3D): Box3 => new Box3().setFromObject(o); +const arr = (v: Vector3): number[] => v.toArray().map((x) => Math.round(x * 1e6) / 1e6); +const signal = (): AbortSignal => new AbortController().signal; + +const CUBE_OBJ = [ + 'v -1 -2 -3', 'v 1 -2 -3', 'v 1 2 -3', 'v -1 2 -3', 'v -1 -2 3', 'v 1 -2 3', 'v 1 2 3', 'v -1 2 3', + 'f 1 2 3 4', 'f 5 6 7 8', 'f 1 2 6 5', 'f 2 3 7 6', 'f 3 4 8 7', 'f 4 1 5 8', +].join('\n'); + +describe('model loading and bounds', () => { + it('reads an ASCII STL triangle and bounds it by its three corners', async () => { + serve({ '/api/file/raw?': 'solid t\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 2 0 0\nvertex 0 3 0\nendloop\nendfacet\nendsolid t\n' }); + const out = await loadModel('stl', '/w/t.stl', 0, signal()); + const b = box(out.object); + expect(arr(b.min)).toEqual([0, 0, 0]); + expect(arr(b.max)).toEqual([2, 3, 0]); + }); + it('reads a binary STL written by hand and bounds both triangles together', async () => { + serve({ '/api/file/raw?': binaryStl([[[0, 0, 0], [1, 0, 0], [0, 1, 0]], [[-4, 5, 6], [7, -8, 9], [0, 0, -10]]]) }); + const out = await loadModel('stl', '/w/t.stl', 0, signal()); + const b = box(out.object); + expect(arr(b.min)).toEqual([-4, -8, -10]); + expect(arr(b.max)).toEqual([7, 5, 9]); + const g = (out.object as Mesh).geometry as BufferGeometry; + expect(g.getAttribute('position').count).toBe(6); + }); + it('bounds an OBJ box by its extreme vertices and centres it on the origin', async () => { + serve({ '/api/file/raw?': CUBE_OBJ }); + const out = await loadModel('obj', '/w/c.obj', 0, signal()); + const b = box(out.object); + expect(arr(b.min)).toEqual([-1, -2, -3]); + expect(arr(b.max)).toEqual([1, 2, 3]); + expect(arr(b.getCenter(new Vector3()))).toEqual([0, 0, 0]); + expect(arr(b.getSize(new Vector3()))).toEqual([2, 4, 6]); + }); + it('gives a bounding sphere radius of half the box diagonal for a centred box', async () => { + serve({ '/api/file/raw?': CUBE_OBJ }); + const out = await loadModel('obj', '/w/c.obj', 0, signal()); + let mesh: Mesh | null = null; + out.object.traverse((o) => { if ((o as Mesh).isMesh) mesh = o as Mesh; }); + expect(mesh).not.toBeNull(); + const g = (mesh as unknown as Mesh).geometry; + g.computeBoundingSphere(); + expect(g.boundingSphere?.radius).toBeCloseTo(Math.sqrt(1 + 4 + 9), 6); + }); + it('adds face normals to a mesh that has none, pointing out of the counter-clockwise face', async () => { + serve({ '/api/file/raw?': 'v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n' }); + const out = await loadModel('obj', '/w/t.obj', 0, signal()); + let mesh: Mesh | null = null; + out.object.traverse((o) => { if ((o as Mesh).isMesh) mesh = o as Mesh; }); + const n = (mesh as unknown as Mesh).geometry.getAttribute('normal'); + expect(n).toBeDefined(); + for (let i = 0; i < n.count; i++) expect([n.getX(i), n.getY(i), n.getZ(i)].map((x) => Math.round(x))).toEqual([0, 0, 1]); + }); + it('passes on the engine refusal when a format is neither native nor convertible', async () => { + serve({}); + await expect(loadModel('xyz', '/w/a.xyz', 0, signal())).rejects.toThrow('The engine cannot convert this.'); + }); + it('stops at once when the load was cancelled', async () => { + serve({ '/api/file/raw?': CUBE_OBJ }); + const c = new AbortController(); + c.abort(); + vi.stubGlobal('fetch', async (_u: unknown, init?: RequestInit): Promise => { + if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError'); + return new Response(CUBE_OBJ); + }); + await expect(loadModel('obj', '/w/c.obj', 0, c.signal)).rejects.toThrow(); + }); +}); diff --git a/frontend/tests/unit/docview/pure.test.ts b/frontend/tests/unit/docview/pure.test.ts new file mode 100644 index 0000000..e9cc923 --- /dev/null +++ b/frontend/tests/unit/docview/pure.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect } from 'vitest'; +import { Group, Mesh, BoxGeometry, MeshBasicMaterial } from 'three'; +import { fmtBytes, fmtInt, baseName, dirName, Seq, errText } from '../../../src/ui/docview/common'; +import { splitHighlighted, ensureLanguage } from '../../../src/ui/docview/highlight'; +import { docKindOf, docHandles } from '../../../src/ui/docview/index'; +import { VirtualList } from '../../../src/ui/docview/vlist'; +import { VGrid } from '../../../src/ui/docview/grid'; +import { BLOCKS } from '../../../src/ui/docview/blocks'; +import { zUpByDefault, NATIVE } from '../../../src/ui/model/loaders'; +import { disposeTree } from '../../../src/ui/model/engine'; +import { entry } from './helpers'; + +describe('byte and number formatting', () => { + it('shows sizes under 1024 as whole bytes', () => { + expect(fmtBytes(0)).toBe('0 B'); + expect(fmtBytes(1023)).toBe('1023 B'); + }); + it('shows 1024 bytes as 1.0 KB and 1536 as 1.5 KB', () => { + expect(fmtBytes(1024)).toBe('1.0 KB'); + expect(fmtBytes(1536)).toBe('1.5 KB'); + }); + it('shows 2 to the 20 bytes as 1.0 MB and 2 to the 30 as 1.0 GB', () => { + expect(fmtBytes(2 ** 20)).toBe('1.0 MB'); + expect(fmtBytes(2 ** 30)).toBe('1.0 GB'); + }); + it('drops the decimal from 100 units upward', () => { + expect(fmtBytes(100 * 2 ** 20)).toBe('100 MB'); + }); + it('shows nothing for a negative or non-finite size', () => { + expect(fmtBytes(-1)).toBe(''); + expect(fmtBytes(Number.NaN)).toBe(''); + }); + it('groups thousands with commas whatever the machine locale', () => { + expect(fmtInt(1234567)).toBe('1,234,567'); + expect(fmtInt(999)).toBe('999'); + }); +}); + +describe('path helpers', () => { + it('takes the last segment as the base name for both slash kinds', () => { + expect(baseName('/a/b/c.txt')).toBe('c.txt'); + expect(baseName('C:\\x\\y.bin')).toBe('y.bin'); + }); + it('takes the parent folder as the directory name', () => { + expect(dirName('/a/b/c.txt')).toBe('/a/b'); + expect(dirName('C:\\x\\y.bin')).toBe('C:\\x'); + }); + it('gives the root for a file directly under the root', () => { + expect(dirName('/c.txt')).toBe('/'); + }); + it('uses the message of an Error and a plain sentence for anything else', () => { + expect(errText(new Error('Disk gone.'))).toBe('Disk gone.'); + expect(errText(42)).toBe('Something went wrong.'); + }); + it('a sequence token is current only until the next one is taken', () => { + const s = new Seq(); + const a = s.next(); + expect(s.is(a)).toBe(true); + const b = s.next(); + expect(s.is(a)).toBe(false); + expect(s.is(b)).toBe(true); + s.bump(); + expect(s.is(b)).toBe(false); + }); +}); + +describe('highlight line splitting', () => { + const strip = (h: string): string => h.replace(/<[^>]+>/g, ''); + it('closes and reopens a span that crosses a line break', () => { + expect(splitHighlighted('x\nyz')).toEqual(['x', 'yz']); + }); + it('keeps the visible text of every line the same as splitting the plain text', () => { + const html = 'ab\nc\nde\nf'; + expect(splitHighlighted(html).map(strip)).toEqual(strip(html).split('\n')); + }); + it('leaves every produced line with balanced span tags', () => { + for (const line of splitHighlighted('1\n2\n3\n45')) { + expect((line.match(//g) ?? []).length); + } + }); + it('resolves short language names to their full name and refuses unknown ones', async () => { + expect(await ensureLanguage('py')).toBe('python'); + expect(await ensureLanguage('HTML')).toBe('xml'); + expect(await ensureLanguage('klingon')).toBeNull(); + expect(await ensureLanguage(null)).toBeNull(); + }); +}); + +describe('which viewer opens a file', () => { + it('opens md as markdown, csv and tsv as a table, json and jsonl as data', () => { + expect(docKindOf(entry('/a/readme.md', 'text'))).toBe('markdown'); + expect(docKindOf(entry('/a/t.csv', 'text'))).toBe('csv'); + expect(docKindOf(entry('/a/t.tsv', 'text'))).toBe('csv'); + expect(docKindOf(entry('/a/d.json', 'text'))).toBe('json'); + expect(docKindOf(entry('/a/d.jsonl', 'text'))).toBe('json'); + }); + it('opens a database file as sqlite, plain text as text and unknown bytes as hex', () => { + expect(docKindOf(entry('/a/x.sqlite', 'other'))).toBe('sqlite'); + expect(docKindOf(entry('/a/x.log', 'text'))).toBe('text'); + expect(docKindOf(entry('/a/x.bin', 'other'))).toBe('hex'); + }); + it('lets the pdf, font and archive types win over the extension', () => { + expect(docKindOf(entry('/a/x.json', 'pdf'))).toBe('pdf'); + expect(docKindOf(entry('/a/x.md', 'font'))).toBe('font'); + expect(docKindOf(entry('/a/x.csv', 'archive'))).toBe('archive'); + }); + it('does not handle folders or unknown binary files', () => { + expect(docHandles({ ...entry('/a/dir.md', 'text'), kind: 'dir' })).toBe(false); + expect(docHandles(entry('/a/x.bin', 'other'))).toBe(false); + expect(docHandles(entry('/a/x.csv', 'other'))).toBe(true); + }); +}); + +describe('virtual list paging maths', () => { + const make = (rowH: number): { sc: HTMLElement; list: VirtualList; filled: number[] } => { + const sc = document.createElement('div'); + const filled: number[] = []; + const list = new VirtualList(sc, rowH, () => document.createElement('div'), (n, i) => { filled.push(i); n.textContent = `row ${i}`; }); + return { sc, list, filled }; + }; + it('makes the body as tall as the row count times the row height', () => { + const { list } = make(10); + list.setCount(1000); + expect(list.body.style.height).toBe('10000px'); + expect(list.total).toBe(1000); + }); + it('caps the body at eight million pixels for huge lists', () => { + const { list } = make(10); + list.setCount(1_000_000); + expect(list.body.style.height).toBe('8000000px'); + }); + it('scrolls to row times row height and reports that row as first visible', () => { + const { sc, list } = make(10); + list.setCount(1000); + list.scrollToIndex(37); + expect(sc.scrollTop).toBe(370); + expect(list.firstVisible()).toBe(37); + }); + it('clamps a scroll target to the last row and to zero', () => { + const { sc, list } = make(10); + list.setCount(50); + list.scrollToIndex(999); + expect(sc.scrollTop).toBe(490); + list.scrollToIndex(-5); + expect(sc.scrollTop).toBe(0); + }); + it('never builds more row nodes than there are rows', () => { + const { list } = make(10); + list.setCount(2); + expect(list.body.children.length).toBe(2); + list.setCount(0); + expect(list.body.children.length).toBe(0); + }); + it('fills rows starting at index zero with their own index', () => { + const { list } = make(10); + list.setCount(3); + expect(Array.from(list.body.children).map((c) => c.textContent)).toEqual(['row 0', 'row 1', 'row 2']); + }); +}); + +describe('grid', () => { + it('shows a one-based row number, the cell text, and NULL for a null cell', () => { + const g = new VGrid(); + const data: Array> = [['a', null], ['b', 'c']]; + g.cell = (r, c) => data[r][c]; + g.setColumns([{ label: 'L', width: 80 }, { label: 'R', width: 90, right: true }]); + g.setCount(2); + const rows = Array.from(g.root.querySelectorAll('.dv-grid-row')).map((r) => Array.from(r.children).map((c) => c.textContent)); + expect(rows).toEqual([['1', 'a', 'NULL'], ['2', 'b', 'c']]); + expect(g.root.querySelectorAll('.is-null').length).toBe(1); + }); + it('labels the header and sums the column widths plus the 56px gutter', () => { + const g = new VGrid(); + g.setColumns([{ label: 'L', width: 80 }, { label: 'R', width: 90 }]); + expect(Array.from(g.root.querySelectorAll('.dv-gh-label')).map((n) => n.textContent)).toEqual(['L', 'R']); + expect(g.root.style.getPropertyValue('--w')).toBe('226px'); + }); + it('reports the clicked header column to the sort handler', () => { + const g = new VGrid(); + g.setColumns([{ label: 'L', width: 80 }, { label: 'R', width: 90 }]); + const got: number[] = []; + g.onSort = (c) => got.push(c); + (g.root.querySelectorAll('.dv-gh-label')[1] as HTMLElement).click(); + expect(got).toEqual([1]); + }); +}); + +describe('unicode block table', () => { + it('has ordered, non-overlapping ranges', () => { + for (let i = 0; i < BLOCKS.length; i++) { + expect(BLOCKS[i][1]).toBeLessThanOrEqual(BLOCKS[i][2]); + if (i > 0) expect(BLOCKS[i][1]).toBeGreaterThan(BLOCKS[i - 1][2]); + } + }); + it('puts the letter A in Basic Latin and the Greek alpha in Greek and Coptic', () => { + const of = (cp: number): string | undefined => BLOCKS.find((b) => cp >= b[1] && cp <= b[2])?.[0]; + expect(of(0x41)).toBe('Basic Latin'); + expect(of(0x3b1)).toBe('Greek and Coptic'); + expect(of(0x416)).toBe('Cyrillic'); + }); +}); + +describe('3D model helpers', () => { + it('treats STL and 3MF as Z-up and glTF as Y-up, as those formats define', () => { + expect(zUpByDefault('stl')).toBe(true); + expect(zUpByDefault('3mf')).toBe(true); + expect(zUpByDefault('glb')).toBe(false); + expect(zUpByDefault('obj')).toBe(false); + }); + it('lists the natively loaded model formats', () => { + for (const e of ['glb', 'gltf', 'obj', 'stl', 'ply', 'fbx']) expect(NATIVE.has(e)).toBe(true); + expect(NATIVE.has('txt')).toBe(false); + }); + it('disposes every geometry and material in a tree', () => { + const g = new Group(); + const inner = new Group(); + const m1 = new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial()); + const m2 = new Mesh(new BoxGeometry(2, 2, 2), [new MeshBasicMaterial(), new MeshBasicMaterial()]); + g.add(m1, inner); + inner.add(m2); + let n = 0; + m1.geometry.addEventListener('dispose', () => { n++; }); + m2.geometry.addEventListener('dispose', () => { n++; }); + (m1.material as MeshBasicMaterial).addEventListener('dispose', () => { n++; }); + for (const m of m2.material as MeshBasicMaterial[]) m.addEventListener('dispose', () => { n++; }); + disposeTree(g); + expect(n).toBe(5); + }); +}); diff --git a/frontend/tests/unit/docview/table-tree.test.ts b/frontend/tests/unit/docview/table-tree.test.ts new file mode 100644 index 0000000..3f1a16b --- /dev/null +++ b/frontend/tests/unit/docview/table-tree.test.ts @@ -0,0 +1,180 @@ +import { describe, it, expect } from 'vitest'; +import { CsvView } from '../../../src/ui/docview/csv'; +import { JsonView } from '../../../src/ui/docview/json'; +import { deps, entry, settle, stubEngine, textDoc, txt } from './helpers'; + +interface Csv { delimiter?: string; header: string[] | null; rows: string[][]; total_rows?: number; truncated?: boolean } + +async function openCsv(c: Csv): Promise { + stubEngine({ csv: { delimiter: c.delimiter ?? ',', header: c.header, rows: c.rows, total_rows: c.total_rows ?? c.rows.length, truncated: c.truncated ?? false } }); + const v = new CsvView(deps()); + document.body.appendChild(v.root); + await v.open(entry('/w/t.csv', 'text')); + await settle(); + return v; +} + +const labels = (root: HTMLElement): string[] => Array.from(root.querySelectorAll('.dv-gh-label')).map((n) => n.textContent ?? ''); +const rows = (root: HTMLElement): string[][] => Array.from(root.querySelectorAll('.dv-grid-row')).map((r) => Array.from(r.children).slice(1).map((c) => c.textContent ?? '')); +const col = (root: HTMLElement, c: number): string[] => rows(root).map((r) => r[c]); +const sortBy = (root: HTMLElement, c: number): void => { (root.querySelectorAll('.dv-gh-label')[c] as HTMLElement).click(); }; + +function filter(v: CsvView, s: string): void { + const f = v.root.querySelector('.dv-find'); + if (!f) throw new Error('no filter'); + f.value = s; + f.dispatchEvent(new Event('input')); +} + +const PEOPLE: Csv = { header: ['name', 'age'], rows: [['Ann', '10'], ['Bob', '9'], ['Cy', '100']] }; + +describe('table viewer for CSV', () => { + it('uses the header row as column labels and shows the data rows in file order', async () => { + const v = await openCsv(PEOPLE); + expect(labels(v.root)).toEqual(['name', 'age']); + expect(rows(v.root)).toEqual([['Ann', '10'], ['Bob', '9'], ['Cy', '100']]); + }); + it('describes the delimiter, row count and column count', async () => { + const v = await openCsv(PEOPLE); + expect(txt(v.root, '.dv-info')).toBe('Comma-separated \u00b7 3 rows \u00b7 2 columns'); + }); + it('names a tab-separated file as such', async () => { + const v = await openCsv({ ...PEOPLE, delimiter: '\t' }); + expect(txt(v.root, '.dv-info')).toMatch(/^Tab-separated/); + }); + it('sorts a numeric column by value, not as text, then descending, then back to file order', async () => { + const v = await openCsv(PEOPLE); + sortBy(v.root, 1); + expect(col(v.root, 1)).toEqual(['9', '10', '100']); + sortBy(v.root, 1); + expect(col(v.root, 1)).toEqual(['100', '10', '9']); + sortBy(v.root, 1); + expect(col(v.root, 1)).toEqual(['10', '9', '100']); + }); + it('sorts a text column alphabetically ignoring case', async () => { + const v = await openCsv({ header: ['w'], rows: [['pear'], ['Apple'], ['banana']] }); + sortBy(v.root, 0); + expect(col(v.root, 0)).toEqual(['Apple', 'banana', 'pear']); + }); + it('puts empty cells last when sorting', async () => { + const v = await openCsv({ header: ['n'], rows: [['3'], [''], ['1']] }); + sortBy(v.root, 0); + expect(col(v.root, 0)).toEqual(['1', '3', '']); + }); + it('keeps only rows containing the filter text, ignoring case, and counts them', async () => { + const v = await openCsv(PEOPLE); + filter(v, 'BO'); + expect(rows(v.root)).toEqual([['Bob', '9']]); + expect(txt(v.root, '.dv-count')).toBe('1 of 3 rows'); + }); + it('turns the header back into a data row when the header toggle is switched off', async () => { + const v = await openCsv(PEOPLE); + v.root.querySelector('[data-c="header"]')?.click(); + expect(labels(v.root)).toEqual(['A', 'B']); + expect(rows(v.root)[0]).toEqual(['name', 'age']); + expect(rows(v.root).length).toBe(4); + }); + it('labels columns A, B, ... Z, AA, AB like a spreadsheet when there is no header', async () => { + const wide = Array.from({ length: 28 }, (_, i) => String(i)); + const v = await openCsv({ header: null, rows: [wide] }); + const l = labels(v.root); + expect(l[0]).toBe('A'); + expect(l[25]).toBe('Z'); + expect(l[26]).toBe('AA'); + expect(l[27]).toBe('AB'); + expect(v.root.querySelector('[data-c="header"]')?.disabled).toBe(true); + }); + it('says how many of the total rows are shown for a truncated file', async () => { + const v = await openCsv({ ...PEOPLE, total_rows: 5000, truncated: true }); + expect(txt(v.root, '.dv-note')).toBe('Showing the first 3 of 5,000 rows.'); + }); +}); + +async function openJson(text: string, name = '/w/d.json'): Promise { + stubEngine({ text: textDoc(text, 'json') }); + const v = new JsonView(deps()); + document.body.appendChild(v.root); + await v.open(entry(name, 'text')); + await settle(); + return v; +} + +const tree = (v: JsonView): HTMLElement => v.root.querySelector('.dv-jtree') as HTMLElement; +const kids = (n: Element): HTMLElement[] => Array.from(n.querySelectorAll(':scope > .dv-jkids > .dv-jn')); +const rowText = (n: Element): string => Array.from(n.querySelector(':scope > .dv-jrow')?.querySelectorAll('.dv-jk,.dv-jc,.dv-jv') ?? []).map((s) => s.textContent).join(''); +const top = (v: JsonView): HTMLElement => tree(v).firstElementChild as HTMLElement; +const pathOf = (v: JsonView, n: Element): string => { + (n.querySelector(':scope > .dv-jrow .dv-jv') as HTMLElement).click(); + return v.root.querySelector('.dv-path')?.value ?? ''; +}; + +describe('JSON tree viewer', () => { + it('summarises the top level and shows each key with a typed value preview', async () => { + const v = await openJson('{"a": 1, "s": "hi", "n": null, "t": true, "o": {"x": 1, "y": 2}, "l": [1]}'); + expect(rowText(top(v))).toBe('{ 6 keys }'); + expect(kids(top(v)).map(rowText)).toEqual(['a:1', 's:"hi"', 'n:null', 't:true', 'o:{ 2 keys }', 'l:[ 1 item ]']); + expect(txt(v.root, '.dv-info')).toBe('6 keys at the top level'); + }); + it('opens a nested object when its caret is clicked and closes it again', async () => { + const v = await openJson('{"o": {"x": 1}}'); + const o = kids(top(v))[0]; + (o.querySelector('.dv-jcaret') as HTMLElement).click(); + expect(o.classList.contains('is-open')).toBe(true); + expect(kids(o).map(rowText)).toEqual(['x:1']); + (o.querySelector('.dv-jcaret') as HTMLElement).click(); + expect(o.classList.contains('is-open')).toBe(false); + }); + it('shows the selected node path in dot, bracket and quoted-key form', async () => { + const v = await openJson('{"list": [10, 20], "a b": 1}'); + const [list, spaced] = kids(top(v)); + expect(pathOf(v, list)).toBe('$.list'); + expect(pathOf(v, spaced)).toBe('$["a b"]'); + (list.querySelector('.dv-jcaret') as HTMLElement).click(); + expect(pathOf(v, kids(list)[1])).toBe('$.list[1]'); + }); + it('pages a long array one hundred children at a time', async () => { + const v = await openJson(JSON.stringify(Array.from({ length: 250 }, (_, i) => i))); + const r = top(v); + expect(kids(r).length).toBe(100); + expect(r.querySelector('.dv-jmore')?.textContent).toBe('Show 100 more of 150 left'); + (r.querySelector('.dv-jmore') as HTMLElement).click(); + expect(kids(r).length).toBe(200); + expect(rowText(kids(r)[199])).toBe('199:199'); + (r.querySelector('.dv-jmore') as HTMLElement).click(); + expect(kids(r).length).toBe(250); + expect(r.querySelector('.dv-jmore')).toBeNull(); + }); + it('reads a JSON Lines file as one array item per non-empty line', async () => { + const v = await openJson('{"a":1}\n\n{"a":2}\n', '/w/d.jsonl'); + expect(txt(v.root, '.dv-info')).toBe('2 items at the top level'); + expect(kids(top(v)).map(rowText)).toEqual(['0:{ 1 key }', '1:{ 1 key }']); + }); + it('names the broken line of a JSON Lines file', async () => { + const v = await openJson('{"a":1}\n{oops\n', '/w/d.jsonl'); + expect(txt(v.root, '.dv-note')).toMatch(/^Line 2: /); + expect(tree(v).children.length).toBe(0); + }); + it('falls back to the text view with the parse error for invalid JSON', async () => { + const v = await openJson('{"a": }'); + expect(txt(v.root, '.dv-note')).not.toBe(''); + expect(v.root.querySelector('[data-j="tree"]')?.disabled).toBe(true); + expect((v.root.querySelector('.dv-jscroll') as HTMLElement).hidden).toBe(true); + expect(Array.from(v.root.querySelectorAll('.dv-ln')).map((n) => n.textContent)).toEqual(['{"a": }']); + }); + it('describes a bare scalar document as a single value', async () => { + const v = await openJson('42'); + expect(txt(v.root, '.dv-info')).toBe('A single value'); + expect(rowText(top(v))).toBe('42'); + }); + it('gives empty containers no caret', async () => { + const v = await openJson('{"e": [], "f": {}}'); + expect(kids(top(v)).map(rowText)).toEqual(['e:[ ]', 'f:{ }']); + for (const k of kids(top(v))) expect(k.querySelector('.dv-jcaret')?.innerHTML).toBe(''); + }); + it('shows a key holding markup as plain text', async () => { + const v = await openJson('{"": ""}'); + expect(tree(v).querySelector('img')).toBeNull(); + expect(tree(v).querySelector('script')).toBeNull(); + expect(rowText(kids(top(v))[0])).toBe(':""'); + }); +}); diff --git a/frontend/tests/unit/docview/text.test.ts b/frontend/tests/unit/docview/text.test.ts new file mode 100644 index 0000000..1d82697 --- /dev/null +++ b/frontend/tests/unit/docview/text.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect } from 'vitest'; +import { TextView } from '../../../src/ui/docview/text'; +import { deps, entry, settle, stubEngine, textDoc, txt } from './helpers'; + +async function openText(text: string, language: string | null = null, extra: Record = {}): Promise { + stubEngine({ text: textDoc(text, language, extra) }); + const v = new TextView(deps()); + document.body.appendChild(v.root); + await v.open(entry('/w/notes.txt', 'text')); + await settle(); + return v; +} + +const lineTexts = (v: TextView): string[] => Array.from(v.root.querySelectorAll('.dv-ln')).map((n) => n.textContent ?? ''); +const lineNums = (v: TextView): string[] => Array.from(v.root.querySelectorAll('.dv-ln')).map((n) => n.dataset.n ?? ''); + +function find(v: TextView, needle: string): void { + const box = v.root.querySelector('.dv-find'); + if (!box) throw new Error('no find box'); + box.value = needle; + box.dispatchEvent(new Event('input')); +} + +const press = (v: TextView, t: string): void => { v.root.querySelector(`[data-t="${t}"]`)?.click(); }; + +describe('text viewer', () => { + it('shows every line of the file in its own row numbered from one', async () => { + const v = await openText('alpha\nbeta\ngamma'); + expect(lineTexts(v)).toEqual(['alpha', 'beta', 'gamma']); + expect(lineNums(v)).toEqual(['1', '2', '3']); + }); + it('does not show an extra empty row for a final newline', async () => { + const v = await openText('one\ntwo\n'); + expect(lineTexts(v)).toEqual(['one', 'two']); + }); + it('splits Windows and old Mac line endings into separate rows', async () => { + const v = await openText('a\r\nb\rc', null, { eol: 'mixed' }); + expect(lineTexts(v)).toEqual(['a', 'b', 'c']); + }); + it('states encoding, line ending and line count in the info line', async () => { + const v = await openText('x\ny\nz'); + expect(txt(v.root, '.dv-info')).toBe('utf-8 \u00b7 LF \u00b7 3 lines'); + expect(txt(v.root, '.dv-note')).toBe('No highlighting for this file type.'); + }); + it('mentions a byte order mark and CRLF endings', async () => { + const v = await openText('x\r\ny', null, { bom: true, eol: 'crlf', lines: 2 }); + expect(txt(v.root, '.dv-info')).toBe('utf-8 with BOM \u00b7 CRLF \u00b7 2 lines'); + }); + it('shows markup inside a plain text file as literal characters', async () => { + const v = await openText('bold'); + expect(v.root.querySelector('.dv-code b')).toBeNull(); + expect(v.root.querySelector('.dv-code img')).toBeNull(); + expect(lineTexts(v)).toEqual(['bold']); + expect((window as unknown as { __ftx?: number }).__ftx).toBeUndefined(); + }); + it('keeps the visible text of a highlighted source file identical to the file', async () => { + const src = 'def f(x):\n return "a\\nb" + str(x)\n'; + const v = await openText(src, 'python'); + expect(lineTexts(v)).toEqual(['def f(x):', ' return "a\\nb" + str(x)']); + expect(txt(v.root, '.dv-info')).toContain('python'); + expect(v.root.querySelector('.dv-ln span')).not.toBeNull(); + }); + it('says when only the first part of a long file is shown', async () => { + const v = await openText('abcd', null, { truncated: true }); + expect(txt(v.root, '.dv-note')).toContain('Showing the first 4 B of the file.'); + }); + it('shows the engine refusal message when the file cannot be read', async () => { + stubEngine({}); + const v = new TextView(deps()); + await v.open(entry('/w/gone.txt', 'text')); + expect(txt(v.root, '.dv-note')).toBe('No such thing here.'); + expect(v.root.querySelectorAll('.dv-ln').length).toBe(0); + }); +}); + +describe('text search', () => { + it('counts every occurrence ignoring case, including several on one line', async () => { + const v = await openText('Banana\nplan\nnothing'); + find(v, 'an'); + expect(txt(v.root, '.dv-count')).toBe('1 of 3'); + }); + it('marks the line that holds the current match', async () => { + const v = await openText('zero\nhere is the needle\nmore'); + find(v, 'needle'); + const hit = v.root.querySelector('.dv-ln.is-hit'); + expect(hit?.dataset.n).toBe('2'); + }); + it('steps to the next match and wraps from the last back to the first', async () => { + const v = await openText('ab\nab\nab'); + find(v, 'b'); + press(v, 'next'); + expect(txt(v.root, '.dv-count')).toBe('2 of 3'); + press(v, 'next'); + press(v, 'next'); + expect(txt(v.root, '.dv-count')).toBe('1 of 3'); + }); + it('steps back from the first match to the last one', async () => { + const v = await openText('x1\nx2\nx3\nx4'); + find(v, 'x'); + press(v, 'prev'); + expect(txt(v.root, '.dv-count')).toBe('4 of 4'); + expect(v.root.querySelector('.dv-ln.is-hit')?.dataset.n).toBe('4'); + }); + it('finds only exact-case matches once match case is on', async () => { + const v = await openText('Aa\naA\na'); + find(v, 'A'); + expect(txt(v.root, '.dv-count')).toBe('1 of 5'); + press(v, 'case'); + expect(txt(v.root, '.dv-count')).toBe('1 of 2'); + }); + it('says no matches for text that is not in the file and clears when emptied', async () => { + const v = await openText('hello world'); + find(v, 'zebra'); + expect(txt(v.root, '.dv-count')).toBe('No matches'); + find(v, ''); + expect(txt(v.root, '.dv-count')).toBe(''); + }); + it('does not count overlapping occurrences twice', async () => { + const v = await openText('aaaa'); + find(v, 'aa'); + expect(txt(v.root, '.dv-count')).toBe('1 of 2'); + }); +}); diff --git a/frontend/tests/unit/io/engine-client.test.ts b/frontend/tests/unit/io/engine-client.test.ts new file mode 100644 index 0000000..2103d8b --- /dev/null +++ b/frontend/tests/unit/io/engine-client.test.ts @@ -0,0 +1,400 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { api, ApiError } from '../../../src/io/api'; +import { loadWindowKey, windowKey, keyed } from '../../../src/io/window-key'; +import { desktopApi } from '../../../src/io/desktop-api'; +import { utilApi, fmtBytes, baseName, dirName } from '../../../src/io/util-api'; +import { host, inDesktop } from '../../../src/io/host'; +import { desk, overlayParams } from '../../../src/io/desk'; + +interface Call { url: string; init: RequestInit } + +function engine(reply: (url: string, init: RequestInit) => Response): { calls: Call[] } { + const calls: Call[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => { + const i = init ?? {}; + calls.push({ url, init: i }); + return reply(url, i); + })); + return { calls }; +} + +const json = (body: unknown, status = 200): Response => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function noKey(): Promise { + sessionStorage.clear(); + vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 500 }))); + await loadWindowKey(); +} + +async function refusal(p: Promise): Promise { + try { await p; } catch (e) { return e as ApiError; } + throw new Error('the call was not refused'); +} + +beforeEach(async () => { await noKey(); }); +afterEach(() => { vi.unstubAllGlobals(); sessionStorage.clear(); }); + +describe('engine client requests', () => { + it('lists a folder by sending the path and the hidden flag in the query', async () => { + const { calls } = engine(() => json({ path: '/photos/a b', parent: '/photos', entries: [] })); + const out = await api.list('/photos/a b&c', true); + const q = new URL(calls[0].url, 'http://x').searchParams; + expect(new URL(calls[0].url, 'http://x').pathname).toBe('/api/fs/list'); + expect(q.get('path')).toBe('/photos/a b&c'); + expect(q.get('hidden')).toBe('1'); + expect(out.parent).toBe('/photos'); + }); + + it('sends hidden as 0 when hidden files are not asked for', async () => { + const { calls } = engine(() => json({ path: '/', parent: null, entries: [] })); + await api.dirs('/'); + expect(new URL(calls[0].url, 'http://x').searchParams.get('hidden')).toBe('0'); + }); + + it('writes a rating as a JSON POST that carries the path and only the changed field', async () => { + const { calls } = engine(() => json({ rating: 4, label: null })); + const tag = await api.metaWrite('/p/x.jpg', { rating: 4 }); + expect(calls[0].url).toBe('/api/meta/write'); + expect(calls[0].init.method).toBe('POST'); + expect(new Headers(calls[0].init.headers).get('Content-Type')).toBe('application/json'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ path: '/p/x.jpg', rating: 4 }); + expect(tag.rating).toBe(4); + }); + + it('saves a preset with PUT under its name escaped for the URL', async () => { + const { calls } = engine(() => json({ ok: true })); + const output = { format: 'png', quality: 90, folder: '', subfolder: '', naming: '{name}', overwrite: 'rename', keep_metadata: true, keep_folders: false, keep_dates: true } as const; + await api.savePreset('web/small #1', [], output); + expect(calls[0].init.method).toBe('PUT'); + expect(decodeURIComponent(calls[0].url.slice('/api/batch/presets/'.length))).toBe('web/small #1'); + expect(calls[0].url).not.toContain('/small'); + }); + + it('deletes a preset with the DELETE method', async () => { + const { calls } = engine(() => json({ ok: true })); + await api.deletePreset('old'); + expect(calls[0]).toMatchObject({ url: '/api/batch/presets/old', init: { method: 'DELETE' } }); + }); + + it('asks for a lossless transform when rotating a picture', async () => { + const { calls } = engine(() => json({ ok: true, lossless_used: true, path: '/p/x.jpg' })); + const out = await api.transform('/p/x.jpg', 'rotate-cw'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ path: '/p/x.jpg', op: 'rotate-cw', lossless: true }); + expect(out.lossless_used).toBe(true); + }); + + it('sends an edit with its operations, output and overwrite flag', async () => { + const { calls } = engine(() => json({ ok: true, path: '/p/out.png' })); + await api.edit('/p/x.jpg', [{ op: 'crop', x: 1, y: 2, w: 3, h: 4 }], { format: 'png' }, true); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ path: '/p/x.jpg', ops: [{ op: 'crop', x: 1, y: 2, w: 3, h: 4 }], out: { format: 'png' }, overwrite: true }); + }); + + it('cancels a job by posting to the job id escaped for the URL', async () => { + const { calls } = engine(() => json({ id: 'a/b', state: 'cancelled' })); + const job = await api.cancelJob('a/b'); + expect(calls[0].url).toBe('/api/jobs/a%2Fb/cancel'); + expect(job.state).toBe('cancelled'); + }); + + it('answers a consent request with the chosen answer', async () => { + const { calls } = engine(() => json({ access: 'ask', kept: false })); + await api.agentAnswer('r 1', 'once'); + expect(calls[0].url).toBe('/api/agents/requests/r%201'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ answer: 'once' }); + }); + + it('sets agent access with PUT', async () => { + const { calls } = engine(() => json({ access: 'blocked' })); + const out = await api.agentSetAccess('blocked'); + expect(calls[0].init.method).toBe('PUT'); + expect(out.access).toBe('blocked'); + }); + + it('merges batch inputs, output and actions into one plan body', async () => { + const { calls } = engine(() => json({ items: [], skipped: [] })); + const output = { format: 'same', quality: 80, folder: '/out', subfolder: '', naming: '{name}', overwrite: 'skip', keep_metadata: false, keep_folders: true, keep_dates: false } as const; + await api.batchPlan({ inputs: ['/a'], recursive: true, extensions: ['jpg'] }, output, [{ id: 'resize', params: { w: 10 } }]); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ inputs: ['/a'], recursive: true, extensions: ['jpg'], output, actions: [{ id: 'resize', params: { w: 10 } }] }); + }); + + it('unwraps the terminal list from the engine answer', async () => { + engine(() => json({ terminals: [{ id: 't1', title: 'sh', alive: true, kind: 'shell' }] })); + expect((await api.terminals()).map((t) => t.id)).toEqual(['t1']); + }); + + it('sends the waveform point count with the path', async () => { + const { calls } = engine(() => json({ duration: 2, peaks: [0, 1] })); + await api.waveform('/m/a.wav', 512); + const q = new URL(calls[0].url, 'http://x').searchParams; + expect([q.get('path'), q.get('points')]).toEqual(['/m/a.wav', '512']); + }); +}); + +describe('engine client refusals', () => { + it('carries the engine refusal message and HTTP status to the caller', async () => { + engine(() => json({ ok: false, error: 'No such folder: /nope' }, 404)); + const e = await refusal(api.list('/nope')); + expect(e).toBeInstanceOf(ApiError); + expect(e.message).toBe('No such folder: /nope'); + expect(e.status).toBe(404); + }); + + it('treats an answer with ok false as a refusal even when the status is 200', async () => { + engine(() => json({ ok: false, error: 'The file is read only.' }, 200)); + const e = await refusal(api.metaWrite('/p/x.jpg', { label: 'red' })); + expect(e.message).toBe('The file is read only.'); + expect(e.status).toBe(200); + }); + + it('names the status when the engine answers without a JSON body', async () => { + engine(() => new Response('bad gateway', { status: 502 })); + const e = await refusal(api.health()); + expect(e.status).toBe(502); + expect(e.message).toContain('502'); + }); + + it('refuses an answer whose body is empty even with status 200', async () => { + engine(() => new Response('', { status: 200 })); + const e = await refusal(api.capabilities()); + expect(e).toBeInstanceOf(ApiError); + expect(e.message).toContain('200'); + }); + + it('lets a network failure reach the caller', async () => { + vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('Failed to fetch'); })); + await expect(api.home()).rejects.toThrow('Failed to fetch'); + }); + + it('refuses a Claude Code start that comes back without a terminal id', async () => { + engine(() => json({ title: 'claude' })); + const e = await refusal(api.openClaude({ prompt: 'hi' })); + expect(e).toBeInstanceOf(ApiError); + expect(e.status).toBe(502); + }); + + it('returns the Claude Code terminal when the engine gives an id', async () => { + const { calls } = engine(() => json({ id: 't9', title: 'claude', alive: true, kind: 'claude' })); + const t = await api.openClaude({ resume: 's1', cols: 80, rows: 24 }); + expect(t.id).toBe('t9'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ resume: 's1', cols: 80, rows: 24 }); + }); + + it('turns a refused agent status into null instead of throwing', async () => { + engine(() => json({ ok: false, error: 'gone' }, 500)); + expect(await api.claudeStatus()).toBeNull(); + }); + + it('asks for a fresh agent status with a query flag', async () => { + const { calls } = engine(() => json({ installed: true, running: false })); + await api.claudeStatus(true); + expect(calls[0].url).toBe('/api/agent/claude/status?fresh=true'); + }); + + it('reports Claude Code as missing when both status routes are refused', async () => { + engine(() => json({ ok: false, error: 'no' }, 404)); + expect(await api.claudeCodeStatus()).toBeNull(); + }); + + it('reports Claude Code installed from the newer status route without asking the older one', async () => { + const { calls } = engine(() => json({ installed: true, version: '2.1.0', signedIn: true })); + expect(await api.claudeCodeStatus()).toEqual({ installed: true, version: '2.1.0', install: '', signedIn: true }); + expect(calls.length).toBe(1); + }); + + it('falls back to the older agent status route when the newer one is refused', async () => { + engine((url) => url.startsWith('/api/claude-code/') ? json({ ok: false }, 404) : json({ installed: true, version: '1.0', install: 'npm i', signedIn: false })); + expect(await api.claudeCodeStatus()).toEqual({ installed: true, version: '1.0', install: 'npm i', signedIn: false }); + }); + + it('refuses a batch preview with the engine message', async () => { + engine(() => json({ error: 'Cannot read that picture.' }, 415)); + const e = await refusal(api.batchPreviewUrl('/p/x.heic', [], 512)); + expect([e.message, e.status]).toEqual(['Cannot read that picture.', 415]); + }); +}); + +describe('engine URLs built for the page', () => { + it('builds a thumbnail URL whose query reads back to the same path, size and stamp', () => { + const u = new URL(api.thumbUrl('C:\\Shots\\a b#1.jpg', 256, 7), 'http://x'); + expect(u.pathname).toBe('/api/image/thumb'); + expect(Object.fromEntries(u.searchParams)).toEqual({ path: 'C:\\Shots\\a b#1.jpg', size: '256', v: '7' }); + }); + + it('builds view, raw and stream URLs that round trip the path', () => { + const p = '/m/100% sure?.mov'; + for (const url of [api.viewUrl(p), api.rawUrl(p), api.streamUrl(p), api.mediaThumbUrl(p, 64)]) { + expect(new URL(url, 'http://x').searchParams.get('path')).toBe(p); + } + }); + + it('names an external subtitle file in its own query field', () => { + const q = new URL(api.subtitleFileUrl('/m/a.mkv', '/m/a.en.srt'), 'http://x').searchParams; + expect([q.get('path'), q.get('file')]).toEqual(['/m/a.mkv', '/m/a.en.srt']); + }); +}); + +describe('window key', () => { + it('uses a key handed over by the desktop shell and attaches it to every request', async () => { + (window as unknown as { __FORMTOOLS_WINDOW_KEY?: string }).__FORMTOOLS_WINDOW_KEY = 'k-given'; + await loadWindowKey(); + expect(windowKey()).toBe('k-given'); + expect((window as unknown as { __FORMTOOLS_WINDOW_KEY?: string }).__FORMTOOLS_WINDOW_KEY).toBeUndefined(); + const { calls } = engine(() => json({ ok: true, app: 'formtools', version: '0.14.0' })); + await api.health(); + expect(new Headers(calls[0].init.headers).get('X-Formtools-Window-Key')).toBe('k-given'); + }); + + it('asks the engine for a new key when none is stored and remembers it for the tab', async () => { + const { calls } = engine((url) => url === '/api/window/key' ? json({ key: 'k-new' }) : json({}, 401)); + await loadWindowKey(); + expect(windowKey()).toBe('k-new'); + expect(calls.map((c) => [c.url, c.init.method])).toEqual([['/api/window/key', 'POST']]); + expect(sessionStorage.getItem('formtools-window-key')).toBe('k-new'); + }); + + it('keeps a stored key the engine still accepts without asking for a new one', async () => { + sessionStorage.setItem('formtools-window-key', 'k-old'); + const { calls } = engine(() => json({ terminals: [] })); + await loadWindowKey(); + expect(windowKey()).toBe('k-old'); + expect(calls.map((c) => c.url)).toEqual(['/api/terminal']); + expect(new Headers(calls[0].init.headers).get('X-Formtools-Window-Key')).toBe('k-old'); + }); + + it('replaces a stored key the engine no longer accepts', async () => { + sessionStorage.setItem('formtools-window-key', 'k-stale'); + engine((url) => url === '/api/window/key' ? json({ key: 'k-fresh' }) : json({ error: 'bad key' }, 403)); + await loadWindowKey(); + expect(windowKey()).toBe('k-fresh'); + expect(sessionStorage.getItem('formtools-window-key')).toBe('k-fresh'); + }); + + it('sends requests without the key header when there is no key', () => { + expect(windowKey()).toBe(''); + expect(new Headers(keyed({ headers: { A: 'b' } }).headers).has('X-Formtools-Window-Key')).toBe(false); + }); +}); + +describe('desktop and file tool clients', () => { + it('explains that the desktop tool is missing when the engine has no such route', async () => { + engine(() => new Response('Not Found', { status: 404 })); + const e = await refusal(desktopApi.hosts()); + expect(e.status).toBe(404); + expect(e.message).toMatch(/does not include the desktop tool/); + }); + + it('passes on the engine message for a refused hosts save', async () => { + engine(() => json({ ok: false, error: 'The hosts file changed on disk.' }, 409)); + const e = await refusal(desktopApi.saveHosts([], 'v1')); + expect([e.message, e.status]).toEqual(['The hosts file changed on disk.', 409]); + }); + + it('sends the version only when one is known when saving hosts', async () => { + const { calls } = engine(() => json({ ok: true, backup: '/b', elevated: false })); + const entry = { enabled: true, address: '127.0.0.1', names: ['a.test'], comment: '' }; + await desktopApi.saveHosts([entry]); + await desktopApi.saveHosts([entry], 'v2'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ entries: [entry] }); + expect(JSON.parse(String(calls[1].init.body))).toEqual({ entries: [entry], version: 'v2' }); + }); + + it('sends a null value to remove an environment variable', async () => { + const { calls } = engine(() => json({ ok: true })); + await desktopApi.setEnv('user', 'FOO', null); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ scope: 'user', name: 'FOO', value: null }); + }); + + it('leaves the name out of a template create when none is given', async () => { + const { calls } = engine(() => json({ ok: true, path: '/d/x' })); + await utilApi.templateCreate('Note.txt', '/d'); + await utilApi.templateCreate('Note.txt', '/d', 'Mine.txt'); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ template: 'Note.txt', folder: '/d' }); + expect(JSON.parse(String(calls[1].init.body))).toEqual({ template: 'Note.txt', folder: '/d', name: 'Mine.txt' }); + }); + + it('asks who holds a file open with the path escaped in the query', async () => { + const { calls } = engine(() => json({ supported: true, holders: [] })); + await utilApi.locks('/x/a&b.txt'); + expect(new URL(calls[0].url, 'http://x').searchParams.get('path')).toBe('/x/a&b.txt'); + }); + + it('refuses a trash request with the engine message', async () => { + engine(() => json({ ok: false, error: 'Nothing to trash.' }, 400)); + await expect(utilApi.trash([])).rejects.toThrow('Nothing to trash.'); + }); +}); + +describe('byte sizes and path names', () => { + it('shows sizes under one kibibyte in bytes', () => { + expect(fmtBytes(0)).toBe('0 B'); + expect(fmtBytes(1023)).toBe('1023 B'); + }); + + it('shows 1536 bytes as 1.5 KB', () => { + expect(fmtBytes(1536)).toBe('1.5 KB'); + }); + + it('drops the decimal from 100 units upward', () => { + expect(fmtBytes(150 * 1024 * 1024)).toBe('150 MB'); + expect(fmtBytes(99.5 * 1024)).toBe('99.5 KB'); + }); + + it('stops at terabytes for very large sizes', () => { + expect(fmtBytes(2048 * 1024 ** 4)).toBe('2048 TB'); + }); + + it('shows a negative or unknown size as 0 B', () => { + expect(fmtBytes(-5)).toBe('0 B'); + expect(fmtBytes(Number.NaN)).toBe('0 B'); + }); + + it('takes the last name of a path with either separator and a trailing one', () => { + expect(baseName('/a/b/c.txt')).toBe('c.txt'); + expect(baseName('C:\\Users\\me\\Pics\\')).toBe('Pics'); + }); + + it('takes the folder of a path', () => { + expect(dirName('/a/b/c.txt')).toBe('/a/b'); + expect(dirName('C:\\x\\y.png')).toBe('C:\\x'); + }); +}); + +describe('desktop shell outside the desktop app', () => { + it('knows it is not in the desktop app', () => { + expect(inDesktop()).toBe(false); + }); + + it('answers null for every shell request in a browser', async () => { + expect(await host.pickFolder()).toBeNull(); + expect(await host.pickFiles()).toBeNull(); + expect(await host.menuStatus()).toBeNull(); + }); + + it('refuses a desk tool in a browser with a message saying where it works', async () => { + await expect(desk.caps()).rejects.toThrow('This works in the desktop app.'); + await expect(desk.start('ruler')).rejects.toThrow('desktop app'); + }); + + it('copies text through the browser clipboard outside the desktop app', async () => { + const writeText = vi.fn(async () => undefined); + vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText } }); + await desk.copyText('#FF0000'); + expect(writeText).toHaveBeenCalledWith('#FF0000'); + }); +}); + +describe('desk overlay parameters', () => { + it('reads the tool, shot, monitor, scale and options from the page query', () => { + const q = `?tool=ruler&shot=${encodeURIComponent('/tmp/s.png')}&monitor=2&scale=1.5&options=${encodeURIComponent(JSON.stringify({ unit: 'px' }))}`; + expect(overlayParams(q)).toEqual({ tool: 'ruler', shot: '/tmp/s.png', monitor: 2, scale: 1.5, options: { unit: 'px' } }); + }); + + it('falls back to the picker at scale 1 with no options for an empty query', () => { + expect(overlayParams('')).toEqual({ tool: 'picker', shot: '', monitor: 0, scale: 1, options: {} }); + }); + + it('ignores options that are not valid JSON and a zero scale', () => { + const p = overlayParams('?tool=zoom&scale=0&options=%7Bbroken'); + expect([p.scale, p.options]).toEqual([1, {}]); + }); +}); diff --git a/frontend/tests/unit/ui/dock-consent.test.ts b/frontend/tests/unit/ui/dock-consent.test.ts new file mode 100644 index 0000000..113321c --- /dev/null +++ b/frontend/tests/unit/ui/dock-consent.test.ts @@ -0,0 +1,147 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ConsentChoice, ConsentHost, ConsentRequest } from '../../../src/dock/adapter'; +import { Consent } from '../../../src/dock/consent'; +import { click, settle } from './support'; + +interface Rig { consent: Consent; add: (r: ConsentRequest) => void; withdraw: (id: string) => void; answer: ReturnType; changes: boolean[] } + +const rig = (opts: { changedOutside?: boolean; answer?: (id: string, c: ConsentChoice) => Promise } = {}): Rig => { + let add: (r: ConsentRequest) => void = () => undefined; + let withdraw: (id: string) => void = () => undefined; + const answer = vi.fn(opts.answer ?? (async () => undefined)); + const host: ConsentHost = { + words: { app: 'FormTools', noun: 'files', lead: '', example: '' }, + t: (_k: string, english: string) => english, + classes: { iconButton: 'ib', button: 'b', primaryButton: 'pb', input: 'i', select: 's', note: 'n' }, + consent: { subscribe: (a, w) => { add = a; withdraw = w; }, answer }, + storedChoice: { get: async () => ({ value: 'ask', changedOutside: opts.changedOutside === true }), set: async () => undefined }, + }; + const consent = new Consent(host); + const changes: boolean[] = []; + consent.onChange = (open) => changes.push(open); + return { consent, add: (r) => add(r), withdraw: (id) => withdraw(id), answer, changes }; +}; + +const req = (over: Partial = {}): ConsentRequest => ({ id: 'r1', agent: 'Scout', what: 'rename 3 files', offers: ['deny', 'once', 'always'], always: 'agent', ...over }); +const dlg = (): HTMLDialogElement => { + const d = document.querySelector('dialog.ft-consent'); + if (!d) throw new Error('no consent dialog'); + return d; +}; +const shown = (sel: string): string => dlg().querySelector(sel)?.textContent ?? ''; + +beforeEach(() => { vi.useFakeTimers(); }); +afterEach(async () => { + await vi.advanceTimersByTimeAsync(2000); + vi.useRealTimers(); + document.body.replaceChildren(); +}); + +describe('the outside agent consent dialog', () => { + it('opens as a modal naming the agent, what it asked and the app', async () => { + const r = rig(); + r.add(req()); + await settle(0); + expect(r.consent.isOpen()).toBe(true); + expect(shown('.ft-consent-title')).toBe('Allow an agent calling itself Scout to make changes in FormTools?'); + expect(shown('.ft-consent-what')).toBe('It asked to rename 3 files.'); + expect(shown('.ft-consent-always')).toBe('Always allow any agent named Scout'); + expect(shown('.ft-consent-count')).toBe('Request 1 of 1'); + expect(r.changes).toEqual([true]); + }); + + it('an unnamed agent and an all-agents scope get their own wording', async () => { + const r = rig(); + r.add(req({ agent: '', always: 'all' })); + await settle(0); + expect(shown('.ft-consent-title')).toBe('Allow an outside agent to make changes in FormTools?'); + expect(shown('.ft-consent-always')).toBe('Always allow all outside agents'); + }); + + it('shows only the choices the request offers', async () => { + const r = rig(); + r.add(req({ offers: ['deny', 'once'] })); + await settle(0); + const hidden = (c: string): boolean => (dlg().querySelector(`.ft-consent-${c}`) as HTMLElement).hidden === true; + expect([hidden('deny'), hidden('once'), hidden('always')]).toEqual([false, false, true]); + }); + + it('a second waiting request is counted, and answering the first sends that answer and shows the next', async () => { + const r = rig(); + r.add(req()); + r.add(req({ id: 'r2', agent: 'Helper', what: 'delete a folder' })); + r.add(req()); + await settle(0); + expect(r.consent.waiting).toBe(2); + expect(shown('.ft-consent-count')).toBe('Request 1 of 2'); + click(dlg().querySelector('.ft-consent-once')); + await settle(0); + expect(r.answer).toHaveBeenCalledWith('r1', 'once'); + expect(shown('.ft-consent-what')).toBe('It asked to delete a folder.'); + expect(shown('.ft-consent-count')).toBe('Request 1 of 1'); + }); + + it('answering the last request closes the dialog and reports it closed', async () => { + const r = rig(); + r.add(req()); + await settle(0); + click(dlg().querySelector('.ft-consent-deny')); + await settle(0); + expect(r.answer).toHaveBeenCalledWith('r1', 'deny'); + expect(r.consent.isOpen()).toBe(false); + expect(r.consent.waiting).toBe(0); + expect(r.changes).toEqual([true, false]); + }); + + it('a request withdrawn by the engine leaves without an answer being sent', async () => { + const r = rig(); + r.add(req()); + await settle(0); + r.withdraw('r1'); + await settle(0); + expect(r.consent.isOpen()).toBe(false); + expect(r.answer).not.toHaveBeenCalled(); + }); + + it('a request past its expiry time is dropped on its own', async () => { + const r = rig(); + r.add(req({ expires: Date.now() + 1000 })); + await settle(0); + expect(r.consent.isOpen()).toBe(true); + await settle(1000); + expect(r.consent.waiting).toBe(0); + expect(r.consent.isOpen()).toBe(false); + }); + + it('notes are listed line by line and hidden when the next request has none', async () => { + const r = rig(); + r.add(req({ notes: ['first note', 'second note'] })); + r.add(req({ id: 'r2' })); + await settle(0); + const notes = dlg().querySelector('.ft-consent-notes') as HTMLElement; + expect([...notes.children].map((n) => n.textContent)).toEqual(['first note', 'second note']); + expect(notes.hidden).toBe(false); + click(dlg().querySelector('.ft-consent-once')); + await settle(0); + expect(notes.hidden).toBe(true); + }); + + it('says the stored choice was changed outside the app when that happened', async () => { + const r = rig({ changedOutside: true }); + r.add(req()); + await settle(0); + const notice = dlg().querySelector('.ft-consent-notice') as HTMLElement; + expect(notice.hidden).toBe(false); + expect(notice.textContent).toBe('The Outside agents setting was changed outside FormTools, so FormTools asks again.'); + }); + + it('a choice the request does not offer is not sent', async () => { + const r = rig(); + r.add(req({ offers: ['deny', 'once'] })); + await settle(0); + click(dlg().querySelector('.ft-consent-always')); + await settle(0); + expect(r.answer).not.toHaveBeenCalled(); + expect(r.consent.waiting).toBe(1); + }); +}); diff --git a/frontend/tests/unit/ui/support.ts b/frontend/tests/unit/ui/support.ts new file mode 100644 index 0000000..704933a --- /dev/null +++ b/frontend/tests/unit/ui/support.ts @@ -0,0 +1,67 @@ +import { vi } from 'vitest'; +import type { Job } from '../../../src/io/api'; + +export interface Call { url: string; method: string; body: unknown } +export type Answer = unknown | { __status: number; body: unknown }; +export type Route = (call: Call) => Answer; + +export function stubEngine(routes: Record): Call[] { + const calls: Call[] = []; + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = init?.method ?? 'GET'; + const body: unknown = typeof init?.body === 'string' ? JSON.parse(init.body) : null; + const call: Call = { url, method, body }; + calls.push(call); + const path = url.split('?')[0]; + const route = routes[`${method} ${path}`]; + if (!route) return new Response(JSON.stringify({ ok: false, error: `no route ${method} ${path}` }), { status: 404 }); + const a = route(call); + if (a && typeof a === 'object' && '__status' in a) { + const r = a as { __status: number; body: unknown }; + return new Response(JSON.stringify(r.body), { status: r.__status }); + } + return new Response(JSON.stringify(a), { status: 200 }); + }); + return calls; +} + +export const refuse = (status: number, error: string): Answer => ({ __status: status, body: { ok: false, error } }); + +export function job(over: Partial = {}): Job { + return { id: 'j1', kind: 'batch', title: 'Convert', state: 'running', done: 0, total: 4, current: '', errors: [], started: 100, finished: null, ...over } as Job; +} + +export function toastRoot(): HTMLElement { + let root = document.getElementById('toast-root'); + if (!root) { + root = document.createElement('div'); + root.id = 'toast-root'; + document.body.appendChild(root); + } + return root; +} + +export function shownToast(): { text: string; kind: string } | null { + const n = toastRoot().querySelector('.cv-toast:not([hidden])'); + if (!n) return null; + return { text: n.querySelector('.cv-toast-text')?.textContent ?? '', kind: n.dataset.kind ?? '' }; +} + +export function click(node: Element | null): void { + if (!node) throw new Error('nothing to click'); + node.dispatchEvent(new MouseEvent('click', { bubbles: true })); +} + +export function type(node: HTMLInputElement | HTMLSelectElement, value: string, event: 'input' | 'change' = 'input'): void { + node.value = value; + node.dispatchEvent(new Event(event, { bubbles: true })); +} + +export function press(node: Element, key: string): KeyboardEvent { + const e = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + node.dispatchEvent(e); + return e; +} + +export const settle = async (ms = 0): Promise => { await vi.advanceTimersByTimeAsync(ms); }; diff --git a/frontend/tests/unit/ui/tools.test.ts b/frontend/tests/unit/ui/tools.test.ts new file mode 100644 index 0000000..8ed3501 --- /dev/null +++ b/frontend/tests/unit/ui/tools.test.ts @@ -0,0 +1,739 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ActionDef, ActionParam } from '../../../src/io/api'; +import { Jobs } from '../../../src/ui/jobs'; +import { BatchTool } from '../../../src/ui/tools/batch'; +import { fieldFor, readFields } from '../../../src/ui/tools/fields'; +import { InputList } from '../../../src/ui/tools/inputs'; +import { DEFAULT_OUTPUT, OutputPanel } from '../../../src/ui/tools/output'; +import { ToolsPage } from '../../../src/ui/tools/page'; +import { RenameTool } from '../../../src/ui/tools/rename'; +import { ResizeTool } from '../../../src/ui/tools/resize'; +import { click, job, press, refuse, settle, shownToast, stubEngine, toastRoot, type } from './support'; + +const DEFS: ActionDef[] = [ + { id: 'blur', group: 'Adjust', label: 'Blur', params: [{ key: 'radius', label: 'Radius', type: 'float', min: 0, max: 50, default: 2.5 }] }, + { id: 'border', group: 'Adjust', label: 'Border', params: [ + { key: 'width', label: 'Width', type: 'int', min: 1, default: 10 }, + { key: 'color', label: 'Colour', type: 'color', default: '#ff8800' }, + { key: 'inside', label: 'Inside', type: 'bool', default: false }, + ] }, + { id: 'watermark', group: 'Marks', label: 'Text watermark', params: [ + { key: 'text', label: 'Text', type: 'text', default: 'draft' }, + { key: 'corner', label: 'Corner', type: 'choice', default: 'se', options: [['nw', 'Top left'], ['se', 'Bottom right']] }, + ] }, +]; + +const q = (root: ParentNode, sel: string): T => { + const n = root.querySelector(sel); + if (!n) throw new Error(`missing ${sel}`); + return n; +}; + +beforeEach(() => { + vi.useFakeTimers(); + toastRoot(); +}); + +afterEach(async () => { + await vi.advanceTimersByTimeAsync(5000); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe('action fields built from a parameter description', () => { + it('a bool parameter becomes a checkbox that starts at its default and reads back as true or false', () => { + const p: ActionParam = { key: 'inside', label: 'Inside', type: 'bool', default: true }; + const host = document.createElement('div'); + host.appendChild(fieldFor(p, undefined)); + const box = q(host, 'input'); + expect(box.type).toBe('checkbox'); + expect(box.checked).toBe(true); + box.checked = false; + expect(readFields(host)).toEqual({ inside: false }); + }); + + it('a choice parameter lists every option by its label and selects the given value', () => { + const p: ActionParam = { key: 'corner', label: 'Corner', type: 'choice', default: 'nw', options: [['nw', 'Top left'], ['se', 'Bottom right']] }; + const host = document.createElement('div'); + host.appendChild(fieldFor(p, 'se')); + const sel = q(host, 'select'); + expect(Array.from(sel.options).map((o) => o.textContent)).toEqual(['Top left', 'Bottom right']); + expect(sel.value).toBe('se'); + expect(readFields(host)).toEqual({ corner: 'se' }); + }); + + it('an int parameter carries its limits and reads back rounded to a whole number', () => { + const p: ActionParam = { key: 'width', label: 'Width', type: 'int', min: 1, max: 99, default: 10 }; + const host = document.createElement('div'); + host.appendChild(fieldFor(p, undefined)); + const inp = q(host, 'input'); + expect([inp.type, inp.min, inp.max, inp.step, inp.value]).toEqual(['number', '1', '99', '1', '10']); + inp.value = '12.6'; + expect(readFields(host)).toEqual({ width: 13 }); + }); + + it('a float parameter keeps its fraction when read back', () => { + const host = document.createElement('div'); + host.appendChild(fieldFor({ key: 'radius', label: 'Radius', type: 'float', default: 2.5 }, undefined)); + expect(q(host, 'input').step).toBe('0.01'); + q(host, 'input').value = '0.75'; + expect(readFields(host)).toEqual({ radius: 0.75 }); + }); + + it('a label with markup characters is shown as text, not turned into elements', () => { + const host = document.createElement('div'); + host.appendChild(fieldFor({ key: 't', label: 'Bold & co', type: 'text', default: 'a "quoted" ' }, undefined)); + expect(q(host, '.ft-row-label').textContent).toBe('Bold & co'); + expect(host.querySelector('b')).toBeNull(); + expect(q(host, 'input').value).toBe('a "quoted" '); + }); + + it('a path parameter asks for a full path and a colour parameter falls back to black', () => { + const host = document.createElement('div'); + host.appendChild(fieldFor({ key: 'p', label: 'File', type: 'path', default: '' }, undefined)); + host.appendChild(fieldFor({ key: 'c', label: 'Colour', type: 'color', default: '' }, undefined)); + expect(q(host, '[data-key="p"]').placeholder).toBe('Full path'); + expect(readFields(host)).toEqual({ p: '', c: '#000000' }); + }); +}); + +describe('the file list of a tool', () => { + it('starts empty with a hint and no count', () => { + const list = new InputList(() => []); + expect(q(list.root, '.ft-inputs-empty').hidden).toBe(false); + expect(q(list.root, '.ft-panel-count').textContent).toBe(''); + expect(list.value).toEqual([]); + }); + + it('typing a path and pressing Enter adds one row named by the last path part and clears the box', () => { + const list = new InputList(() => []); + const box = q(list.root, '.ft-inputs-path'); + box.value = ' /photos/trip/a.jpg '; + const e = press(box, 'Enter'); + expect(e.defaultPrevented).toBe(true); + expect(list.value).toEqual(['/photos/trip/a.jpg']); + const rows = list.root.querySelectorAll('.ft-inputs-item'); + expect(rows.length).toBe(1); + expect(q(rows[0], '.ft-inputs-name').textContent).toBe('a.jpg'); + expect(rows[0].title).toBe('/photos/trip/a.jpg'); + expect(box.value).toBe(''); + expect(q(list.root, '.ft-panel-count').textContent).toBe('1'); + expect(q(list.root, '.ft-inputs-empty').hidden).toBe(true); + }); + + it('the same path typed twice is listed once, and a blank entry adds nothing', () => { + const list = new InputList(() => []); + const box = q(list.root, '.ft-inputs-path'); + for (const v of ['/a/b.png', '/a/b.png', ' ']) { box.value = v; press(box, 'Enter'); } + expect(list.value).toEqual(['/a/b.png']); + }); + + it('a folder path with a trailing separator and a Windows path are named by their last part', () => { + const list = new InputList(() => []); + list.set(['/photos/trip/', 'C:\\Pictures\\cat.png']); + const names = Array.from(list.root.querySelectorAll('.ft-inputs-name')).map((n) => n.textContent); + expect(names).toEqual(['trip', 'cat.png']); + }); + + it('the selection button replaces the list with what the browser has selected', () => { + const list = new InputList(() => ['/x/1.jpg', '/x/2.jpg', '/x/1.jpg']); + list.set(['/old.png']); + click(q(list.root, '[data-in="selection"]')); + expect(list.value).toEqual(['/x/1.jpg', '/x/2.jpg']); + expect(q(list.root, '.ft-panel-count').textContent).toBe('2'); + }); + + it('removing one row keeps the other rows as the same nodes in the document', () => { + const list = new InputList(() => []); + document.body.appendChild(list.root); + list.set(['/a.png', '/b.png', '/c.png']); + const before = Array.from(list.root.querySelectorAll('.ft-inputs-item')); + click(q(before[1], '[data-remove]')); + const after = Array.from(list.root.querySelectorAll('.ft-inputs-item')); + expect(list.value).toEqual(['/a.png', '/c.png']); + expect(after.length).toBe(2); + expect(after[0]).toBe(before[0]); + expect(after[1]).toBe(before[2]); + expect(after[0].isConnected).toBe(true); + list.root.remove(); + }); + + it('clear empties the list, shows the hint again and tells listeners once', () => { + const list = new InputList(() => []); + list.set(['/a.png']); + const heard = vi.fn(); + list.onChange(heard); + click(q(list.root, '[data-in="clear"]')); + expect(list.value).toEqual([]); + expect(q(list.root, '.ft-inputs-empty').hidden).toBe(false); + expect(heard).toHaveBeenCalledTimes(1); + }); + + it('shows at most 500 rows but keeps every path and counts them all', () => { + const list = new InputList(() => []); + const many = Array.from({ length: 520 }, (_, i) => `/big/${i}.jpg`); + list.set(many); + expect(list.root.querySelectorAll('.ft-inputs-item').length).toBe(500); + expect(list.value.length).toBe(520); + expect(q(list.root, '.ft-panel-count').textContent).toBe('520'); + }); + + it('the sub-folder switch is hidden when the tool does not walk folders and reports its state otherwise', () => { + expect(q(new InputList(() => [], false).root, '.ft-inputs-rec').hidden).toBe(true); + const list = new InputList(() => []); + expect(q(list.root, '.ft-inputs-rec').hidden).toBe(false); + expect(list.recursive).toBe(false); + q(list.root, '.ft-inputs-recursive').checked = true; + expect(list.recursive).toBe(true); + }); +}); + +describe('the output panel', () => { + it('opens on the documented defaults: JPEG at quality 90 into a converted sub-folder, adding a number on clashes', () => { + const o = new OutputPanel(); + expect(o.value).toEqual({ format: 'jpeg', quality: 90, folder: '', subfolder: 'converted', naming: '{name}', overwrite: 'rename', keep_metadata: true, keep_folders: false, keep_dates: false }); + expect(o.value).toEqual(DEFAULT_OUTPUT); + expect(q(o.root, '.ft-o-quality output').textContent).toBe('90'); + }); + + it('what is set is what is read back', () => { + const o = new OutputPanel(); + const next = { format: 'webp', quality: 42, folder: '/out', subfolder: 'small', naming: '{name}_{n:3}', overwrite: 'skip', keep_metadata: false, keep_folders: true, keep_dates: true } as const; + o.set({ ...next }); + expect(o.value).toEqual(next); + expect(q(o.root, '.ft-o-quality output').textContent).toBe('42'); + }); + + it('the quality row hides for formats without a quality setting and returns for those with one', () => { + const o = new OutputPanel(); + const fmt = q(o.root, '[data-o="format"]'); + const row = q(o.root, '.ft-o-quality'); + for (const [f, hidden] of [['png', true], ['tiff', true], ['bmp', true], ['gif', true], ['webp', false], ['avif', false], ['same', false], ['jpeg', false]] as const) { + type(fmt, f); + expect([f, row.hidden]).toEqual([f, hidden]); + } + }); + + it('moving the quality slider updates the number beside it and tells listeners', () => { + const o = new OutputPanel(); + const heard = vi.fn(); + o.onChange(heard); + type(q(o.root, '[data-o="quality"]'), '55'); + expect(q(o.root, '.ft-o-quality output').textContent).toBe('55'); + expect(o.value.quality).toBe(55); + expect(heard).toHaveBeenCalledTimes(1); + }); + + it('an emptied file name falls back to the {name} token and folders are trimmed', () => { + const o = new OutputPanel(); + q(o.root, '[data-o="naming"]').value = ' '; + q(o.root, '[data-o="folder"]').value = ' /out dir '; + expect(o.value.naming).toBe('{name}'); + expect(o.value.folder).toBe('/out dir'); + }); +}); + +describe('the resize tool', () => { + const mount = (): { tool: ResizeTool; jobs: Jobs; done: ReturnType } => { + const jobs = new Jobs(); + const done = vi.fn(); + const tool = new ResizeTool(() => [], jobs, done); + document.body.appendChild(tool.root); + return { tool, jobs, done }; + }; + + it('opens on longest side 2048 px, keeping each file format, into a resized sub-folder', () => { + const { tool } = mount(); + expect(q(tool.root, '.ft-r-mode').value).toBe('longest'); + expect(q(tool.root, '.ft-r-one-label').textContent).toBe('Longest side'); + expect(q(tool.root, '.ft-r-value').value).toBe('2048'); + expect(q(tool.root, '.ft-r-unit').textContent).toBe('px'); + expect(q(tool.root, '.ft-r-one').hidden).toBe(false); + expect(Array.from(tool.root.querySelectorAll('.ft-r-box')).map((n) => n.hidden)).toEqual([true, true]); + expect(tool.output.value.format).toBe('same'); + expect(tool.output.value.subfolder).toBe('resized'); + tool.root.remove(); + }); + + it('choosing percent or megapixels changes the unit shown, and a box mode swaps to width and height', () => { + const { tool } = mount(); + const mode = q(tool.root, '.ft-r-mode'); + type(mode, 'percent', 'change'); + expect(q(tool.root, '.ft-r-unit').textContent).toBe('%'); + type(mode, 'megapixels', 'change'); + expect(q(tool.root, '.ft-r-unit').textContent).toBe('MP'); + expect(q(tool.root, '.ft-r-one-label').textContent).toBe('Megapixels'); + type(mode, 'fill', 'change'); + expect(q(tool.root, '.ft-r-one').hidden).toBe(true); + expect(Array.from(tool.root.querySelectorAll('.ft-r-box')).map((n) => n.hidden)).toEqual([false, false]); + tool.root.remove(); + }); + + it('the 4K preset fills in 3840 by 2160 and switches to fitting inside a box', () => { + const { tool } = mount(); + const chip = Array.from(tool.root.querySelectorAll('.ft-chip')).find((c) => c.textContent?.startsWith('4K')); + expect(chip?.textContent).toBe('4K 3840 x 2160'); + click(chip ?? null); + expect(q(tool.root, '.ft-r-mode').value).toBe('fit'); + expect(q(tool.root, '.ft-r-w').value).toBe('3840'); + expect(q(tool.root, '.ft-r-h').value).toBe('2160'); + expect(q(tool.root, '.ft-r-one').hidden).toBe(true); + tool.root.remove(); + }); + + it('pressing Resize with no files says to add files first and sends nothing', async () => { + const calls = stubEngine({}); + const { tool } = mount(); + click(q(tool.root, '[data-r="run"]')); + await settle(); + expect(calls).toEqual([]); + expect(shownToast()).toEqual({ text: 'Add files or a folder first.', kind: 'error' }); + tool.root.remove(); + }); + + it('pressing Resize sends the files, an auto-orient step, the chosen size and the output settings', async () => { + const calls = stubEngine({ 'POST /api/batch/run': () => job({ state: 'done', done: 2, total: 2 }) }); + const { tool } = mount(); + tool.inputs.set(['/p/a.jpg', '/p/b.jpg']); + type(q(tool.root, '.ft-r-mode'), 'width', 'change'); + q(tool.root, '.ft-r-value').value = '800'; + q(tool.root, '.ft-r-up').checked = true; + q(tool.root, '.ft-r-resample').value = 'bicubic'; + q(tool.inputs.root, '.ft-inputs-recursive').checked = true; + click(q(tool.root, '[data-r="run"]')); + await settle(); + expect(calls.length).toBe(1); + expect(calls[0].url).toBe('/api/batch/run'); + expect(calls[0].body).toEqual({ + inputs: ['/p/a.jpg', '/p/b.jpg'], recursive: true, extensions: [], + actions: [{ id: 'auto-orient', params: {} }, { id: 'resize', params: { mode: 'width', width: 1920, height: 1080, value: 800, upscale: true, resample: 'bicubic' } }], + output: { format: 'same', quality: 90, folder: '', subfolder: 'resized', naming: '{name}', overwrite: 'rename', keep_metadata: true, keep_folders: false, keep_dates: false }, + }); + tool.root.remove(); + }); + + it('while the job runs the button is locked and progress reads done of total, then the count of files when finished', async () => { + let n = 0; + stubEngine({ + 'POST /api/batch/run': () => job({ done: 1, total: 4 }), + 'GET /api/jobs/j1': () => (++n === 1 ? job({ done: 3, total: 4 }) : job({ state: 'done', done: 4, total: 4, errors: [{ path: '/p/x', error: 'bad' }] })), + }); + const { tool, done } = mount(); + tool.inputs.set(['/p']); + const btn = q(tool.root, '[data-r="run"]'); + const state = q(tool.root, '.ft-run-state'); + click(btn); + await settle(); + expect(btn.disabled).toBe(true); + expect(state.textContent).toBe('1 of 4'); + await settle(400); + expect(state.textContent).toBe('3 of 4'); + expect(done).not.toHaveBeenCalled(); + await settle(400); + expect(state.textContent).toBe('Done: 4 files, 1 errors'); + expect(btn.disabled).toBe(false); + expect(done).toHaveBeenCalledTimes(1); + tool.root.remove(); + }); + + it('a refusal from the engine is shown as its sentence and the button is usable again', async () => { + stubEngine({ 'POST /api/batch/run': () => refuse(400, 'The folder /p cannot be read.') }); + const { tool } = mount(); + tool.inputs.set(['/p']); + const btn = q(tool.root, '[data-r="run"]'); + click(btn); + await settle(); + expect(shownToast()).toEqual({ text: 'The folder /p cannot be read.', kind: 'error' }); + expect(btn.disabled).toBe(false); + tool.root.remove(); + }); +}); + +describe('the batch convert tool', () => { + const routes = (extra: Record[0][string]> = {}): Parameters[0] => ({ + 'GET /api/batch/actions': () => ({ actions: DEFS }), + 'GET /api/batch/presets': () => ({ presets: [{ name: 'Web', actions: [{ id: 'border', params: { width: 4, color: '#112233', inside: true } }, { id: 'gone', params: {} }], output: { ...DEFAULT_OUTPUT, format: 'webp', quality: 70 } }] }), + 'GET /api/fs/list': () => refuse(400, 'not a folder'), + 'POST /api/batch/preview': () => refuse(400, 'No preview for this file.'), + ...extra, + }); + const mount = async (): Promise => { + const tool = new BatchTool(() => [], new Jobs(), vi.fn()); + document.body.appendChild(tool.root); + await tool.start(); + return tool; + }; + const add = (tool: BatchTool, id: string): void => type(q(tool.root, '.ft-add-action'), id, 'change'); + + it('lists the actions the engine describes, grouped under the engine group names', async () => { + stubEngine(routes()); + const tool = await mount(); + const groups = Array.from(tool.root.querySelectorAll('.ft-add-action optgroup')); + expect(groups.map((g) => g.label)).toEqual(['Adjust', 'Marks']); + expect(groups.map((g) => Array.from(g.querySelectorAll('option')).map((o) => `${o.value}:${o.textContent}`))).toEqual([['blur:Blur', 'border:Border'], ['watermark:Text watermark']]); + expect(Array.from(q(tool.root, '.ft-presets').options).map((o) => o.textContent)).toEqual(['Choose a preset...', 'Web']); + tool.root.remove(); + }); + + it('asks the engine for its action list only once however often the tool is opened', async () => { + const calls = stubEngine(routes()); + const tool = await mount(); + await tool.start(); + expect(calls.filter((c) => c.url === '/api/batch/actions').length).toBe(1); + tool.root.remove(); + }); + + it('when the engine refuses the action list the refusal is shown as a sentence', async () => { + stubEngine({ 'GET /api/batch/actions': () => refuse(503, 'The batch engine is still starting.') }); + const tool = await mount(); + expect(shownToast()).toEqual({ text: 'The batch engine is still starting.', kind: 'error' }); + expect(tool.root.querySelectorAll('.ft-add-action optgroup').length).toBe(0); + tool.root.remove(); + }); + + it('adding an action builds a card with one field per described parameter at its default', async () => { + stubEngine(routes()); + const tool = await mount(); + expect(q(tool.root, '.ft-cards-empty').hidden).toBe(false); + add(tool, 'border'); + const card = q(tool.root, '.ft-card'); + expect(q(card, '.ft-card-title').textContent).toBe('Border'); + expect(Array.from(card.querySelectorAll('.ft-row-label')).map((n) => n.textContent)).toEqual(['Width', 'Colour', 'Inside']); + expect(q(card, '[data-key="width"]').value).toBe('10'); + expect(q(card, '[data-key="color"]').value).toBe('#ff8800'); + expect(q(card, '[data-key="inside"]').checked).toBe(false); + expect(q(tool.root, '.ft-actions-count').textContent).toBe('1'); + expect(q(tool.root, '.ft-cards-empty').hidden).toBe(true); + expect(q(tool.root, '.ft-add-action').value).toBe(''); + tool.root.remove(); + }); + + it('Convert with no files says to add files first and sends no run request', async () => { + const calls = stubEngine(routes()); + const tool = await mount(); + click(q(tool.root, '[data-b="run"]')); + await settle(); + expect(calls.some((c) => c.url === '/api/batch/run')).toBe(false); + expect(shownToast()).toEqual({ text: 'Add files or a folder first.', kind: 'error' }); + tool.root.remove(); + }); + + it('Convert sends the cards in their shown order with the values typed into them', async () => { + const calls = stubEngine(routes({ 'POST /api/batch/run': () => job({ state: 'done', done: 1, total: 1 }) })); + const tool = await mount(); + tool.inputs.set(['/p/a.png']); + add(tool, 'blur'); + add(tool, 'watermark'); + const cards = tool.root.querySelectorAll('.ft-card'); + q(cards[0], '[data-key="radius"]').value = '7.25'; + q(cards[1], '[data-key="text"]').value = 'proof'; + q(cards[1], '[data-key="corner"]').value = 'nw'; + click(q(cards[1], '[data-card="up"]')); + expect(Array.from(tool.root.querySelectorAll('.ft-card-title')).map((n) => n.textContent)).toEqual(['Text watermark', 'Blur']); + click(q(tool.root, '[data-b="run"]')); + await settle(); + const run = calls.find((c) => c.url === '/api/batch/run'); + expect(run?.body).toEqual({ + inputs: ['/p/a.png'], recursive: false, extensions: [], + actions: [{ id: 'watermark', params: { text: 'proof', corner: 'nw' } }, { id: 'blur', params: { radius: 7.25 } }], + output: DEFAULT_OUTPUT, + }); + expect(q(tool.root, '.ft-run-state').textContent).toBe('Done: 1 files'); + tool.root.remove(); + }); + + it('reordering keeps each card as the same node, and removing a card drops only that one', async () => { + stubEngine(routes()); + const tool = await mount(); + add(tool, 'blur'); + add(tool, 'border'); + const [first, second] = Array.from(tool.root.querySelectorAll('.ft-card')); + click(q(first, '[data-card="down"]')); + const now = Array.from(tool.root.querySelectorAll('.ft-card')); + expect(now[0]).toBe(second); + expect(now[1]).toBe(first); + click(q(second, '[data-card="remove"]')); + const left = Array.from(tool.root.querySelectorAll('.ft-card')); + expect(left).toEqual([first]); + expect(first.isConnected).toBe(true); + expect(q(tool.root, '.ft-actions-count').textContent).toBe('1'); + tool.root.remove(); + }); + + it('choosing a preset builds its known actions with the saved values and applies its output settings', async () => { + stubEngine(routes()); + const tool = await mount(); + add(tool, 'blur'); + type(q(tool.root, '.ft-presets'), 'Web', 'change'); + const cards = tool.root.querySelectorAll('.ft-card'); + expect(cards.length).toBe(1); + expect(q(cards[0], '.ft-card-title').textContent).toBe('Border'); + expect(q(cards[0], '[data-key="width"]').value).toBe('4'); + expect(q(cards[0], '[data-key="color"]').value).toBe('#112233'); + expect(q(cards[0], '[data-key="inside"]').checked).toBe(true); + expect(tool.output.value.format).toBe('webp'); + expect(tool.output.value.quality).toBe(70); + tool.root.remove(); + }); + + it('Check names shows each planned name with a summary of conflicts and skipped files', async () => { + const calls = stubEngine(routes({ + 'POST /api/batch/plan': () => ({ + items: [{ src: '/p/a.png', dst: '/p/converted/a.jpg', conflict: 'none' }, { src: '/p/b.png', dst: '/p/converted/a.jpg', conflict: 'duplicate' }], + skipped: [{ path: '/p/notes.txt', reason: 'not a picture' }], + }), + })); + const tool = await mount(); + tool.inputs.set(['/p']); + expect(q(tool.root, '.ft-plan').hidden).toBe(true); + click(q(tool.root, '[data-b="plan"]')); + await settle(); + expect(calls.find((c) => c.url === '/api/batch/plan')?.body).toEqual({ inputs: ['/p'], recursive: false, extensions: [], output: DEFAULT_OUTPUT, actions: [] }); + expect(q(tool.root, '.ft-plan').hidden).toBe(false); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('2 files, 1 name conflicts, 1 skipped'); + const rows = Array.from(tool.root.querySelectorAll('.ft-plan-row')); + expect(rows.map((r) => [q(r, '.ft-plan-src').textContent, q(r, '.ft-plan-dst').textContent, r.dataset.conflict])).toEqual([['a.png', '/p/converted/a.jpg', 'none'], ['b.png', '/p/converted/a.jpg', 'duplicate']]); + tool.root.remove(); + }); + + it('checking names again patches the same rows, and changing the files hides the stale plan', async () => { + let dst = '/p/converted/a.jpg'; + stubEngine(routes({ 'POST /api/batch/plan': () => ({ items: [{ src: '/p/a.png', dst, conflict: 'none' }], skipped: [] }) })); + const tool = await mount(); + tool.inputs.set(['/p']); + click(q(tool.root, '[data-b="plan"]')); + await settle(); + const row = q(tool.root, '.ft-plan-row'); + dst = '/p/converted/a.webp'; + click(q(tool.root, '[data-b="plan"]')); + await settle(); + expect(q(tool.root, '.ft-plan-row')).toBe(row); + expect(q(row, '.ft-plan-dst').textContent).toBe('/p/converted/a.webp'); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('1 files'); + tool.inputs.set(['/p', '/q']); + expect(q(tool.root, '.ft-plan').hidden).toBe(true); + tool.root.remove(); + }); + + it('with no files the preview box asks for files', async () => { + stubEngine(routes()); + const tool = await mount(); + tool.inputs.set([]); + await settle(400); + expect(q(tool.root, '.ft-preview-msg').textContent).toBe('Add files to see a preview.'); + expect(q(tool.root, '.ft-preview-msg').hidden).toBe(false); + expect(q(tool.root, '.ft-preview-img').hidden).toBe(true); + tool.root.remove(); + }); + + it('a preview refusal is shown in the preview box beside the file name', async () => { + stubEngine(routes()); + const tool = await mount(); + tool.inputs.set(['/p/raw.xyz']); + await settle(400); + expect(q(tool.root, '.ft-preview-name').textContent).toBe('raw.xyz'); + expect(q(tool.root, '.ft-preview-msg').textContent).toBe('No preview for this file.'); + tool.root.remove(); + }); +}); + +describe('the rename tool', () => { + const plan = (items: Array<{ src: string; dst: string; conflict?: string; changed?: boolean }>): { items: unknown[] } => ({ items: items.map((i) => ({ conflict: 'none', changed: i.src !== i.dst, ...i })) }); + const mount = (): { tool: RenameTool; done: ReturnType } => { + const done = vi.fn(); + const tool = new RenameTool(() => [], done); + document.body.appendChild(tool.root); + return { tool, done }; + }; + const add = (tool: RenameTool, id: string): void => type(q(tool.root, '.ft-add-rule'), id, 'change'); + + it('offers the eight rule kinds by name', () => { + const { tool } = mount(); + expect(Array.from(q(tool.root, '.ft-add-rule').options).map((o) => o.textContent)).toEqual([ + 'Add a rule...', 'Find and replace', 'Change case', 'Insert text', 'Remove characters', 'Number', 'Date', 'Tidy spaces and separators', 'Extension']); + tool.root.remove(); + }); + + it('plans with the engine a moment after typing and shows old and new names with a change count', async () => { + const calls = stubEngine({ 'POST /api/rename/plan': () => plan([{ src: '/p/IMG 1.JPG', dst: '/p/img 1.JPG' }, { src: '/p/b.png', dst: '/p/b.png' }]) }); + const { tool } = mount(); + tool.inputs.set(['/p/IMG 1.JPG', '/p/b.png']); + add(tool, 'case'); + expect(calls.length).toBe(0); + await settle(200); + expect(calls.length).toBe(1); + expect(calls[0].body).toEqual({ paths: ['/p/IMG 1.JPG', '/p/b.png'], rules: [{ type: 'case', mode: 'lower' }] }); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('1 of 2 change'); + const rows = Array.from(tool.root.querySelectorAll('.ft-plan-row')); + expect(rows.map((r) => [q(r, '.ft-plan-src').textContent, q(r, '.ft-plan-dst').textContent, r.dataset.changed])).toEqual([['IMG 1.JPG', 'img 1.JPG', 'true'], ['b.png', 'b.png', 'false']]); + expect(q(tool.root, '[data-n="apply"]').disabled).toBe(false); + tool.root.remove(); + }); + + it('several quick edits send one plan request carrying the last values', async () => { + const calls = stubEngine({ 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/a_x.png' }]) }); + const { tool } = mount(); + tool.inputs.set(['/p/a.png']); + add(tool, 'insert'); + const text = q(tool.root, '.ft-card [data-key="text"]'); + type(text, '_'); + await settle(100); + type(text, '_x'); + await settle(200); + expect(calls.length).toBe(1); + expect(calls[0].body).toEqual({ paths: ['/p/a.png'], rules: [{ type: 'insert', text: '_x', position: 'end' }] }); + tool.root.remove(); + }); + + it('a name conflict is counted and Rename stays locked', async () => { + stubEngine({ 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/c.png', conflict: 'duplicate' }, { src: '/p/b.png', dst: '/p/c.png', conflict: 'duplicate' }]) }); + const { tool } = mount(); + tool.inputs.set(['/p/a.png', '/p/b.png']); + await settle(200); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('2 of 2 change, 2 conflicts'); + expect(q(tool.root, '[data-n="apply"]').disabled).toBe(true); + expect(q(tool.root, '.ft-plan-row').dataset.conflict).toBe('duplicate'); + tool.root.remove(); + }); + + it('Rename stays locked when no name would change', async () => { + stubEngine({ 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/a.png' }]) }); + const { tool } = mount(); + tool.inputs.set(['/p/a.png']); + await settle(200); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('0 of 1 change'); + expect(q(tool.root, '[data-n="apply"]').disabled).toBe(true); + tool.root.remove(); + }); + + it('a rule the engine refuses shows the refusal where the count was', async () => { + stubEngine({ 'POST /api/rename/plan': () => refuse(400, 'The regular expression is not valid: missing ).') }); + const { tool } = mount(); + tool.inputs.set(['/p/a.png']); + add(tool, 'replace'); + await settle(200); + expect(q(tool.root, '.ft-plan-count').textContent).toBe('The regular expression is not valid: missing ).'); + tool.root.remove(); + }); + + it('with no files nothing is sent and the plan is empty', async () => { + const calls = stubEngine({}); + const { tool } = mount(); + add(tool, 'trim'); + await settle(200); + expect(calls).toEqual([]); + expect(tool.root.querySelectorAll('.ft-plan-row').length).toBe(0); + expect(q(tool.root, '.ft-plan-count').textContent).toBe(''); + tool.root.remove(); + }); + + it('Rename sends the rules, reports how many items were renamed and lists the files under their new names', async () => { + const calls = stubEngine({ + 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/a_001.png' }]), + 'POST /api/rename/apply': () => ({ ok: true, renamed: 1, undo: 'u-77' }), + }); + const { tool, done } = mount(); + tool.inputs.set(['/p/a.png']); + add(tool, 'counter'); + await settle(200); + const undo = q(tool.root, '[data-n="undo"]'); + expect(undo.disabled).toBe(true); + click(q(tool.root, '[data-n="apply"]')); + await settle(); + expect(calls.find((c) => c.url === '/api/rename/apply')?.body).toEqual({ paths: ['/p/a.png'], rules: [{ type: 'counter', start: 1, step: 1, pad: 3, position: 'end', separator: '_' }] }); + expect(shownToast()).toEqual({ text: 'Renamed 1 item.', kind: 'info' }); + expect(tool.inputs.value).toEqual(['/p/a_001.png']); + expect(undo.disabled).toBe(false); + expect(tool.root.querySelectorAll('.ft-card').length).toBe(0); + expect(done).toHaveBeenCalledTimes(1); + tool.root.remove(); + }); + + it('Undo sends the undo token from the rename and puts the old names back in the list', async () => { + const calls = stubEngine({ + 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/z.png' }, { src: '/p/b.png', dst: '/p/y.png' }]), + 'POST /api/rename/apply': () => ({ ok: true, renamed: 2, undo: 'u-9' }), + 'POST /api/rename/undo': () => ({ ok: true }), + }); + const { tool } = mount(); + tool.inputs.set(['/p/a.png', '/p/b.png']); + await settle(200); + click(q(tool.root, '[data-n="apply"]')); + await settle(); + expect(shownToast()?.text).toBe('Renamed 2 items.'); + expect(tool.inputs.value).toEqual(['/p/z.png', '/p/y.png']); + click(q(tool.root, '[data-n="undo"]')); + await settle(); + expect(calls.find((c) => c.url === '/api/rename/undo')?.body).toEqual({ undo: 'u-9' }); + expect(tool.inputs.value).toEqual(['/p/a.png', '/p/b.png']); + expect(q(tool.root, '[data-n="undo"]').disabled).toBe(true); + expect(shownToast()?.text).toBe('The rename was undone.'); + tool.root.remove(); + }); + + it('a refused rename changes nothing in the list and shows the refusal', async () => { + stubEngine({ + 'POST /api/rename/plan': () => plan([{ src: '/p/a.png', dst: '/p/z.png' }]), + 'POST /api/rename/apply': () => refuse(409, 'A file named z.png already exists.'), + }); + const { tool, done } = mount(); + tool.inputs.set(['/p/a.png']); + await settle(200); + click(q(tool.root, '[data-n="apply"]')); + await settle(); + expect(shownToast()).toEqual({ text: 'A file named z.png already exists.', kind: 'error' }); + expect(tool.inputs.value).toEqual(['/p/a.png']); + expect(q(tool.root, '[data-n="undo"]').disabled).toBe(true); + expect(done).not.toHaveBeenCalled(); + tool.root.remove(); + }); +}); + +describe('the tools page', () => { + const mount = (): { page: ToolsPage; back: ReturnType } => { + stubEngine({ 'GET /api/batch/actions': () => ({ actions: DEFS }), 'GET /api/batch/presets': () => ({ presets: [] }) }); + const back = vi.fn(); + const page = new ToolsPage(() => [], new Jobs(), back, vi.fn()); + document.body.appendChild(page.root); + return { page, back }; + }; + const visible = (page: ToolsPage): string[] => Array.from(page.root.querySelectorAll('.ft-tool-page')).filter((n) => !n.hidden).map((n) => n.dataset.tool ?? ''); + + it('has three tabs named Batch convert, Resize and Rename', () => { + const { page } = mount(); + expect(Array.from(page.root.querySelectorAll('[data-tab]')).map((n) => n.textContent?.trim())).toEqual(['Batch convert', 'Resize', 'Rename']); + page.root.remove(); + }); + + it('clicking a tab shows only that tool and marks the tab', async () => { + const { page } = mount(); + page.show('convert'); + await settle(); + expect(visible(page)).toEqual(['convert']); + click(q(page.root, '[data-tab="rename"]')); + expect(visible(page)).toEqual(['rename']); + expect(page.current).toBe('rename'); + expect(Array.from(page.root.querySelectorAll('[data-tab].is-on')).map((n) => n.dataset.tab)).toEqual(['rename']); + page.root.remove(); + }); + + it('opening a tool with files puts them in that tool only', () => { + const { page } = mount(); + page.show('resize', ['/p/a.jpg']); + expect(page.resize.inputs.value).toEqual(['/p/a.jpg']); + expect(page.batch.inputs.value).toEqual([]); + expect(page.rename.inputs.value).toEqual([]); + page.root.remove(); + }); + + it('the back button and Escape go back, but Escape inside a text box does not', () => { + const { page, back } = mount(); + click(q(page.root, '[data-t="back"]')); + expect(back).toHaveBeenCalledTimes(1); + press(q(page.root, '.ft-tools-body'), 'Escape'); + expect(back).toHaveBeenCalledTimes(2); + press(q(page.resize.root, '.ft-r-value'), 'Escape'); + expect(back).toHaveBeenCalledTimes(2); + page.root.remove(); + }); +}); diff --git a/frontend/tests/unit/ui/views.test.ts b/frontend/tests/unit/ui/views.test.ts new file mode 100644 index 0000000..dd17a1a --- /dev/null +++ b/frontend/tests/unit/ui/views.test.ts @@ -0,0 +1,536 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { EditOp, Entry, Job } from '../../../src/io/api'; +import type { OverlayParams } from '../../../src/io/desk'; +import type { BaseCtx } from '../../../src/overlay/ctx'; +import { mountTimer } from '../../../src/overlay/timer'; +import { Jobs } from '../../../src/ui/jobs'; +import { SaveDialog } from '../../../src/ui/save-dialog'; +import { ChecksumsView } from '../../../src/ui/utilities/checksums'; +import { confirmButton, progressText, trashAll, type UtilDeps } from '../../../src/ui/utilities/common'; +import { click, job, press, refuse, settle, shownToast, stubEngine, toastRoot, type } from './support'; + +const q = (root: ParentNode, sel: string): T => { + const n = root.querySelector(sel); + if (!n) throw new Error(`missing ${sel}`); + return n; +}; +const text = (root: ParentNode, sel: string): string => q(root, sel).textContent ?? ''; + +beforeEach(() => { + vi.useFakeTimers(); + toastRoot(); +}); + +afterEach(async () => { + await vi.advanceTimersByTimeAsync(5000); + vi.useRealTimers(); + vi.unstubAllGlobals(); + for (const n of [...document.body.children]) if (n.id !== 'toast-root') n.remove(); +}); + +describe('the jobs button and panel', () => { + const mount = (): Jobs => { + const jobs = new Jobs(); + document.body.append(jobs.button, jobs.panel); + return jobs; + }; + + it('stays hidden and the panel says there are no jobs until one is tracked', () => { + const jobs = mount(); + expect(jobs.button.hidden).toBe(true); + expect(q(jobs.panel, '.cv-jobs-empty').hidden).toBe(false); + expect(text(jobs.panel, '.cv-jobs-empty')).toBe('No jobs yet.'); + }); + + it('a running job shows how many run and done of total, and its row reads the percentage', () => { + stubEngine({ 'GET /api/jobs/j1': () => job({ done: 1 }) }); + const jobs = mount(); + jobs.track(job({ done: 1, total: 4 })); + expect(jobs.button.hidden).toBe(false); + expect(text(jobs.button, '.ft-st-jobs-text')).toBe('1 running \u00b7 1 of 4'); + expect(text(jobs.panel, '.cv-jobs-pct')).toBe('25%'); + expect(q(jobs.button, 'i').style.getPropertyValue('--p')).toBe('25%'); + }); + + it('polls the engine and, when the job ends, patches the same row to Done and says so once', async () => { + const calls = stubEngine({ 'GET /api/jobs/j1': () => job({ done: 4, state: 'done', finished: 200 }) }); + const jobs = mount(); + jobs.track(job({ done: 1 })); + const row = q(jobs.panel, '.cv-jobs-row'); + await settle(400); + expect(calls.map((c) => c.url)).toEqual(['/api/jobs/j1']); + expect(jobs.panel.querySelectorAll('.cv-jobs-row')).toHaveLength(1); + expect(q(jobs.panel, '.cv-jobs-row')).toBe(row); + expect(text(row, '.cv-jobs-pct')).toBe('Done'); + expect(q(row, '.cv-jobs-stop').disabled).toBe(true); + expect(text(jobs.button, '.ft-st-jobs-text')).toBe('1 job'); + expect(shownToast()).toEqual({ text: 'Convert: done.', kind: 'info' }); + await settle(2000); + expect(calls).toHaveLength(1); + }); + + it('a finished job with errors counts them on the row and in an error message', async () => { + stubEngine({ 'GET /api/jobs/j1': () => job({ done: 4, state: 'done', errors: [{ path: '/a', error: 'x' }, { path: '/b', error: 'y' }] }) }); + const jobs = mount(); + jobs.track(job()); + await settle(400); + expect(text(jobs.panel, '.cv-jobs-pct')).toBe('2 errors'); + expect(shownToast()).toEqual({ text: 'Convert: done, 2 could not be processed.', kind: 'error' }); + }); + + it('a job the engine no longer knows is marked failed with a sentence saying it may have restarted', async () => { + stubEngine({ 'GET /api/jobs/j1': () => refuse(404, 'no such job') }); + const jobs = mount(); + jobs.track(job()); + await settle(400); + expect(text(jobs.panel, '.cv-jobs-pct')).toBe('Failed'); + expect(shownToast()).toEqual({ text: 'Convert failed: the engine no longer knows this job; it may have restarted.', kind: 'error' }); + }); + + it('Stop posts a cancel for that job and the row then reads Stopped', async () => { + const calls = stubEngine({ + 'POST /api/jobs/j1/cancel': () => job({ state: 'cancelled' }), + 'GET /api/jobs/j1': () => job(), + }); + const jobs = mount(); + jobs.track(job()); + click(q(jobs.panel, '.cv-jobs-stop')); + await settle(0); + expect(calls[0]).toMatchObject({ url: '/api/jobs/j1/cancel', method: 'POST' }); + expect(text(jobs.panel, '.cv-jobs-pct')).toBe('Stopped'); + expect(shownToast()?.text).toBe('Convert stopped.'); + }); + + it('lists the newest job first and tells each listener about its own job', () => { + stubEngine({ 'GET /api/jobs/old': () => job({ id: 'old' }), 'GET /api/jobs/new': () => job({ id: 'new' }) }); + const jobs = mount(); + const seen: string[] = []; + jobs.track(job({ id: 'old', title: 'Older', started: 10 }), (j) => seen.push(j.id)); + jobs.track(job({ id: 'new', title: 'Newer', started: 20 })); + expect([...jobs.panel.querySelectorAll('.cv-jobs-name')].map((n) => n.textContent)).toEqual(['Newer', 'Older']); + expect(seen).toEqual(['old']); + expect(text(jobs.button, '.ft-st-jobs-text')).toBe('2 running \u00b7 0 of 4'); + }); + + it('opens the panel from the button and a pointer press elsewhere closes it', () => { + stubEngine({ 'GET /api/jobs/j1': () => job() }); + const jobs = mount(); + jobs.track(job()); + click(jobs.button); + expect(jobs.panel.hidden).toBe(false); + document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true })); + expect(jobs.panel.hidden).toBe(true); + }); +}); + +describe('progress sentences for a utility job', () => { + it('reads done of total while running, or just done when the total is unknown', () => { + expect(progressText(job({ done: 3, total: 8 }), 'files')).toBe('3 of 8 files'); + expect(progressText(job({ done: 7, total: 0 }), 'folders')).toBe('7 folders'); + }); + + it('says Stopped when cancelled, gives the first error when failed, and nothing when done', () => { + expect(progressText(job({ state: 'cancelled' }), 'files')).toBe('Stopped.'); + expect(progressText(job({ state: 'failed', errors: [{ path: '/x', error: 'disk gone' }] }), 'files')).toBe('disk gone'); + expect(progressText(job({ state: 'failed' }), 'files')).toBe('The scan failed.'); + expect(progressText(job({ state: 'done' }), 'files')).toBe(''); + }); +}); + +describe('moving many files to the trash', () => { + it('sends at most 5000 paths per request and adds up what was moved', async () => { + const calls = stubEngine({ 'POST /api/files/trash': (c) => ({ ok: true, trashed: (c.body as { paths: string[] }).paths.length, errors: [] }) }); + const paths = Array.from({ length: 12000 }, (_, i) => `/f/${i}`); + const r = await trashAll(paths); + expect(calls.map((c) => (c.body as { paths: string[] }).paths.length)).toEqual([5000, 5000, 2000]); + expect(r).toEqual({ trashed: 12000, errors: [] }); + }); + + it('a refused later batch marks each of its paths with the refusal, while a refused first batch is thrown', async () => { + let n = 0; + stubEngine({ 'POST /api/files/trash': () => (n++ === 0 ? { ok: true, trashed: 5000, errors: [] } : refuse(500, 'Trash is full')) }); + const r = await trashAll(Array.from({ length: 5002 }, (_, i) => `/f/${i}`)); + expect(r.trashed).toBe(5000); + expect(r.errors).toEqual([{ path: '/f/5000', error: 'Trash is full' }, { path: '/f/5001', error: 'Trash is full' }]); + stubEngine({ 'POST /api/files/trash': () => refuse(403, 'Not allowed here') }); + await expect(trashAll(['/a'])).rejects.toThrow('Not allowed here'); + }); +}); + +describe('a button that asks before it acts', () => { + const mount = (): { btn: HTMLButtonElement; action: ReturnType } => { + const btn = document.createElement('button'); + btn.innerHTML = 'Delete all'; + document.body.append(btn); + const action = vi.fn(); + confirmButton(btn, () => 'Delete 3 files?', action); + return { btn, action }; + }; + + it('the first press asks, the second press acts and the label returns', () => { + const { btn, action } = mount(); + click(btn); + expect(text(btn, '.ft-u-btn-label')).toBe('Delete 3 files?'); + expect(btn.classList.contains('is-danger')).toBe(true); + expect(action).not.toHaveBeenCalled(); + click(btn); + expect(action).toHaveBeenCalledTimes(1); + expect(text(btn, '.ft-u-btn-label')).toBe('Delete all'); + }); + + it('the question goes away after four seconds and a later press asks again', async () => { + const { btn, action } = mount(); + click(btn); + await settle(4000); + expect(text(btn, '.ft-u-btn-label')).toBe('Delete all'); + click(btn); + expect(action).not.toHaveBeenCalled(); + expect(text(btn, '.ft-u-btn-label')).toBe('Delete 3 files?'); + }); +}); + +describe('the save dialog', () => { + const entry = (over: Partial = {}): Entry => ({ name: 'x.jpg', path: '/p/x.jpg', kind: 'file', ext: 'jpg', ...over }) as Entry; + const mount = (): { dlg: SaveDialog; opener: HTMLButtonElement; done: ReturnType void>> } => { + const opener = document.createElement('button'); + document.body.append(opener); + opener.focus(); + const dlg = new SaveDialog(); + document.body.append(dlg.root); + return { dlg, opener, done: vi.fn<(path: string) => void>() }; + }; + const w = (d: SaveDialog): HTMLInputElement => q(d.root, '.ft-w'); + const h = (d: SaveDialog): HTMLInputElement => q(d.root, '.ft-h'); + + it('opens for resizing with the picture size filled in and the width focused, and Escape returns focus to the opener', () => { + const { dlg, opener, done } = mount(); + dlg.open('resize', entry(), { w: 4000, h: 3000 }, [], done); + expect(dlg.isOpen).toBe(true); + expect(text(dlg.root, '.ft-dlg-title')).toBe('Resize'); + expect([w(dlg).value, h(dlg).value]).toEqual(['4000', '3000']); + expect(document.activeElement).toBe(w(dlg)); + press(w(dlg), 'Escape'); + expect(dlg.isOpen).toBe(false); + expect(document.activeElement).toBe(opener); + }); + + it('keeping proportions turns a 4000 by 3000 picture at width 1000 into height 750, and height 300 into width 400', () => { + const { dlg, done } = mount(); + dlg.open('resize', entry(), { w: 4000, h: 3000 }, [], done); + type(w(dlg), '1000'); + expect(h(dlg).value).toBe('750'); + h(dlg).focus(); + type(h(dlg), '300'); + expect(w(dlg).value).toBe('400'); + }); + + it('without kept proportions the other side is left alone', () => { + const { dlg, done } = mount(); + dlg.open('resize', entry(), { w: 4000, h: 3000 }, [], done); + q(dlg.root, '.ft-lock').checked = false; + type(w(dlg), '1000'); + expect(h(dlg).value).toBe('3000'); + }); + + it('a width of zero is refused with a sentence and nothing is sent', async () => { + const calls = stubEngine({}); + const { dlg, done } = mount(); + dlg.open('resize', entry(), { w: 40, h: 30 }, [], done); + type(w(dlg), '0'); + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(calls).toHaveLength(0); + expect(shownToast()).toEqual({ text: 'Width and height must be at least 1 pixel.', kind: 'error' }); + expect(dlg.isOpen).toBe(true); + }); + + it('Save sends the resize step, the quality of a JPEG and a new file, then closes and names the saved file', async () => { + const calls = stubEngine({ 'POST /api/image/edit': () => ({ ok: true, path: '/p/x-1.jpg' }) }); + const { dlg, opener, done } = mount(); + dlg.open('resize', entry(), { w: 4000, h: 3000 }, [], done); + type(w(dlg), '1000'); + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(calls[0].body).toEqual({ path: '/p/x.jpg', ops: [{ op: 'resize', width: 1000, height: 750, resample: 'lanczos' }], out: { quality: 90 }, overwrite: false }); + expect(dlg.isOpen).toBe(false); + expect(document.activeElement).toBe(opener); + expect(shownToast()?.text).toBe('Saved x-1.jpg.'); + expect(done).toHaveBeenCalledWith('/p/x-1.jpg'); + }); + + it('a PNG has no quality row and no quality is sent', async () => { + const calls = stubEngine({ 'POST /api/image/edit': () => ({ ok: true, path: '/p/y-1.png' }) }); + const { dlg, done } = mount(); + dlg.open('save', entry({ name: 'y.png', path: '/p/y.png', ext: 'png' }), { w: 10, h: 10 }, [], done); + expect(q(dlg.root, '.ft-quality-row').hidden).toBe(true); + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(calls[0].body).toEqual({ path: '/p/y.png', ops: [], out: {}, overwrite: false }); + }); + + it('describes a crop in words and sends it unchanged', async () => { + const calls = stubEngine({ 'POST /api/image/edit': () => ({ ok: true, path: '/p/x-crop.jpg' }) }); + const { dlg, done } = mount(); + const crop: EditOp = { op: 'crop', x: 10, y: 20, w: 300, h: 200 }; + dlg.open('crop', entry(), { w: 4000, h: 3000 }, [crop], done); + expect(text(dlg.root, '.ft-dlg-title')).toBe('Save the crop'); + expect(text(dlg.root, '.ft-save-crop')).toBe('Crop to 300 x 200 px from 10, 20.'); + expect(q(dlg.root, '.ft-save-size').hidden).toBe(true); + click(q(dlg.root, '[data-save]')); + await settle(0); + expect((calls[0].body as { ops: EditOp[] }).ops).toEqual([crop]); + }); + + it('replacing the original in a different format is refused before any request', async () => { + const calls = stubEngine({}); + const { dlg, done } = mount(); + dlg.open('save', entry(), { w: 10, h: 10 }, [], done); + type(q(dlg.root, '.ft-format'), 'png', 'change'); + q(dlg.root, 'input[value="replace"]').checked = true; + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(calls).toHaveLength(0); + expect(shownToast()?.text).toBe('Replacing the original keeps its format. Choose "A new file" to change the format.'); + }); + + it('replacing a .jpg as JPEG is allowed and asks the engine to overwrite that path', async () => { + const calls = stubEngine({ 'POST /api/image/edit': () => ({ ok: true, path: '/p/x.jpg' }) }); + const { dlg, done } = mount(); + dlg.open('save', entry(), { w: 10, h: 10 }, [], done); + type(q(dlg.root, '.ft-format'), 'jpeg', 'change'); + q(dlg.root, 'input[value="replace"]').checked = true; + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(calls[0].body).toEqual({ path: '/p/x.jpg', ops: [], out: { format: 'jpeg', quality: 90, path: '/p/x.jpg' }, overwrite: true }); + }); + + it('an engine refusal is shown as its sentence and the dialog stays open with Save usable', async () => { + stubEngine({ 'POST /api/image/edit': () => refuse(409, 'The file is open in another program.') }); + const { dlg, done } = mount(); + dlg.open('save', entry(), { w: 10, h: 10 }, [], done); + click(q(dlg.root, '[data-save]')); + await settle(0); + expect(shownToast()).toEqual({ text: 'The file is open in another program.', kind: 'error' }); + expect(dlg.isOpen).toBe(true); + expect(q(dlg.root, '[data-save]').disabled).toBe(false); + expect(done).not.toHaveBeenCalled(); + }); + + it('clicking the scrim around the dialog closes it', () => { + const { dlg, done } = mount(); + dlg.open('save', entry(), { w: 10, h: 10 }, [], done); + click(dlg.root); + expect(dlg.isOpen).toBe(false); + }); +}); + +describe('the checksums utility', () => { + const A = 'a'.repeat(64); + const B = 'b'.repeat(64); + const mount = (): ChecksumsView => { + const jobs = new Jobs(); + const deps = { jobs, selection: () => [], folders: () => [], folder: () => '/', reveal: vi.fn(), open: vi.fn(), changed: vi.fn() } as unknown as UtilDeps; + const view = new ChecksumsView(deps); + document.body.append(view.root); + return view; + }; + const doneHash = (): Job => job({ + id: 'h1', title: 'Checksums', state: 'done', done: 2, total: 2, + result: { items: [{ path: '/d/one.iso', size: 1024, hashes: { sha256: A, blake3: 'c1' } }, { path: '/d/sub/two.bin', size: 512, hashes: { sha256: B, blake3: 'c2' } }] }, + } as Partial); + + it('with no files it says to add some and sends nothing', async () => { + const calls = stubEngine({}); + const view = mount(); + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect(calls).toHaveLength(0); + expect(shownToast()).toEqual({ text: 'Add files or a folder first.', kind: 'error' }); + }); + + it('with every algorithm unticked it asks for one and sends nothing', async () => { + const calls = stubEngine({}); + const view = mount(); + view.show(['/d/one.iso']); + for (const box of view.root.querySelectorAll('[data-algo]')) box.checked = false; + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect(calls).toHaveLength(0); + expect(shownToast()?.text).toBe('Choose at least one algorithm.'); + }); + + it('Compute sends the files with the two algorithms ticked at the start, SHA-256 and BLAKE3', async () => { + const calls = stubEngine({ 'POST /api/hash': () => doneHash() }); + const view = mount(); + view.show(['/d/one.iso', '/d/sub/two.bin']); + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect(calls[0].body).toEqual({ paths: ['/d/one.iso', '/d/sub/two.bin'], algorithms: ['sha256', 'blake3'] }); + }); + + it('shows each file by name and size with a line per algorithm and a total of 1536 bytes as 1.5 KB', async () => { + stubEngine({ 'POST /api/hash': () => doneHash() }); + const view = mount(); + view.show(['/d']); + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect([...view.root.querySelectorAll('.ft-h-name')].map((n) => n.textContent)).toEqual(['one.iso', 'two.bin']); + expect([...view.root.querySelectorAll('.ft-h-size')].map((n) => n.textContent)).toEqual(['1.0 KB', '512 B']); + expect(text(view.root, '.ft-h-sum')).toBe('2 files \u00b7 1.5 KB'); + const first = view.root.querySelectorAll('.ft-h-item')[0]; + expect([...first.querySelectorAll('.ft-h-algo-name')].map((n) => n.textContent)).toEqual(['SHA-256', 'BLAKE3']); + expect(text(first, '[data-algo-line="sha256"] .ft-h-hex')).toBe(A); + expect(q(view.root, '.ft-h-empty').hidden).toBe(true); + expect(q(view.root, '[data-h="save"]').disabled).toBe(false); + }); + + it('follows a running hash job to its end before showing results', async () => { + const calls = stubEngine({ 'POST /api/hash': () => job({ id: 'h1', done: 0, total: 2 }), 'GET /api/jobs/h1': () => doneHash() }); + const view = mount(); + view.show(['/d']); + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect(text(view.root, '.ft-h-state')).toBe('0 of 2 files'); + expect(q(view.root, '[data-u="run"]').dataset.mode).toBe('stop'); + await settle(400); + expect(calls.map((c) => c.url)).toEqual(['/api/hash', '/api/jobs/h1']); + expect(view.root.querySelectorAll('.ft-h-item')).toHaveLength(2); + expect(q(view.root, '[data-u="run"]').dataset.mode).toBe('run'); + }); + + it('a pasted published checksum is matched ignoring case and a leading algorithm name', async () => { + stubEngine({ 'POST /api/hash': () => doneHash() }); + const view = mount(); + view.show(['/d']); + click(q(view.root, '[data-u="run"]')); + await settle(0); + const cmp = q(view.root, '.ft-h-cmp'); + type(cmp, `SHA256: ${B.toUpperCase()}`); + expect(text(view.root, '.ft-h-cmp-out')).toBe('Matches one file.'); + expect(view.root.querySelectorAll('.ft-h-line.is-match')).toHaveLength(1); + expect(q(view.root, '.ft-h-items').querySelectorAll('.ft-h-item')[1].querySelector('.is-match')).not.toBeNull(); + type(cmp, 'deadbeefdeadbeef'); + expect(text(view.root, '.ft-h-cmp-out')).toBe('No file matches this checksum.'); + type(cmp, 'abc'); + expect(text(view.root, '.ft-h-cmp-out')).toBe(''); + }); + + it('comparing before computing says to compute first', () => { + const view = mount(); + type(q(view.root, '.ft-h-cmp'), A); + expect(text(view.root, '.ft-h-cmp-out')).toBe('Compute first, then compare.'); + }); + + it('a refused hash request is shown as its sentence', async () => { + stubEngine({ 'POST /api/hash': () => refuse(400, 'Unknown algorithm.') }); + const view = mount(); + view.show(['/d']); + click(q(view.root, '[data-u="run"]')); + await settle(0); + expect(shownToast()).toEqual({ text: 'Unknown algorithm.', kind: 'error' }); + }); + + it('Verify with no checksum file path asks for one and sends nothing', async () => { + const calls = stubEngine({}); + const view = mount(); + click(q(view.root, '[data-h="verify"]')); + await settle(0); + expect(calls).toHaveLength(0); + expect(shownToast()?.text).toBe('Type the path of a checksum file.'); + }); + + it('Verify sends the file path, counts good, changed and missing, and lists changed files first', async () => { + const result = { ok: 1, failed: 1, missing: 1, items: [ + { path: 'a.bin', expected: 'e1', actual: 'e1', ok: true, missing: false }, + { path: 'b.bin', expected: 'e2', actual: null, ok: false, missing: true }, + { path: 'c.bin', expected: 'e3', actual: 'f3', ok: false, missing: false }, + ] }; + const calls = stubEngine({ 'POST /api/hash/verify': () => job({ id: 'v1', state: 'done', result } as Partial) }); + const view = mount(); + const box = q(view.root, '.ft-h-sums'); + box.value = '/d/SHA256SUMS'; + press(box, 'Enter'); + await settle(0); + expect(calls[0].body).toEqual({ path: '/d/SHA256SUMS' }); + expect(text(view.root, '.ft-v-state')).toBe('1 good \u00b7 1 changed \u00b7 1 missing'); + expect(text(view.root, '.ft-h-title')).toBe('Verification'); + const rows = [...view.root.querySelectorAll('.ft-v-item')]; + expect(rows.map((r) => [r.dataset.state, r.querySelector('.ft-v-badge')?.textContent])).toEqual([['bad', 'Changed'], ['missing', 'Missing'], ['ok', 'Good']]); + expect(rows[0].querySelector('.ft-v-hex')?.textContent).toBe('expected e3, found f3'); + }); +}); + +describe('the break timer overlay', () => { + const mount = (options: Record): { ctx: BaseCtx; dispose: () => void; root: HTMLElement } => { + const root = document.createElement('div'); + root.id = 'ov-root'; + document.body.append(root); + const ctx = { + params: { tool: 'timer', options } as unknown as OverlayParams, + hint: { set: vi.fn() }, + reduced: false, + finish: vi.fn(async () => undefined), + cancel: vi.fn(async () => undefined), + switchTo: vi.fn(), + } as unknown as BaseCtx; + return { ctx, dispose: mountTimer(ctx), root }; + }; + + it('opens in the overlay root counting down the asked minutes', async () => { + const { root, dispose } = mount({ minutes: 10 }); + expect(root.querySelector('.ov-timer')).not.toBeNull(); + expect(text(root, '.ov-timer-time')).toBe('10:00'); + expect(text(root, '.ov-timer-sub')).toBe('10 min break'); + await settle(61000); + expect(text(root, '.ov-timer-time')).toBe('8:59'); + dispose(); + }); + + it('shows hours with two-digit minutes for 90 minutes', () => { + const { root, dispose } = mount({ minutes: 90 }); + expect(text(root, '.ov-timer-time')).toBe('1:30:00'); + dispose(); + }); + + it('falls back to 5 minutes for a missing value and caps a huge one at 600 minutes', () => { + const a = mount({}); + expect(text(a.root, '.ov-timer-time')).toBe('5:00'); + a.dispose(); + a.root.remove(); + const b = mount({ minutes: 5000 }); + expect(text(b.root, '.ov-timer-time')).toBe('10:00:00'); + b.dispose(); + }); + + it('after the time is up it says so and counts the overtime upward', async () => { + const { root, dispose } = mount({ minutes: 1 }); + await settle(65000); + expect(text(root, '.ov-timer-label')).toBe('Time is up'); + expect(text(root, '.ov-timer-time')).toBe('+0:05'); + expect(text(root, '.ov-timer-sub')).toBe('Overtime'); + expect(q(root, '.ov-timer').classList.contains('is-over')).toBe(true); + dispose(); + }); + + it('Up adds a minute, Down removes one but never below one minute, and Escape cancels', () => { + const { ctx, root, dispose } = mount({ minutes: 2 }); + press(window as unknown as Element, 'ArrowUp'); + expect(text(root, '.ov-timer-time')).toBe('3:00'); + expect(text(root, '.ov-timer-sub')).toBe('3 min break'); + press(window as unknown as Element, 'ArrowDown'); + press(window as unknown as Element, 'ArrowDown'); + press(window as unknown as Element, 'ArrowDown'); + expect(text(root, '.ov-timer-sub')).toBe('1 min break'); + press(window as unknown as Element, 'Escape'); + expect(ctx.cancel).toHaveBeenCalledTimes(1); + dispose(); + }); + + it('closing removes the timer from the overlay root and stops listening for keys', () => { + const { ctx, root, dispose } = mount({ minutes: 2 }); + dispose(); + expect(root.querySelector('.ov-timer')).toBeNull(); + press(window as unknown as Element, 'Escape'); + expect(ctx.cancel).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts new file mode 100644 index 0000000..bba5cdc --- /dev/null +++ b/frontend/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/unit/**/*.test.ts'], + environment: 'happy-dom', + restoreMocks: true, + testTimeout: 20000, + }, +}); diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 3462ec5..3107fe5 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -109,3 +109,10 @@ - Removed from the keep test: `&& codesign -d --entitlements - "$f" 2>/dev/null | grep -q 'com.apple.security.cs.disable-library-validation'` as a condition on every file. Removed: the single `codesign --force --timestamp --options runtime "${sign_args[@]}" --sign "$APPLE_SIGNING_IDENTITY" "$f"` for every file, now split by whether the file is in a framework. - The entry of 2026-11-03 calls this loop formvis's. Any app that copied the loop and ships a one-folder engine from a framework Python has the same fault. - Checked: `bash -n`, and `sign_engine` run against a stand-in engine folder with stub `codesign` and `file` (the framework library signed outside its folder, a PyInstaller-signed library kept, ad hoc and unsigned ones signed, the engine program signed with entitlements, the guard stopping on a framework-bound signature). Not run: a macOS build. Apple's notary service has not seen an engine signed this way, because notarization is off while formcompiler's `signing.macos` is `developer-id`. + +## 2026-11-23 · v0.14.0 · the test runner + +- `test` and `test.bat` · New: `./formtools test [layer] [rest]`. Layers: `unit` (vitest in `frontend`, tests in `frontend/tests/unit/`) and `engine` (pytest on `backend/tests` with the backend venv's Python, run from `backend`). Nothing or `all` runs both and exits 1 when either failed; an unknown layer exits 2 with a sentence. Whatever follows the layer goes to the runner unchanged. +- The script installs nothing. It stops with the command to run when the backend venv or `frontend/node_modules` is missing, and when pytest or httpx is not in the venv (`./formtools install` does not add them; `backend/requirements.txt` holds only what the engine ships with). +- pytest runs with `-q -p no:cacheprovider` so a run leaves no `.pytest_cache` folder in the tree. +- CI: the job `test` runs the two layers one step each; the pytest step that was the last step of the `backend` job moved there. `docs/TESTING.md` holds the rules a test must meet. diff --git a/setup/cli.py b/setup/cli.py index d6d078f..f8c90fd 100644 --- a/setup/cli.py +++ b/setup/cli.py @@ -36,9 +36,9 @@ def read_version(): pass try: with open(os.path.join(ROOT, "frontend", "package.json"), encoding="utf-8") as f: - return json.load(f).get("version") or "0.13.0" + return json.load(f).get("version") or "0.14.0" except (OSError, ValueError): - return "0.13.0" + return "0.14.0" def get(route, **query): diff --git a/setup/mcp_stdio.py b/setup/mcp_stdio.py index 65b90e0..48f5e76 100644 --- a/setup/mcp_stdio.py +++ b/setup/mcp_stdio.py @@ -29,9 +29,9 @@ def read_version(): pass try: with open(os.path.join(ROOT, "frontend", "package.json"), encoding="utf-8") as f: - return json.load(f).get("version") or "0.13.0" + return json.load(f).get("version") or "0.14.0" except (OSError, ValueError): - return "0.13.0" + return "0.14.0" def base(): diff --git a/setup/mcpb/manifest.json b/setup/mcpb/manifest.json index be0a5b9..cb841f2 100644 --- a/setup/mcpb/manifest.json +++ b/setup/mcpb/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.2", "name": "formtools", "display_name": "formtools", - "version": "0.13.0", + "version": "0.14.0", "description": "Browse folders, read picture and media details, batch convert, resize and rename pictures, inspect 3D models, list and safely extract archives, compute checksums and find duplicates, through the formtools engine on this computer.", "long_description": "formtools is the Form family's media and file utility belt. This extension is a stdio bridge to the formtools engine's MCP endpoint on 127.0.0.1. Start the formtools app or run ./formtools boot first; the bridge also tries to start the engine when it can.", "author": { diff --git a/setup/test b/setup/test new file mode 100755 index 0000000..c7eb2e9 --- /dev/null +++ b/setup/test @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +source "$(dirname "$0")/lib.sh" +which="${1:-all}" +[ $# -gt 0 ] && shift +case "$which" in + all|unit|engine) ;; + *) ft_say "unknown test layer: $which (use unit, engine or nothing for all)"; exit 2 ;; +esac +fail=0 +run() { ft_say "$1"; shift; "$@" || fail=1; } +wants() { [ "$which" = all ] || [ "$which" = "$1" ]; } +if wants unit; then + [ -d "$FORMTOOLS_ROOT/frontend/node_modules" ] || ft_die "frontend not installed, run ./formtools install" + cd "$FORMTOOLS_ROOT/frontend" + run "interface logic (vitest)" npx vitest run "$@" +fi +if wants engine; then + py="$FORMTOOLS_ROOT/backend/venv/bin/python" + [ -x "$py" ] || py="$FORMTOOLS_ROOT/backend/venv/Scripts/python.exe" + [ -x "$py" ] || ft_die "backend venv missing, run ./formtools install" + "$py" -c "import pytest, httpx" >/dev/null 2>&1 || ft_die "the engine tests need pytest and httpx: $py -m pip install pytest httpx" + cd "$FORMTOOLS_ROOT/backend" + run "engine (pytest)" "$py" -m pytest tests -q -p no:cacheprovider "$@" +fi +exit "$fail" diff --git a/setup/test.bat b/setup/test.bat new file mode 100644 index 0000000..8be1620 --- /dev/null +++ b/setup/test.bat @@ -0,0 +1,31 @@ +@echo off +setlocal +cd /d "%~dp0.." +set "WHICH=%~1" +if "%WHICH%"=="" set "WHICH=all" +set "REST=%2 %3 %4 %5 %6 %7 %8 %9" +set "FAIL=0" +if /i "%WHICH%"=="all" goto :unit +if /i "%WHICH%"=="unit" goto :unit +if /i "%WHICH%"=="engine" goto :engine +echo [formtools] unknown test layer: %WHICH% (use unit, engine or nothing for all) +exit /b 2 +:unit +if not exist frontend\node_modules ( echo [formtools] error: frontend not installed, run formtools.bat install & exit /b 1 ) +echo [formtools] interface logic (vitest) +pushd frontend +call npx vitest run %REST% +if errorlevel 1 set "FAIL=1" +popd +if /i "%WHICH%"=="unit" exit /b %FAIL% +:engine +set "PY=backend\venv\Scripts\python.exe" +if not exist "%PY%" ( echo [formtools] error: backend venv missing, run formtools.bat install & exit /b 1 ) +"%PY%" -c "import pytest, httpx" >nul 2>nul +if errorlevel 1 ( echo [formtools] error: the engine tests need pytest and httpx: %PY% -m pip install pytest httpx & exit /b 1 ) +echo [formtools] engine (pytest) +pushd backend +venv\Scripts\python.exe -m pytest tests -q -p no:cacheprovider %REST% +if errorlevel 1 set "FAIL=1" +popd +exit /b %FAIL% diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7059f15..844ebe2 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1320,7 +1320,7 @@ dependencies = [ [[package]] name = "formtools" -version = "0.13.0" +version = "0.14.0" dependencies = [ "image", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9f87b96..d58f764 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formtools" -version = "0.13.0" +version = "0.14.0" description = "formtools desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9901af0..6790e16 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormTools", - "version": "0.13.0", + "version": "0.14.0", "identifier": "ai.nodemode.formtools", "build": { "frontendDist": "../frontend/dist"