TableTower/tests/test_text.gd

232 lines
11 KiB
GDScript3
Raw Normal View History

extends TestBase
## Headless checks for RollContext, TextExpander and Formatter.
## Run: godot --headless --path . -s res://tests/test_text.gd
const TABLES := {
"names": "Names",
"gems": "[b]Gems[/b]",
"towns": "Towns",
"loop": "Loop",
"bold": "Bold",
}
## Each stub table returns its results in order, cycling.
const RESULTS := {
"names": ["Alice", "Bob", "Cora"],
"gems": ["Ruby", "Opal", "Jade", "Onyx"],
"towns": ["Riverton", "Hilltop"],
"bold": ["[b]heavy"],
}
var _ctx: RollContext
var _rolls: Dictionary = {}
func _init() -> void:
_test_expander()
_test_formatter()
_test_format_menu()
finish()
func _new_ctx(persistent: Dictionary = {}) -> RollContext:
var rng := RandomNumberGenerator.new()
rng.seed = 7
_ctx = RollContext.new(persistent, rng)
_ctx.resolve_table = _resolve
_ctx.roll_table = _roll
_rolls = {}
return _ctx
func _resolve(name_or_id: String) -> String:
if TABLES.has(name_or_id):
return name_or_id
var want := RollContext.normalize_name(name_or_id)
for id: String in TABLES:
if RollContext.normalize_name(TABLES[id]) == want:
return id
return ""
func _roll(table_id: String, depth: int) -> Dictionary:
if not TABLES.has(table_id):
return {}
var k: int = int(_rolls.get(table_id, 0))
_rolls[table_id] = k + 1
if table_id == "loop":
_ctx.depth = depth + 1
var r := TextExpander.expand("again [[Loop]]", _ctx)
return {"summary": r["text"], "children": r["children"], "depth": depth}
var list: Array = RESULTS[table_id]
return {"summary": list[k % list.size()], "table": table_id, "depth": depth}
func _x(text: String, ctx: RollContext) -> String:
return TextExpander.expand(text, ctx)["text"]
func _test_expander() -> void:
var ctx := _new_ctx()
# Plain reference, by name, case-insensitive, BBCode in the table name ignored.
var r := TextExpander.expand("A [[gems]] ring", ctx)
_eq(r["text"], "A [url=table:gems]Ruby[/url] ring", "reference by name")
_check((r["children"] as Array).size() == 1, "reference adds one child")
_eq(_x("[[Names]]", ctx), "[url=table:names]Alice[/url]", "reference by name, plain")
# Left to right: a chain var used before it's saved is unset, after it's set.
ctx = _new_ctx()
_eq(_x("{hero} [[Names -> hero]] {hero}", ctx),
"[url=unset:hero]{hero?}[/url] [url=table:names]Alice[/url] [url=var:hero]Alice[/url]",
"left to right ordering")
_eq(ctx.lookup("hero"), "Alice", "chain var saved")
_check(ctx.lookup("nobody") == null, "unset lookup is null")
r = TextExpander.expand("[[Names]] then [[Gems]] then [[Names]]", ctx)
var kids: Array = r["children"]
_check(kids.size() == 3 and kids[0]["summary"] == "Bob" and kids[1]["summary"] == "Ruby" and kids[2]["summary"] == "Cora",
"children in text order")
# Chain vs persistent scope.
var store := {}
ctx = _new_ctx(store)
_x("[[Towns -> @town]] [[Names -> hero]]", ctx)
_check(store.has("town") and store["town"]["value"] == "Riverton" and store["town"]["source"] == "towns",
"persistent var saved into the caller's dictionary: %s" % store)
_check(not store.has("hero") and ctx.chain_vars.has("hero"), "chain var stays in the chain")
_check(ctx.persistent_changed, "persistent_changed set")
ctx = _new_ctx(store)
_eq(_x("{hero} in {@town}", ctx), "[url=unset:hero]{hero?}[/url] in [url=var:@town]Riverton[/url]",
"new roll: chain var gone, persistent kept")
_check(not ctx.persistent_changed, "reading doesn't set persistent_changed")
# {@var|Table}: existing value is reused without rolling.
_eq(_x("{@town|Towns}", ctx), "[url=var:@town]Riverton[/url]", "{@var|Table} uses the saved value")
_check(not _rolls.has("towns"), "{@var|Table} didn't reroll")
ctx = _new_ctx({})
r = TextExpander.expand("{@town|Towns}, again {@town|Towns}", ctx)
_eq(r["text"], "[url=var:@town]Riverton[/url], again [url=var:@town]Riverton[/url]", "{@var|Table} rolls once when unset")
_check(int(_rolls.get("towns", 0)) == 1 and (r["children"] as Array).size() == 1, "{@var|Table} rolled exactly once")
_eq(ctx.lookup("@town"), "Riverton", "{@var|Table} saved")
_eq(_x("{@port|Nowhere}", ctx), "[url=missing:Nowhere]⚠ Nowhere[/url]", "{@var|Missing} shows missing marker")
_check(ctx.lookup("@port") == null, "{@var|Missing} saves nothing")
# Count forms.
ctx = _new_ctx()
r = TextExpander.expand("[[3x Gems]]", ctx)
_eq(r["text"], "[url=table:gems]Ruby[/url], [url=table:gems]Opal[/url], [url=table:gems]Jade[/url]", "3x")
_check((r["children"] as Array).size() == 3, "3x adds three children")
ctx = _new_ctx()
_x("[[2 x Gems -> loot]]", ctx)
_eq(ctx.lookup("loot"), "Ruby, Opal", "Nx with save joins the values")
for s in 20:
ctx = _new_ctx()
ctx.rng.seed = s
r = TextExpander.expand("[[1d4 Gems]]", ctx)
var c: int = (r["children"] as Array).size()
_check(c >= 1 and c <= 4, "1d4 rolls 1–4 times (got %d)" % c)
_check((r["text"] as String).count("[url=table:gems]") == c, "1d4 inserts one piece per roll")
ctx = _new_ctx()
_check(TextExpander.roll_dice("2d6+3", ctx.rng) >= 5 and TextExpander.roll_dice("2d6+3", ctx.rng) <= 15, "NdM+K in range")
_check(TextExpander.roll_dice("d1-1", ctx.rng) == 0, "dM-K")
_check(TextExpander.roll_dice("banana", ctx.rng) == -1, "bad dice expression")
_eq(TextExpander.expand("[[0x Gems]]", ctx)["text"], "", "0x inserts nothing")
# Missing tables, unset vars, depth.
ctx = _new_ctx()
r = TextExpander.expand("A [[Dragons]] and [[2x Dragons]].", ctx)
_eq(r["text"], "A [url=missing:Dragons]⚠ Dragons[/url] and [url=missing:Dragons]⚠ Dragons[/url].", "missing table marker")
_check((r["children"] as Array).is_empty(), "missing table adds no children")
_eq(_x("{@nope}", ctx), "[url=unset:@nope]{@nope?}[/url]", "unset persistent marker")
ctx = _new_ctx()
ctx.max_depth = 5
var deep := _x("[[Loop]]", ctx)
_check(deep.contains(TextExpander.deep_marker("loop")), "depth marker present")
_eq(int(_rolls.get("loop", 0)), 6, "loop rolled depths 0..5 then stopped")
_eq(deep.count("again"), 6, "six levels of text")
_eq(ctx.depth, 0, "depth restored after expansion")
ctx = _new_ctx()
ctx.depth = 40
_eq(_x("[[Names]]", ctx), "[url=deep:names]⚠ chain too deep[/url]", "default max depth 32")
# Brackets and BBCode.
ctx = _new_ctx()
_eq(_x("[x] marks [optional] spot", ctx), "[x] marks [optional] spot", "ordinary brackets untouched")
_eq(_x("[b][[Names]][/b] [i]{hero}[/i]", ctx), "[b][url=table:names]Alice[/url][/b] [i][url=unset:hero]{hero?}[/url][/i]",
"BBCode around references")
_eq(_x("[color=red][[Gems]][/color]", ctx), "[color=red][url=table:gems]Ruby[/url][/color]", "reference inside color")
_eq(_x("[url={\"a\":1}]x[/url]", ctx), "[url={\"a\":1}]x[/url]", "braces in a tag parameter aren't variables")
_eq(_x("[[b]x[/b]] and [lb][lb]Names]]", ctx), "[[b]x[/b]] and [lb][lb]Names]]", "not references")
_eq(_x("{not a var} {} {1x}", ctx), "{not a var} {} {1x}", "braces that aren't variables")
_eq(_x("A [[Bold]] thing", ctx), "A [url=table:bold][b]heavy[/b][/url] thing", "child's open tag closed inside its piece")
_eq(_x("[i]left open [[Names]]", ctx), "[i]left open [url=table:names]Bob[/url][/i]", "entry's open tag closed at end")
# references()
_new_ctx()
var refs := TextExpander.references("[[Names -> hero]] [[3x Gems]] {@town|Towns} [[1d4+1 Coins]] [x] [b]y[/b] [[Names]] {hero}")
_check(refs == (["Names", "Gems", "Towns", "Coins"] as Array[String]), "references: %s" % [refs])
var tricky := TextExpander.references("[[3x Gems]]", func(n: String) -> String: return "t" if n == "3x Gems" else "")
_check(tricky == (["3x Gems"] as Array[String]), "references keeps a whole name that resolves: %s" % [tricky])
_check(_rolls.is_empty(), "references doesn't roll")
func _test_formatter() -> void:
# close_open_tags
_eq(Formatter.close_open_tags("[b]bold"), "[b]bold[/b]", "close one")
_eq(Formatter.close_open_tags("[b][i]x"), "[b][i]x[/i][/b]", "close nested in order")
_eq(Formatter.close_open_tags("[b][i]x[/b] y"), "[b][i]x[/i][/b] y", "mismatched close fixes inner")
_eq(Formatter.close_open_tags("x[/b] y"), "x[lb]/b] y", "stray close escaped")
_eq(Formatter.close_open_tags("[color=#ff0000]r[font_size=20]big"), "[color=#ff0000]r[font_size=20]big[/font_size][/color]", "params")
_eq(Formatter.close_open_tags("[x] [lb] [b]ok[/b]"), "[x] [lb] [b]ok[/b]", "balanced and unknown untouched")
_eq(Formatter.close_open_tags("[ul bullet=*]\na\nb"), "[ul bullet=*]\na\nb[/ul]", "list closed")
# strip_tags
_eq(Formatter.strip_tags("[b]Bold[/b] [color=red]red[/color] [x] [lb]b]"), "Bold red [x] [b]", "strip basic")
_eq(Formatter.strip_tags("[url=table:gems]Ruby[/url] and [url=missing:Dragons]⚠ Dragons[/url] for [url=unset:hero]{hero?}[/url]"),
"Ruby and ⚠ Dragons (missing table) for {hero?}", "strip markers")
_eq(Formatter.strip_tags("a[img]res://icon.svg[/img]b[br]c[char=41]"), "ab\ncA", "strip img, br, char")
_eq(Formatter.strip_tags("[url={\"a\":1}]link[/url]"), "link", "strip JSON url")
# to_export_bbcode
_eq(Formatter.to_export_bbcode("[b][url=table:gems]Ruby[/url][/b] [url=var:@town]Hilltop[/url] [url=https://x.org]site[/url]"),
"[b]Ruby[/b] Hilltop [url=https://x.org]site[/url]", "export drops only internal urls")
_eq(Formatter.to_export_bbcode("[url=table:a]x [url=table:b]y[/url] z[/url]"), "x y z", "export nested internal urls")
# sanitize_import
_eq(Formatter.sanitize_import("[img]/etc/passwd[/img]hi [url=file:///x]there[/url]"), "hi there", "import strips img and url")
_eq(Formatter.sanitize_import("[img=10x10]a.png[/img][font=res://f.ttf]t[/font]"), "t", "import strips img with param and font")
_eq(Formatter.sanitize_import("[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]"),
"[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]", "import keeps allowed tags")
_eq(Formatter.sanitize_import("[url=missing:Fake]⚠ Fake[/url]"), "⚠ Fake", "import can't forge markers")
_eq(Formatter.sanitize_import("[color=red onclick]x[/color][b]open"), "x[b]open[/b]", "bad params dropped, open closed")
_eq(Formatter.sanitize_import("[ul bullet=*]\na\n[/ul][lb]b]"), "[ul bullet=*]\na\n[/ul][lb]b]", "import keeps lists and lb")
# escape_literal
_eq(Formatter.escape_literal("[b]x[/b]"), "[lb]b]x[lb]/b]", "escape tags")
_eq(Formatter.strip_tags(Formatter.escape_literal("[b]x[/b] [[Gems]]")), "[b]x[/b] [[Gems]]", "escaped text strips back")
_eq(TextExpander.expand(Formatter.escape_literal("[[Gems]]"), _new_ctx())["text"], "[lb][lb]Gems]]", "escaped reference not expanded")
_eq(RollContext.normalize_name(" [b]Gems[/b] "), "gems", "normalize_name")
## Right-click formatting and the app's own text effects.
func _test_format_menu() -> void:
var line := LineEdit.new()
line.text = "A legendary sword"
FormatMenu.attach(line)
var menu := line.get_menu()
var labels: Array[String] = []
for i in menu.item_count:
labels.append(menu.get_item_text(i))
_check(labels.has("Bold") and labels.has("Effect"), "a text field's right-click menu has Bold and Effect: %s" % ", ".join(labels))
var changed := []
line.text_changed.connect(func(text: String) -> void: changed.append(text))
line.select(2, 11)
FormatMenu.wrap_selection(line, "[sparkle]", "[/sparkle]")
_eq(line.text, "A [sparkle]legendary[/sparkle] sword", "it wraps the selected words")
_eq(changed.size(), 1, "and tells the field's listeners")
_eq(Formatter.strip_tags(line.text), "A legendary sword", "the app's own effects count as tags (stripped from plain text)")
var label := RichText.label("[shimmer]Rare[/shimmer]", 15, Color.WHITE, false)
_eq(label.get_parsed_text(), "Rare", "a label draws the shimmer effect instead of showing its tag")
label.free()
line.free()