extends SceneTree ## Headless checks for the import/export converters. ## Run: godot --headless --path . -s res://tests/test_io.gd const TMP_DIR := "user://test_io_tmp/" var _failures := 0 func _init() -> void: DirAccess.make_dir_recursive_absolute(TMP_DIR) _test_json() _test_canvas() _test_canvas_stripped() _test_mermaid_dot() _test_graphml() _cleanup() print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) quit(1 if _failures else 0) ## Two tables with weights, ranges, count/save_as pipes, an inline reference, a ## missing target, BBCode, quotes and brackets. func _small() -> Dictionary: return { "format_version": 2, "id": "demo", "name": "Demo \"Set\"", "tables": [ {"id": "loot", "name": "Loot", "x": 40, "y": 60, "details": "Treasure [b]stuff[/b]\nline 2", "tags": ["a", "b"], "entries": [ {"id": "e1", "text": "Gold coins", "weight": 3}, {"id": "e2", "text": "[b]Melee[/b] weapon \"sharp\" [1]", "details": "A [i]nice[/i] one", "pipes": [{"table": "weapons", "count": 2, "save_as": "weapon"}, "ghost"]}, {"id": "e3", "text": "Try [[Weapons -> w2]] again"}, ]}, {"id": "weapons", "name": "Weapons", "x": 420, "y": 80, "dice": "1d6", "card_mode": true, "entries": [ {"id": "e1", "text": "Dagger", "range": [1, 2]}, {"id": "e2", "text": "Sword", "range": [3, 5], "pipes": ["loot"]}, {"id": "e3", "text": "Warhammer", "range": [6, 6]}, ]}, ], } func _test_json() -> void: var sample := SampleBoard.create().to_dict() var text := JsonIO.export_json(sample) var res := JsonIO.import_json(text) _check(res["ok"], "sample JSON imports") var col: Dictionary = res["collection"] var canon := JsonIO.canonical(sample) _check(col["tables"] == canon["tables"], "sample JSON round-trips its tables") _check(col["format_version"] == 2 and str(col["id"]) != "" and str(col["name"]) != "", "legacy file gets version 2, id and name") var wild: Dictionary = {} for t in col["tables"]: if t["id"] == "wilderness": wild = t _check(wild.get("dice", "") == "1d100" and not wild.has("die"), "legacy die: 100 becomes dice 1d100") var small := _small() var res2 := JsonIO.import_json(JsonIO.export_json(small)) _check(res2["ok"] and res2["collection"] == JsonIO.canonical(small), "small collection round-trips exactly") _check(not JsonIO.export_json({"tables": [], "state": {"draws": 1}}).contains("state"), "export drops unknown/local keys") # Legacy keys: triggers, die, collection name. var legacy := JsonIO.import_json('{"format_version":1,"collection":"Old","tables":[{"id":"a","name":"A","die":20,"entries":[{"text":"x","triggers":["a"]}]}]}') _check(legacy["ok"] and legacy["collection"]["name"] == "Old", "legacy collection key becomes name") var lt: Dictionary = legacy["collection"]["tables"][0] _check(lt["dice"] == "1d20" and lt["entries"][0]["pipes"] == ["a"] and lt["entries"][0]["id"] == "e1", "legacy die/triggers/missing entry id handled") # Id collisions: duplicate and missing table ids, duplicate entry ids; pipes keep pointing right. var dup := {"tables": [ {"id": "t", "name": "First", "entries": [{"id": "x", "text": "a", "pipes": ["t"]}, {"id": "x", "text": "b"}]}, {"id": "t", "name": "Second", "entries": [{"text": "c", "pipes": ["First"]}]}, {"name": "Third Table", "entries": [{"text": "d", "pipes": ["t"]}]}, ]} var dres := JsonIO.import_dict(dup) _check(dres["ok"], "colliding ids still import") var dt: Array = dres["collection"]["tables"] var ids := {} for t in dt: ids[t["id"]] = true _check(ids.size() == 3, "table ids are unique after import") _check(dt[0]["id"] == "t" and dt[1]["id"] != "t" and dt[2]["id"] == "third_table", "first keeps id, others get fresh ones") _check(dt[0]["entries"][0]["id"] != dt[0]["entries"][1]["id"], "duplicate entry ids are fixed") _check(dt[1]["entries"][0]["pipes"] == ["t"], "pipe by table name is resolved to the id") _check(dt[2]["entries"][0]["pipes"] == ["t"], "pipe to the original id keeps pointing at the first table") # Validation. _check(not JsonIO.import_json("not json")["ok"], "garbage is rejected") _check(not JsonIO.import_json("[1,2]")["ok"], "non-object is rejected") _check(not JsonIO.import_json('{"nope":1}')["ok"], "missing tables is rejected") _check(not JsonIO.import_json('{"tables":[3]}')["ok"], "non-object table is rejected") _check(not JsonIO.import_json('{"format_version":9,"tables":[]}')["ok"], "future version is rejected") _check((JsonIO.import_json("not json")["errors"] as Array).size() == 1, "errors are listed") # Sanitize hook reaches every visible string. var san := func(s: String) -> String: return s.replace("[b]", "").replace("[/b]", "").to_upper() var sres := JsonIO.import_json(JsonIO.export_json(small), san) var st: Dictionary = sres["collection"]["tables"][0] _check(st["name"] == "LOOT" and st["entries"][1]["text"].begins_with("MELEE WEAPON"), "sanitize applies to names and entry text") _check(st["details"] == "TREASURE STUFF\nLINE 2" and st["tags"] == ["A", "B"], "sanitize applies to details and tags") _check(st["entries"][1]["pipes"][0]["save_as"] == "WEAPON" and st["entries"][1]["pipes"][0]["table"] == "weapons", "sanitize touches save_as but not ids") func _test_canvas() -> void: var small := _small() var text := CanvasIO.export_canvas(small) var doc: Variant = JSON.parse_string(text) _check(doc is Dictionary and doc["nodes"] is Array and doc["edges"] is Array, "canvas is valid JSON with nodes and edges") var groups := 0 var texts: Array[String] = [] for n in doc["nodes"]: if n["type"] == "group": groups += 1 else: texts.append(n["text"]) _check(groups == 2, "canvas has a group per table") _check(texts.has("3 × Gold coins") and texts.has("1–2: Dagger") and texts.has("6–6: Warhammer"), "canvas text shows weights and ranges (%s)" % str(texts)) var labels: Array[String] = [] for e in doc["edges"]: labels.append(str(e.get("label", ""))) _check(labels.has("×2 → weapon") and labels.has("ref → w2"), "canvas edge labels (%s)" % str(labels)) _check(doc["edges"].size() == 3, "canvas edges: 2 pipes + 1 ref (missing target skipped), got %d" % doc["edges"].size()) var res := CanvasIO.import_canvas(text) _check(res["ok"], "canvas imports") var want := JsonIO.canonical(small) var got: Dictionary = res["collection"] _check(got["tables"] == want["tables"], "canvas round trip keeps every field") _check(got["id"] == "demo" and got["name"] == small["name"], "canvas round trip keeps collection id and name") # Group sizing: entries sit inside their group. var ok_inside := true var group_rects := {} for n in doc["nodes"]: if n["type"] == "group": group_rects[n["id"]] = Rect2(n["x"], n["y"], n["width"], n["height"]) for n in doc["nodes"]: if n["type"] == "text": var r := Rect2(n["x"], n["y"], n["width"], n["height"]) var inside := false for gr in group_rects.values(): if (gr as Rect2).encloses(r): inside = true ok_inside = ok_inside and inside _check(ok_inside, "every entry node fits inside a group") var sample := SampleBoard.create().to_dict() var big := CanvasIO.import_canvas(CanvasIO.export_canvas(sample)) _check(big["ok"] and _plain_tables(big["collection"]["tables"], sample) == _plain_tables(JsonIO.canonical(sample)["tables"], sample), "sample board's roll tables survive a canvas round trip (logic keys are JSON-only)") func _test_canvas_stripped() -> void: var text := CanvasIO.export_canvas(_small()) var doc: Dictionary = JSON.parse_string(text) doc.erase("tabletower") for n in doc["nodes"]: n.erase("tabletower") for e in doc["edges"]: e.erase("tabletower") var res := CanvasIO.import_canvas(JSON.stringify(doc)) _check(res["ok"], "stripped canvas imports") _check(not (res["guesses"] as Array).is_empty(), "stripped canvas reports guesses") var tables: Array = res["collection"]["tables"] _check(tables.size() == 2, "stripped: two tables") var loot: Dictionary = tables[0] var weapons: Dictionary = tables[1] _check(loot["name"] == "Loot" and loot["x"] == 40 and loot["y"] == 60, "stripped: name and position") _check(loot["entries"].size() == 3 and loot["entries"][0]["text"] == "Gold coins" and loot["entries"][0]["weight"] == 3, "stripped: weighted entry recovered") _check(not loot.has("dice"), "stripped: unranged table has no dice") _check(weapons.get("dice", "") == "1d6", "stripped: dice inferred from ranges") _check(weapons["entries"][1]["range"] == [3, 5] and weapons["entries"][1]["text"] == "Sword", "stripped: ranges recovered") _check(loot["entries"][1]["text"] == "Melee weapon \"sharp\" [1]", "stripped: BBCode is gone from visible text") var pipe: Variant = loot["entries"][1].get("pipes", [])[0] _check(pipe is Dictionary and pipe["table"] == weapons["id"] and pipe["count"] == 2 and pipe["save_as"] == "weapon", "stripped: count and save_as parsed from edge label") _check(weapons["entries"][1].get("pipes", []) == [loot["id"]], "stripped: plain pipe becomes a table id") _check(not loot["entries"][2].has("pipes"), "stripped: reference edges do not become pipes") var found := false for g in res["guesses"]: found = found or (g as String).contains("1d6") _check(found, "stripped: dice guess is reported") # A d100 table written with 00 for the top. var d100 := CanvasIO.import_canvas(CanvasIO.export_canvas({"tables": [{"id": "w", "name": "W", "dice": "1d100", "entries": [ {"text": "low", "range": [1, 95]}, {"text": "high", "range": [96, 100]}]}]}).replace("\"tabletower\"", "\"zz\"")) var wt: Dictionary = d100["collection"]["tables"][0] _check(wt["entries"][1]["range"] == [96, 100] and wt["dice"] == "1d100", "stripped: 96–00 reads as 96-100") _check(not CanvasIO.import_canvas("{}")["collection"].has("tables") or not CanvasIO.import_canvas("{}")["ok"], "empty canvas is not ok") _check(not CanvasIO.import_canvas("nope")["ok"], "invalid canvas JSON is not ok") func _test_mermaid_dot() -> void: var small := _small() var m := MermaidExporter.export_mermaid(small) _check(m.begins_with("graph LR"), "mermaid starts with graph LR") _check(m.contains("t0[\"Loot\"]") and m.contains("t1[\"Weapons (1d6)\"]"), "mermaid nodes, dice in label") _check(m.contains("t0 -->|\"") and m.contains("×2 → weapon") and m.contains("| t1"), "mermaid pipe edge with count and save_as") _check(m.contains("t0 -.->|\"") , "mermaid dashed edge for reference") _check(m.contains("t1 -->|\"Sword") and m.contains("| t0"), "mermaid pipe back to Loot") _check(m.contains("missing: ghost") and m.contains(":::missing"), "mermaid marks the missing target") _check(not m.contains("[b]") and not m.contains("[/b]"), "mermaid strips BBCode") _check(m.contains("#quot;sharp#quot;") and m.contains("#91;1#93;"), "mermaid escapes quotes and brackets") for line in m.split("\n"): if line.contains("-->|") or line.contains("-.->|"): # Between the pipes there must be exactly one quoted string. var inner: String = line.get_slice("|", 1) _check(inner.begins_with("\"") and inner.ends_with("\"") and inner.count("\"") == 2, "mermaid label is one clean quoted string: " + line) var d := DotExporter.export_dot(small) _check(d.begins_with("digraph TableTower {") and d.strip_edges().ends_with("}"), "dot has a digraph wrapper") _check(d.contains("Weapons (1d6)") and d.contains("PORT=\"e1\""), "dot table labels and entry ports") _check(d.contains("t0:e1:e -> t1:head:w [label=\"×2 → weapon\"]"), "dot pipe edge from entry port to table") _check(d.contains("t0:e2:e -> t1:head:w [label=\"ref → w2\", style=dashed]"), "dot dashed reference edge") _check(d.contains("t1:e1:e -> t0:head:w;"), "dot plain pipe edge") _check(d.contains("missing: ghost") and d.contains("color=red"), "dot marks the missing target") _check(d.contains(""sharp"") and not d.contains("[b]"), "dot escapes quotes in HTML labels and strips BBCode") _check(d.contains("label=\"Demo \\\"Set\\\"\""), "dot escapes quotes in strings") _check(DotExporter.escape_string("a\"b\\c\nd") == "a\\\"b\\\\c\\nd", "dot string escaping") _check(DotExporter.escape_html("") == "<a&b>", "dot html escaping") # Big tables don't explode. var sm := MermaidExporter.export_mermaid(SampleBoard.create().to_dict()) var sd := DotExporter.export_dot(SampleBoard.create().to_dict()) _check(sm.contains("graph LR") and sd.contains("more"), "sample board exports to mermaid and dot") func _test_graphml() -> void: var small := _small() var text := GraphMLIO.export_graphml(small) _check(text.contains("")["ok"], "non-graphml is rejected") # Write a file once to make sure the text survives disk. var path := TMP_DIR + "x.graphml" var f := FileAccess.open(path, FileAccess.WRITE) f.store_string(text) f.close() _check(GraphMLIO.import_graphml(FileAccess.get_file_as_string(path))["collection"] == JsonIO.canonical(small), "graphml survives a file") func _cleanup() -> void: var dir := DirAccess.open(TMP_DIR) if dir != null: for f in dir.get_files(): dir.remove(f) DirAccess.remove_absolute(TMP_DIR) ## The tables of `tables` that are plain roll tables in `sample` (no kind, ## modifier or changes), since only TableTower JSON keeps logic keys. func _plain_tables(tables: Array, sample: Dictionary) -> Array: var plain := {} for t: Dictionary in JsonIO.canonical(sample)["tables"]: var logic := t.has("kind") or t.has("dice_mod") for e: Dictionary in t["entries"]: logic = logic or e.has("effects") if not logic: plain[t["id"]] = true return tables.filter(func(t: Dictionary) -> bool: return plain.has(t["id"])) func _check(ok: bool, what: String) -> void: if not ok: _failures += 1 print(" ✗ ", what)