diff --git a/CHANGELOG.md b/CHANGELOG.md index bd85bfe..ad5911d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.143.0 (2026-11-23) + +- **Fixed: `write_world_file(include_hidden=False)` could carry a hidden element.** 0.142.0 made the package's reader refuse a file nested more than 200 deep, and the writer of a world file took that refusal for "this file is no element": a hidden element whose file was nested that deep travelled in a share, whole and with its author fields, where 0.141.0 had left it out. The same was true in every earlier version for an element file holding an integer of more than 4,300 digits. Now a file the reader refuses stops the write: `write_world_file` and `world_file_bytes` raise `ValueError` naming the file and why, and nothing is written, whenever they would have had to read that file, to leave out the hidden (`include_hidden=False`) or to take out author fields (the default). A copy that leaves nothing out (`include_hidden=True, include_author_fields=True`) reads no element file and still carries every one byte for byte. Text that is no JSON at all is no element to any reader and travels as it is, as before. If you share world files from folders you did not write yourself, upgrade. +- **A number that is not finite makes its file unreadable.** `1e400` in an element file read as infinity, which no writer of this package can write back and a JavaScript reader serves as `null`; `NaN`, `Infinity` and `-Infinity`, which are no JSON, were read as floats by the Kanka and LegendKeeper doors. The one reader for text the package did not write now refuses all of them with a plain `ValueError` (`a number too large to read`, `NaN is not JSON`), so `read_folder` skips such a file with that reason, the doctor lists it under `unread`, and the Kanka door skips it with a note instead of stopping with an error at the write. A finite number of any size reads as before. +- Not changed: an integer of up to 4,300 digits is read exactly, as Python reads it. The npm SDK's Kanka door skips a file holding an integer past 2^53, which a JavaScript number rounds: the one input on which the two doors differ. + ## 0.142.0 (2026-11-23) - **The doctor names what it could not read.** On a folder, `Report.unread` (and `unread` in `--json`, after `written`) lists each file the folder reader did not read as an element, with why: a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. The prose report puts the list first, and any entry makes the exit code 1. Until now the doctor said nothing: with one element file cut off mid-write it reported the other elements as the whole world and listed every link to the unread one under "a link to an element that is not there". A dot-prefixed file is not listed. The API door's list is always empty. diff --git a/README.md b/README.md index e21e42c..a15d514 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ world = read_world_file("moppetopia.owworld") world.to_folder("moppetopia-copy") ``` -`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. +`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. An element file the writer must read and cannot hold (nested more than 200 deep, or holding a number that is not finite or an integer of more than 4,300 digits) stops the write with a `ValueError` naming it: whether it is hidden cannot be told, and nothing is carried by guess. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. To send a folder's edits back, keep a copy exported before you edited, then push the difference: @@ -253,7 +253,7 @@ for finding in report.findings: It looks for links to elements that are not there, Events that end before they start, elements with no links in or out, two elements of one type whose names collide once case, character width, spacing and punctuation are folded (a name shared across types, such as a Location and its Pin, is not one), stubs never filled (a known-of element older than `--days`, or an element with no text in any of its type's text fields, on every type but map, marker, pin and relation), and a charter Law untouched after `--changes` changes in the feed. On a folder it also checks `world.json`: a `format_version` older than this package's (flag 9), and an `api_key` in a `world.json` that git tracks (flag 10). On both doors it reads the world's own house rules (flag 11, the checks profile: `x_checks_rules` on the world's Charter, the newest Law with supertype Charter that carries the mark `x_charter_of`, applied by `onlyworlds.apply_checks`) and names every element a rule finds short, with each rule's scoped and short counts, and every rule it cannot apply, with why; an older marked Charter is a finding, its rules not applied; a Law with supertype Charter and no mark is lore, not a Charter and not a finding, and its rules are never applied. Flag 14 names a marked Guide or Domain whose links name an element that is not in the world or a hidden one (every other reader is served the Guide or Domain without it; not through a guest key, and the hidden half only through a key that is served hidden elements). On a spine world (one where an element carries an `x_spine_` key), flag 13 reads each element with `read_spine_element` and names an off-list supertype on a listed type, every value the reader drops and a probe not in the probe form; then, on a source world, it checks that each row (an Object, Construct, Location or Law of a listed kind, the Charter too) is kept by exactly one Seat (a Title with supertype `Seat`, through its field for the row's type; any other Title neither owns nor counts), that every `x_spine_depends_on` id is in the world (not through a guest key), that a `legacy` or `provenance` row has an Event with supertype `Retirement` that names it in `x_spine_retires` and links it through its typed field where the type has one (`objects`, `constructs`, `locations`; an Event has no `laws` field, so a Law's retirement is attributed by the key alone; only through a key that sees every element, hidden ones too), that no row is still at `gone` (its retirement is unfinished), and that no two rows of one row type share a name once trimmed and folded for case (a Seat or any other element is outside that rule). Whether a probe passes and `x_spine_probed` are not checked, and the report says so. A projection (a public world built from a spine, each row naming its keeping Seat in `x_spine_owner`) is marked on its World with `x_spine_projection`, `{source, at}`: `source` the projected-from world's id as a string, a UUID that is no element's id in this world, and `at` the ISO 8601 time of the last rebuild, which must parse; each is a finding on the world otherwise. On a projection only the projection's own checks run: every row must carry `x_spine_owner` (the keeping Seat's name in the source, which need match nothing in the projection) and no element may be hidden; the source's checks do not run there, and the report names each. On an unmarked world `x_spine_owner` is a finding (the projection's third check), and a malformed mark is a finding on the world, which is then read as unmarked. Each check says how much it could compare, and one it cannot run (a folder has no change feed; nothing records whether a message was read) is listed with the reason, never counted as clean. A finding on a message or a room thing (supertype Message, Board, Work item, Spec, Heart, Vote or Sitting) is marked `"kind": "message"` and listed last, outside the count of things to look at. `--json` prints the same report for a tool, and `--packet` prints the findings as work packets (the `packet` extension profile: a Relation with supertype `Work item`, its elements with a reason each under `x_packet_elements`, a JSON array, empty when clean) for a tool that lands them in a world or a parlor. The exit code is 0 when there is nothing to look at, 1 when there is (a message finding too), 2 when nothing could be read. -On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed. +On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is nested more than 200 deep or holds a number that is not finite, is not an object or has no `id`, a second file of one id, a directory that is no type's. Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed. The API door reads the key from `OW_API_KEY` and the PIN from `OW_API_PIN`, or from the toolkit's `ONLYWORLDS_API_KEY` and `ONLYWORLDS_API_PIN` when those are not set. diff --git a/src/onlyworlds/_outside_json.py b/src/onlyworlds/_outside_json.py index 86d4ec4..da4e21a 100644 --- a/src/onlyworlds/_outside_json.py +++ b/src/onlyworlds/_outside_json.py @@ -1,6 +1,6 @@ """``json.loads`` for text this package did not write: a world folder's file, an archive, another tool's export. -Two inputs that are JSON by the grammar make ``json.loads`` do something its callers do not expect. +Three inputs make ``json.loads`` do something its callers do not expect. A value nested very deep: where the interpreter's own limit is met first, ``json.loads`` raises ``RecursionError``, which is no ``ValueError``, so every reader that catches "not JSON" let it through as @@ -10,12 +10,18 @@ An integer of more than 4,300 digits: a plain ``ValueError`` whose message advises a Python setting. -Here both are a ``ValueError`` in plain words, so a caller's ``except ValueError`` reads either as a file -it cannot read, and says why.""" +A number that is not finite: ``1e400`` reads as infinity, and ``NaN``, ``Infinity`` and ``-Infinity``, which +are no JSON, are read as floats. No writer of this package can write such a value back, and a JavaScript +reader serves it as ``null``. + +Here each is a ``ValueError`` in plain words that is no ``json.JSONDecodeError``, so a caller's +``except ValueError`` reads it as a file it cannot read, and says why; a caller that must tell text that is +no JSON from JSON this reader refuses catches the decode error first.""" from __future__ import annotations import json +import math import sys from typing import Any @@ -26,6 +32,17 @@ _TOO_DEEP = f"nested more than {MAX_DEPTH} deep" +def _float(text: str) -> float: + value = float(text) + if not math.isfinite(value): + raise ValueError("a number too large to read") + return value + + +def _constant(token: str) -> Any: + raise ValueError(f"{token} is not JSON") + + def _int(text: str) -> int: limit = sys.get_int_max_str_digits() if limit and len(text.lstrip("-")) > limit: @@ -51,8 +68,10 @@ def _too_deep(value: Any) -> bool: def loads(text: str, **kwargs: Any) -> Any: - """``json.loads(text, **kwargs)``, with the two cases above raised as ``ValueError``.""" + """``json.loads(text, **kwargs)``, with the cases above raised as ``ValueError``.""" kwargs.setdefault("parse_int", _int) + kwargs.setdefault("parse_float", _float) + kwargs.setdefault("parse_constant", _constant) try: value = json.loads(text, **kwargs) except RecursionError: diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 193f98e..5a6bb17 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.142.0" +__version__ = "0.143.0" diff --git a/src/onlyworlds/worldfile.py b/src/onlyworlds/worldfile.py index 59bd632..8613002 100644 --- a/src/onlyworlds/worldfile.py +++ b/src/onlyworlds/worldfile.py @@ -59,6 +59,7 @@ from __future__ import annotations import io +import json import os import re import shutil @@ -835,17 +836,34 @@ def _default_top(world: Mapping[str, Any]) -> str: return f"{slugify(name if isinstance(name, str) else None) or 'world'}-{str(world['id'])[:8]}" -def _hidden_element_file(rel: str, src: Path) -> bool: - """An element file (a ``.json`` file directly in a type folder of ``elements/`` or legacy ``spatial/``) - whose JSON object carries the hidden mark at the top level (``folder.is_hidden``). A file anywhere - else, or that is not a JSON object, is not an element and is carried as it is, as ever.""" +def _element_body(rel: str, src: Path, to: str) -> Any: + """What an element file holds (a ``.json`` file directly in a type folder of ``elements/`` or legacy + ``spatial/``), for a writer that must read it ``to`` leave something out. None for a file anywhere else, + or one that is not UTF-8 JSON: no reader takes that as an element, and it is carried as it is, as ever. + + A file that is JSON this package's reader refuses (nested past its depth, a number it cannot hold) raises + ``ValueError``: what it holds cannot be read, so the writer leaves nothing in by guess, as with a records + manifest it cannot read (OW-8).""" segs = rel.split("/") if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): - return False + return None try: - body = _outside_json.loads(src.read_bytes().decode("utf-8-sig")) - except (UnicodeDecodeError, ValueError): - return False + return _outside_json.loads(src.read_bytes().decode("utf-8-sig")) + except (UnicodeDecodeError, json.JSONDecodeError): + return None + except ValueError as exc: + raise ValueError( + f"{src} cannot be read ({exc}), so the writer cannot {to} and carries nothing by guess. Fix or " + "remove the file, or pass include_hidden=True and include_author_fields=True to carry every file " + "as it is." + ) from None + + +def _hidden_element_file(rel: str, src: Path) -> bool: + """An element file whose JSON object carries the hidden mark at the top level (``folder.is_hidden``). + A file that is not an element file, or not a JSON object, is carried as it is, as ever; one the reader + refuses raises (``_element_body``).""" + body = _element_body(rel, src, "tell whether it is hidden") return isinstance(body, dict) and is_hidden(body) @@ -859,14 +877,9 @@ def _without_author_fields(rel: str, src: Path) -> bytes | None: as the TypeScript writer reads one) without its author fields, in the folder's own form (``_jsonfmt.encode``: two-space indent, a trailing newline, the other keys in their order), or None when it holds none of them or is not a JSON object: then it travels byte for byte. Only - top-level keys go; an ``x_*`` value that holds one of the names is the extension's, and stays.""" - segs = rel.split("/") - if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): - return None - try: - body = _outside_json.loads(src.read_bytes().decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant) - except ValueError: # not UTF-8, or not JSON - return None + top-level keys go; an ``x_*`` value that holds one of the names is the extension's, and stays. + A file the reader refuses raises (``_element_body``): its author fields cannot be told from its bytes.""" + body = _element_body(rel, src, "take out its author fields") if not isinstance(body, dict) or not any(k in body for k in _AUTHOR_FIELDS): return None return encode({k: v for k, v in body.items() if k not in _AUTHOR_FIELDS}) diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py index 30abd64..e546f8a 100644 --- a/tests/test_outside_json.py +++ b/tests/test_outside_json.py @@ -1,17 +1,23 @@ """Text this package did not write (a folder's file, an archive, another tool's export) is parsed through -``_outside_json.loads``: two inputs that are JSON by the grammar must come back as a ``ValueError`` a reader -catches, never a traceback. And every ``json.loads`` in the package is either that one or named here.""" +``_outside_json.loads``: JSON it cannot hold as written (nested past its depth, an integer past Python's +digit limit, a number that is not finite) must come back as a ``ValueError`` a reader catches, never a +traceback and never a value the file does not hold. A writer that must read a file to leave something out +refuses to write when the reader refuses the file. And every ``json.loads`` in the package is either that +one or named here.""" from __future__ import annotations import ast import json +import zipfile from pathlib import Path import pytest from onlyworlds import _outside_json, read_folder, write_folder from onlyworlds.folder import FORMAT_VERSION +from onlyworlds.kanka import import_kanka +from onlyworlds.worldfile import read_world_file, world_file_bytes, write_world_file SRC = Path(__file__).resolve().parent.parent / "src" / "onlyworlds" DEEP = "[" * 100_000 + "]" * 100_000 @@ -19,7 +25,12 @@ def test_what_json_reads_it_reads_the_same() -> None: - for text in ('{"a": [1, 2.5, -3, 1e400, "x", null, true]}', "12345678901234567890", "-" + "7" * 4300, "[[[[1]]]]"): + for text in ( + '{"a": [1, 2.5, -3, 1.7976931348623157e308, "x", null, true]}', + "12345678901234567890", + "-" + "7" * 4300, + "[[[[1]]]]", + ): assert _outside_json.loads(text) == json.loads(text) assert _outside_json.loads("1", parse_int=float) == 1.0 @@ -32,6 +43,11 @@ def test_what_json_reads_it_reads_the_same() -> None: (LONG, "a number of more than 4300 digits"), ("-" + LONG, "a number of more than 4300 digits"), ('{"a": [' + LONG + "]}", "a number of more than 4300 digits"), + ("1e400", "a number too large to read"), + ('{"a": [1, {"b": -1e999}]}', "a number too large to read"), + ('{"a": NaN}', "NaN is not JSON"), + ("[Infinity]", "Infinity is not JSON"), + ("-Infinity", "-Infinity is not JSON"), ], ) def test_too_deep_and_too_long_are_value_errors_in_plain_words(text: str, why: str) -> None: @@ -63,7 +79,12 @@ def test_text_that_is_not_json_is_still_a_decode_error() -> None: @pytest.mark.parametrize( - ("value", "why"), [(DEEP, "nested more than 200 deep"), (LONG, "a number of more than 4300 digits")] + ("value", "why"), + [ + (DEEP, "nested more than 200 deep"), + (LONG, "a number of more than 4300 digits"), + ("1e400", "a number too large to read"), + ], ) def test_the_folder_reader_skips_such_a_file_with_the_reason(tmp_path: Path, value: str, why: str) -> None: eid = "l0000000-0000-7000-8000-000000000001" @@ -106,4 +127,119 @@ def calls(path: Path, module: str) -> int: assert len(files) > 40 # the search saw the package assert {p.name: calls(p, "json") for p in files if calls(p, "json")} == NAMED used = {p.name: calls(p, "_outside_json") for p in files if calls(p, "_outside_json")} - assert used == {"folder.py": 1, "kanka.py": 1, "legendkeeper.py": 2, "lint.py": 1, "worldfile.py": 4} + assert used == {"folder.py": 1, "kanka.py": 1, "legendkeeper.py": 2, "lint.py": 1, "worldfile.py": 3} + + +# --- a writer that must read a file to leave something out ------------------------------------------------ + +#: What stands where a key's value goes in a hidden element's file, and whether the reader holds the file. +REFUSED = { + "nested 201 deep": "[" * 200 + "]" * 200, + "nested 100,000 deep": DEEP, + "an integer of 4,301 digits": LONG, + "a number past the largest double": "1e400", + "NaN": "NaN", +} + + +def _folder_with_hidden(root: Path, planted: str) -> tuple[Path, bytes]: + """A folder of two elements; the second is hidden, names who changed it, and holds ``planted``.""" + world = {"id": "w0000000-0000-7000-8000-000000000000", "name": "W", "format_version": FORMAT_VERSION} + write_folder(root, world, {"character": [{"id": "c-1", "name": "Bo"}]}) + secret = root / "elements" / "character" / "cy--c-2.json" + data = ('{"id": "c-2", "name": "Cy", "hidden": true, "changed_by": "m-1", "x": ' + planted + "}").encode() + secret.write_bytes(data) + return secret, data + + +@pytest.mark.parametrize("planted", REFUSED.values(), ids=REFUSED.keys()) +def test_a_share_is_refused_when_a_file_it_must_read_cannot_be_held(tmp_path: Path, planted: str) -> None: + """0.142.0 carried such a hidden element into a share with its author fields: the reader refused the file, + and the writer took the refusal for "not an element".""" + secret, data = _folder_with_hidden(tmp_path / "w", planted) + out = tmp_path / "share.owworld" + # A share, a plain copy (author fields left out by default), and the hidden mark alone. + for hidden, authors in ((False, False), (True, False), (False, True)): + with pytest.raises(ValueError, match="carries nothing by guess") as err: + write_world_file(tmp_path / "w", out, include_hidden=hidden, include_author_fields=authors) + assert not isinstance(err.value, json.JSONDecodeError) + assert str(secret) in str(err.value) and not out.exists() + # A copy that leaves nothing out reads nothing, and carries the file byte for byte. + whole = read_world_file(world_file_bytes(tmp_path / "w", include_author_fields=True)).entries + assert whole["elements/character/cy--c-2.json"] == data + + +def test_a_share_leaves_out_a_hidden_element_at_the_depth_line_and_carries_text_that_is_no_json(tmp_path: Path) -> None: + secret, _ = _folder_with_hidden(tmp_path / "w", "[" * 199 + "]" * 199) + left: list[str] = [] + share = read_world_file(world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=left)).entries + assert left == ["elements/character/cy--c-2.json"] and "elements/character/cy--c-2.json" not in share + # Text that is no JSON is no element to any reader: carried as it is, as ever. + secret.write_bytes(b'{"id": "c-2", "hidden": true, ') + left = [] + share = read_world_file(world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=left)).entries + assert left == [] and share["elements/character/cy--c-2.json"] == b'{"id": "c-2", "hidden": true, ' + + +# --- the Kanka door ---------------------------------------------------------------------------------------- + +KANKA = Path(__file__).resolve().parent / "fixtures" / "kanka" / "quay-export-world_20261025_011029.zip" +ENTITY = "characters/your-character-name_10074596.json" + + +def _export_with(tmp_path: Path, name: str, change: str | None) -> Path: + """The export with ``change`` put in the entity's object as a new key's value; None cuts its last brace.""" + out = tmp_path / f"{name}.zip" + with zipfile.ZipFile(KANKA) as src, zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as dst: + for info in src.infolist(): + data = src.read(info.filename) + if info.filename == ENTITY: + text = data.decode("utf-8").rstrip() + assert text.endswith("}") + data = (text[:-1] if change is None else text[:-1] + ',"x_planted":' + change + "}").encode() + dst.writestr(info.filename, data) + return out + + +def _door(path: Path) -> tuple[dict[str, int], list[str]]: + """What the door would write, by type, and its notes.""" + report = import_kanka(path, None, plan_only=True) + return dict(report.counts), list(report.notes) + + +#: [the planted value, the error class the note names, or None when the file is read] +KANKA_CASES: dict[str, tuple[str, str | None]] = { + "nested 200 deep, the line": ("[" * 199 + "]" * 199, None), + "nested 201 deep, one past it": ("[" * 200 + "]" * 200, "ValueError"), + "nested 100,000 deep": (DEEP, "ValueError"), + "an integer of 4,301 digits": (LONG, "ValueError"), + "a number past the largest double": ("1e400", "ValueError"), + "NaN": ("NaN", "ValueError"), + "-Infinity": ("-Infinity", "ValueError"), + "2^53 - 1": ("9007199254740991", None), + # The one difference from the npm SDK's door, which skips these two: Python holds the integer exactly. + "2^53 + 1": ("9007199254740993", None), + "an integer of 4,300 digits": ("9" * 4300, None), +} + + +def test_the_kanka_door_skips_a_file_it_cannot_hold_with_a_note_as_one_that_is_no_json(tmp_path: Path) -> None: + whole = _door(KANKA) + broken = _door(_export_with(tmp_path, "broken", None)) + assert [n for n in broken[1] if n.startswith(ENTITY)] == [f"{ENTITY}: not readable JSON (JSONDecodeError); skipped"] + assert broken[0] != whole[0] + for n, (name, (planted, error)) in enumerate(KANKA_CASES.items()): + got = _door(_export_with(tmp_path, f"case-{n}", planted)) + if error is None: + assert got == whole, name + else: + assert got[0] == broken[0], name + assert got[1] == [note.replace("(JSONDecodeError)", f"({error})") for note in broken[1]], name + + +def test_the_kanka_door_writes_no_file_holding_a_number_the_export_does_not(tmp_path: Path) -> None: + out = tmp_path / "world" + import_kanka(_export_with(tmp_path, "inf", "1e400"), out) + written = sorted(out.rglob("*.json")) + assert len(written) > 10 + assert not any("Infinity" in p.read_text(encoding="utf-8") for p in written)