diff --git a/museoncli/domains/_writes.py b/museoncli/domains/_writes.py index 9d62275..71926f4 100644 --- a/museoncli/domains/_writes.py +++ b/museoncli/domains/_writes.py @@ -23,13 +23,16 @@ Notes = tuple[Any, list[str], list[str]] -def uuid_arg(value: Any, *, flag: str) -> str: +_UUID_LOOKUP = "Look the ID up first with the matching +list or +get command." + + +def uuid_arg(value: Any, *, flag: str, lookup: str | None = None) -> str: try: return str(UUID(str(value))) except (TypeError, ValueError): raise ValueError( f"{flag} must be a canonical UUID (e.g. 72defd40-39ad-40d3-8105-8f23a9a016da), " - f"got {value!r}. Look the ID up first with the matching +list or +get command." + f"got {value!r}. {lookup or _UUID_LOOKUP}" ) from None diff --git a/museoncli/domains/html_documents.py b/museoncli/domains/html_documents.py index 9ed13ad..4d54da6 100644 --- a/museoncli/domains/html_documents.py +++ b/museoncli/domains/html_documents.py @@ -118,6 +118,41 @@ def _library(organization_id: str) -> str: return f"/organizations/{organization_id}/html-documents" +def _id_lookup_hint() -> str: + """Name only the list/get shortcuts this domain actually registers.""" + present = { + spec.shortcut + for spec in specs() + if spec.resource is None and spec.shortcut in {"+list", "+get"} + } + names = [name for name in ("+list", "+get") if name in present] + which = " or ".join(names) if names else "+list" + return f"Look the ID up first with the matching {which} command." + + +def _blank_query() -> None: + from museoncli.main import UsageError + + raise UsageError("--q must be 1-200 characters.", command="html-documents.list") + + +def _folder_argument(value: str) -> str: + """``root`` in any case, or a folder id. Anything else says ``root`` is valid.""" + if value.lower() == "root": + return "root" + try: + return uuid_arg(value, flag="--folder", lookup=_id_lookup_hint()) + except ValueError: + raise ValueError( + "--folder must be the literal root or a canonical UUID " + f"(e.g. {_FOLDER}), got {value!r}. {_id_lookup_hint()}" + ) from None + + +def _folder_id_argument(value: str) -> str: + return uuid_arg(value, flag="--folder-id", lookup=_id_lookup_hint()) + + # -- executors --------------------------------------------------------------- @@ -143,8 +178,8 @@ async def _execute_upload(ctx: CommandContext) -> Any: async def _execute_list(ctx: CommandContext) -> Any: arguments = ctx.arguments folder = arguments.get("folder") - if isinstance(folder, str) and folder != "root": - folder = uuid_arg(folder, flag="--folder") + if isinstance(folder, str) and folder.strip(): + folder = _folder_argument(folder.strip()) params: dict[str, Any] = {} if arguments.get("q"): params["q"] = arguments["q"] @@ -209,7 +244,7 @@ def _build_upload_arguments(args: argparse.Namespace) -> dict[str, Any]: else: payload["filename"] = resolved if payload.get("folder_id"): - payload["folder_id"] = uuid_arg(payload["folder_id"], flag="--folder-id") + payload["folder_id"] = _folder_id_argument(str(payload["folder_id"])) else: payload.pop("folder_id", None) _read_html(Path(str(payload["file"])).expanduser()) @@ -229,21 +264,18 @@ def _build_list_arguments(args: argparse.Namespace) -> dict[str, Any]: query = payload.get("q") if isinstance(query, str): query = query.strip() - if query: - if len(query) > 200: - raise ValueError("--q must be at most 200 characters.") - payload["q"] = query - else: - payload.pop("q", None) + if not query: + _blank_query() + if len(query) > 200: + raise ValueError("--q must be at most 200 characters.") + payload["q"] = query folder = payload.get("folder") if isinstance(folder, str): folder = folder.strip() if not folder: payload.pop("folder", None) - elif folder != "root": - payload["folder"] = uuid_arg(folder, flag="--folder") else: - payload["folder"] = folder + payload["folder"] = _folder_argument(folder) return payload diff --git a/museoncli/main.py b/museoncli/main.py index 6e8470b..f22aedd 100644 --- a/museoncli/main.py +++ b/museoncli/main.py @@ -123,9 +123,27 @@ def cli_outdated_error(response: httpx.Response) -> CliOutdatedError: ) +# The HTML document API answers with {"code": "..."} and no message text. +_HTML_DOCUMENT_CODE_MESSAGES = { + "folder_not_found": "Folder not found", + "folder_name_taken": "A folder with this name already exists", + "document_not_found": "Document not found", + "folder_not_empty": "Move or delete the documents in this folder first.", + "html_too_large": "This HTML file is too large.", + "invalid_filename": "Use a single HTML filename, without a folder path.", + "invalid_html": "The file has no HTML to store.", + "invalid_title": "Enter a title.", + "invalid_folder": "Folder must be root or a folder id.", + "invalid_folder_name": "Enter a folder name.", + "invalid_slug": "Slug is not valid.", + "slug_taken": "A document with this slug already exists.", + "invalid_document": "Document could not be saved.", +} + # Messages for server codes whose body carries no readable text of its own. _SERVER_CODE_MESSAGES = { "organization_workspace_mismatch": ORGANIZATION_WORKSPACE_MISMATCH_MESSAGE, + **_HTML_DOCUMENT_CODE_MESSAGES, } @@ -225,6 +243,13 @@ def main(*, update: dict[str, Any] | None = None) -> None: _ACTIVE_UPDATE.set(update) try: result = asyncio.run(dispatch(args)) + except UsageError as exc: + # Argument checks inside a command (not argparse) are usage errors too. + payload, code = error_envelope(exc, command=exc.command or command) + if deprecations: + payload["warnings"] = deprecations + emit(with_notice(payload, args, update)) + raise SystemExit(code) from None except KeyboardInterrupt: emit( { @@ -1171,12 +1196,47 @@ def exception_detail(exc: Exception) -> Any: return exc.detail if isinstance(exc, ApiRequestError) else str(exc) +def _coded_body(value: Any) -> dict[str, Any] | None: + """A business error ``{"code": ...}``, or one JSON encoding of that object.""" + if isinstance(value, str): + text = value.strip() + if len(text) > 2000 or not (text.startswith("{") and text.endswith("}")): + return None + try: + value = json.loads(text) + except json.JSONDecodeError: + return None + if isinstance(value, dict): + code = value.get("code") + if isinstance(code, str) and code: + return value + return None + + +def _server_business_error(detail: Any) -> dict[str, Any] | None: + """The coded object in an API failure, including one nested encoding of it.""" + coded = _coded_body(detail) + if coded is not None: + return coded + if isinstance(detail, dict): + for key in ("message", "detail", "error"): + coded = _coded_body(detail.get(key)) + if coded is not None: + return coded + return None + + def error_envelope(exc: Exception, *, command: str | None) -> tuple[dict[str, Any], int]: """Render one failure as the JSON error contract and its exit code. ``reason`` and ``detail`` keep their released meaning; ``error`` adds a stable shape: ``code`` (the same category as ``reason``), a readable ``message``, the server's own ``server_code`` when it sent one, ``http_status`` and ``retryable``. + + A body that is only ``{"code": "..."}`` — or one JSON encoding of that object, + which used to be copied into ``message`` — sets ``server_code``. A code with a + known sentence uses that sentence. A body that already has its own message is + left alone. """ reason = reason_from_exception(exc) detail = exception_detail(exc) @@ -1184,10 +1244,21 @@ def error_envelope(exc: Exception, *, command: str | None) -> tuple[dict[str, An error: dict[str, Any] = {"code": reason, "message": message.removeprefix(f"{reason}: ")} if isinstance(exc, ApiRequestError): error["http_status"] = exc.status_code - if isinstance(detail, dict) and isinstance(detail.get("code"), str) and detail["code"]: - error["server_code"] = detail["code"] - if detail["code"] in _SERVER_CODE_MESSAGES and not detail.get("message"): - error["message"] = _SERVER_CODE_MESSAGES[detail["code"]] + coded = _server_business_error(detail) + if coded is not None: + error["server_code"] = coded["code"] + own = coded.get("message") + if isinstance(detail, dict) and detail is not coded: + own = detail.get("message", own) + human_own = isinstance(own, str) and bool(own) and _coded_body(own) is None + # Blank, or a message that is itself the encoded code object. A non-string + # message (validation fields) is neither, so the dumped text stays. + missing_text = own in (None, "") or (isinstance(own, str) and not human_own) + mapped = _SERVER_CODE_MESSAGES.get(coded["code"]) + if human_own and isinstance(detail, str): + error["message"] = own + elif mapped is not None and missing_text: + error["message"] = mapped if isinstance(exc, CliOutdatedError): error["hint"] = exc.detail.get("install_hint") if isinstance(exc, RemovedCommandError): diff --git a/tests/test_html_documents.py b/tests/test_html_documents.py index 07fff7f..78e1a96 100644 --- a/tests/test_html_documents.py +++ b/tests/test_html_documents.py @@ -3,12 +3,17 @@ from __future__ import annotations import json +import sys from pathlib import Path +import httpx import pytest from routes_stub import ORG, Server, body, query, run +import museoncli.main as cli +from museoncli.config import AuthState, Config, OrganizationState from museoncli.domains.html_documents import MAX_HTML_BYTES +from museoncli.main import ApiRequestError, UsageError FOLDER = "72defd40-39ad-40d3-8105-8f23a9a016da" OTHER = "70000000-0000-4000-8000-000000000002" @@ -253,22 +258,109 @@ def test_list_sends_q_and_folder_and_nothing_else(monkeypatch) -> None: def test_list_with_no_filters_sends_no_query(monkeypatch) -> None: server = Server({("GET", LIBRARY): _library({"folders": [], "root_count": 1, "documents": []})}) - run(monkeypatch, server, ["html-documents", "+list", "--q", " ", "--folder", " "]) + run(monkeypatch, server, ["html-documents", "+list", "--folder", " "]) assert query(server.requests[0]) == {} +@pytest.mark.parametrize("blank", ["", " ", "\t", "\n"]) +def test_list_rejects_an_empty_search(monkeypatch, capsys, blank: str) -> None: + server = Server({("GET", LIBRARY): _library({"folders": [], "documents": []})}) + + with pytest.raises(UsageError, match="--q"): + run(monkeypatch, server, ["html-documents", "+list", "--q", blank]) + assert server.requests == [] + + cfg = Config( + api_base_url="https://api.example.test/api/v1", + auth=AuthState(api_key="test-only"), + organization=OrganizationState(id=ORG, name="MuseOn"), + ) + monkeypatch.setattr(cli, "load_config", lambda: cfg) + monkeypatch.setattr(sys, "argv", ["museoncli", "html-documents", "+list", "--q", blank]) + with pytest.raises(SystemExit) as exc_info: + cli.main() + + assert exc_info.value.code == 2 + payload = json.loads(capsys.readouterr().out) + assert payload["reason"] == "usage_error" + assert payload["command"] == "html-documents.list" + assert payload["error"]["code"] == "usage_error" + assert payload["error"]["message"] == "--q must be 1-200 characters." + assert "html-documents +list --help" in payload["error"]["hint"] + + +def test_list_rejects_a_blank_search_from_args_json(monkeypatch) -> None: + server = Server({}) + + with pytest.raises(UsageError, match="--q"): + run( + monkeypatch, + server, + ["html-documents", "+list", "--args-json", json.dumps({"q": " "})], + ) + + assert server.requests == [] + + +@pytest.mark.parametrize("literal", ["root", "ROOT", "Root", "rOoT"]) +def test_list_accepts_root_in_any_case(monkeypatch, literal: str) -> None: + server = Server({("GET", LIBRARY): _library({"folders": [], "root_count": 0, "documents": []})}) + + run(monkeypatch, server, ["html-documents", "+list", "--folder", literal]) + + assert query(server.requests[0]) == {"folder": "root"} + + def test_list_accepts_a_folder_id_and_rejects_anything_else(monkeypatch) -> None: server = Server({("GET", LIBRARY): _library({"folders": [], "root_count": 0, "documents": []})}) run(monkeypatch, server, ["html-documents", "+list", "--folder", FOLDER]) assert query(server.requests[0]) == {"folder": FOLDER} - with pytest.raises(ValueError, match="--folder"): + with pytest.raises(ValueError, match="--folder") as exc_info: run(monkeypatch, server, ["html-documents", "+list", "--folder", "not-a-folder"]) + message = str(exc_info.value) + assert "root" in message + assert "+list" in message + assert "+get" not in message assert len(server.requests) == 1 +def test_upload_folder_id_hint_names_only_list(monkeypatch, tmp_path: Path) -> None: + path = tmp_path / "guide.html" + path.write_text("
Hi
", encoding="utf-8") + server = Server({}) + + with pytest.raises(ValueError, match="--folder-id") as exc_info: + run( + monkeypatch, + server, + [ + "html-documents", + "+upload", + "--file", + str(path), + "--title", + "Notes", + "--folder-id", + "nope", + ], + ) + + message = str(exc_info.value) + assert "+list" in message + assert "+get" not in message + assert server.requests == [] + + +def test_shared_uuid_hint_still_names_list_and_get() -> None: + from museoncli.domains._writes import uuid_arg + + with pytest.raises(ValueError, match=r"\+list or \+get"): + uuid_arg("nope", flag="--id") + + def test_folder_create_posts_the_name_only(monkeypatch) -> None: server = Server( { @@ -331,3 +423,64 @@ def test_install_defaults_dry_run_sends_nothing(monkeypatch) -> None: assert server.requests == [] assert result["data"]["dry_run"] is True + + +def _refused(monkeypatch, answer, argv: list[str]) -> dict: + with pytest.raises(ApiRequestError) as caught: + run(monkeypatch, answer, argv) + payload, _code = cli.error_envelope(caught.value, command="html-documents.list") + return payload + + +def test_folder_not_found_is_a_sentence_and_a_server_code(monkeypatch, tmp_path: Path) -> None: + """The API returns {"detail": {"code": ...}} and no message. 2.3.0 printed that object.""" + path = tmp_path / "guide.html" + path.write_text("Hi
", encoding="utf-8") + + def answer(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 404, + json={ + "detail": {"code": "folder_not_found"}, + "error": { + "code": "folder_not_found", + "message": "{'code': 'folder_not_found'}", + "retryable": False, + }, + }, + ) + + payload = _refused( + monkeypatch, + answer, + [ + "html-documents", + "+upload", + "--file", + str(path), + "--title", + "Notes", + "--folder-id", + FOLDER, + ], + ) + + assert payload["reason"] == "not_found" + assert payload["error"]["server_code"] == "folder_not_found" + assert payload["error"]["message"] == "Folder not found" + assert payload["error"]["http_status"] == 404 + assert "folder_not_found" not in payload["error"]["message"] + + +def test_a_json_encoded_folder_name_taken_body_is_decoded(monkeypatch) -> None: + def answer(request: httpx.Request) -> httpx.Response: + return httpx.Response(409, json={"detail": json.dumps({"code": "folder_name_taken"})}) + + payload = _refused( + monkeypatch, answer, ["html-documents", "folder", "+create", "--name", "Guides"] + ) + + assert payload["reason"] == "conflict" + assert payload["error"]["server_code"] == "folder_name_taken" + assert payload["error"]["message"] == "A folder with this name already exists" + assert payload["detail"] == '{"code": "folder_name_taken"}' diff --git a/tests/test_output_contract.py b/tests/test_output_contract.py index d67faaf..e5e1501 100644 --- a/tests/test_output_contract.py +++ b/tests/test_output_contract.py @@ -65,6 +65,52 @@ def test_failures_share_one_envelope_and_a_meaningful_exit_code( assert payload["error"]["message"] +def test_a_validation_body_keeps_its_fields_in_the_message() -> None: + detail = { + "code": "invalid_enum", + "field": "payload.category", + "received": "EDUCATION", + "suggested_values": ["LEARNING_PLATFORMS"], + } + payload, _code = main_module.error_envelope(ApiRequestError(422, detail), command="media.get") + + assert payload["error"]["server_code"] == "invalid_enum" + assert "payload.category" in payload["error"]["message"] + assert payload["detail"] == detail + + +def test_a_code_only_body_keeps_its_message_until_the_code_has_a_sentence() -> None: + """Other commands that already show a JSON code object stay on that text.""" + unknown = ApiRequestError(404, {"code": "campaign_missing"}) + payload, _code = main_module.error_envelope(unknown, command="campaign.get") + + assert payload["error"]["server_code"] == "campaign_missing" + assert payload["error"]["message"] == '{"code": "campaign_missing"}' + assert payload["detail"] == {"code": "campaign_missing"} + + +def test_an_encoded_server_body_surfaces_its_code_and_its_own_message() -> None: + raw = '{"code": "version_conflict", "message": "Video version conflict"}' + payload, code = main_module.error_envelope(ApiRequestError(409, raw), command="media.get") + + assert code == 5 + assert payload["detail"] == raw + assert payload["error"]["server_code"] == "version_conflict" + assert payload["error"]["message"] == "Video version conflict" + + +def test_a_message_that_is_only_an_encoded_code_uses_the_known_sentence() -> None: + detail = {"message": json.dumps({"code": "folder_not_found"})} + payload, code = main_module.error_envelope( + ApiRequestError(404, detail), command="html-documents.upload" + ) + + assert code == 3 + assert payload["error"]["server_code"] == "folder_not_found" + assert payload["error"]["message"] == "Folder not found" + assert payload["detail"] == detail + + def test_usage_errors_are_json_on_stdout_with_exit_code_2(monkeypatch, capsys) -> None: monkeypatch.setattr(sys, "argv", ["museoncli", "hireaicreator", "video", "+get", "--bogus", "1"]) with pytest.raises(SystemExit) as exc_info: