TableTower/tests/test_integration.gd

236 lines
10 KiB
GDScript3
Raw Permalink Normal View History

extends SceneTree
## Headless checks for the roller working with RollContext, TextExpander,
## pipes that save variables, card decks and StateStore.
## Run: godot --headless --path . -s res://tests/test_integration.gd
var _failures := 0
func _init() -> void:
_test_refs_and_vars()
_test_pipe_save()
_test_persistent_across_rolls()
_test_depth_limit()
_test_missing_and_unset()
_test_decks_through_state()
_test_lit_and_steps()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _entry(id: String, text: String, weight: int = 1) -> TableEntry:
var e := TableEntry.new(id, text)
e.weight = weight
return e
func _table(id: String, name: String, texts: Array) -> RollTable:
var t := RollTable.new(id, name)
for i in texts.size():
t.entries.append(_entry("%s%d" % [id, i], texts[i]))
return t
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "test-coll"
for t in tables:
b.tables.append(t)
return b
func _rng(seed_value: int) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
## A quest board: Quest uses refs, chain vars and a persistent var.
func _quest_board() -> TowerBoard:
var quest := _table("quest", "Quest Hook", ["[[Names -> hero]] seeks [[Relics]] in {@town|Towns}. {hero} is [b]sure[/b] of it."])
var names := _table("names", "Names", ["Aldric"])
var relics := _table("relics", "[i]Relics[/i]", ["the Crown"])
var towns := _table("towns", "Towns", ["Riverton"])
return _board([quest, names, relics, towns])
func _test_refs_and_vars() -> void:
var b := _quest_board()
var n := Roller.roll(b, "quest", _rng(1))
var summary: String = n["summary"]
_check(summary.contains("[url=table:names]Aldric[/url]"), "inline [[Names -> hero]] expands: %s" % summary)
_check(summary.contains("[url=table:relics]the Crown[/url]"), "reference matches a name with BBCode")
_check(summary.contains("[url=var:@town]Riverton[/url]"), "{@town|Towns} rolls and inserts")
_check(summary.contains("[url=var:hero]Aldric[/url]"), "{hero} reuses the chain variable")
_eq(Formatter.strip_tags(summary), "Aldric seeks the Crown in Riverton. Aldric is sure of it.", "plain text of the result")
var kids: Array = n["children"]
_check(kids.size() == 3, "three inline children (names, relics, towns), got %d" % kids.size())
var all_inline := true
for c: Dictionary in kids:
all_inline = all_inline and c.get("inline", false)
_check(all_inline, "inline children are marked inline")
var steps := Roller.flatten(n, [])
_check(steps.size() == 4 and steps[1].get("inline", false) and not steps[0].has("inline"), "steps mark inline rolls")
_check(int(steps[1]["depth"]) == 1 and int(steps[0]["depth"]) == 0, "steps carry their depth")
_check((steps[0]["text"] as String).contains("[b]sure[/b]"), "steps carry BBCode text")
_check(Roller.ref_targets(b, b.get_table("quest").entries[0].text) == ["names", "relics", "towns"], "ref_targets resolves names: %s" % str(Roller.ref_targets(b, b.get_table("quest").entries[0].text)))
func _test_pipe_save() -> void:
var src := _table("src", "Source", ["Go {foe}, then {@pal?}"])
var dst := _table("dst", "Foes", ["[b]Ogre[/b]"])
var pals := _table("pals", "Pals", ["Mira"])
src.entries[0].add_pipe("dst", 2, "foe")
src.entries[0].add_pipe("pals", 1, "@pal")
var b := _board([src, dst, pals])
var store := {}
var ctx := Roller.new_context(b, _rng(3), store, {})
var n := Roller.roll(b, "src", ctx.rng, 0, {}, ctx)
# Text is expanded before pipes roll, so {foe} isn't set yet in the same entry.
_check((n["summary"] as String).contains("{foe?}"), "pipes roll after the entry's text")
_eq(ctx.lookup("foe"), "[b]Ogre[/b]", "pipe save_as stores the export BBCode in a chain var")
_check(not (ctx.lookup("foe") as String).contains("url="), "saved value has no internal markers")
_check(store.has("pal") and store["pal"]["value"] == "Mira" and store["pal"]["source"] == "pals", "@ save goes to persistent vars with source: %s" % str(store))
_check(ctx.persistent_changed, "persistent_changed after a pipe save")
# A later table in the same chain sees the chain var.
var a := _table("a", "A", ["start"])
var c := _table("c", "C", ["uses {foe}"])
a.entries[0].add_pipe("dst", 1, "foe")
a.entries[0].add_pipe("c")
var b2 := _board([a, c, dst])
var n2 := Roller.roll(b2, "a", _rng(4))
var used: String = (n2["children"] as Array)[1]["summary"]
_eq(used, "uses [url=var:foe][b]Ogre[/b][/url]", "chain var from a pipe is used by a later pipe")
func _test_persistent_across_rolls() -> void:
var b := _quest_board()
var store := {}
var decks := {}
var r := _rng(5)
var ctx := Roller.new_context(b, r, store, decks)
Roller.roll(b, "quest", r, 0, {}, ctx)
_check(store.has("town") and store["town"]["value"] == "Riverton", "first roll saves @town")
# Change the town by hand; the next roll uses it instead of rolling.
store["town"]["value"] = "Hilltop"
var ctx2 := Roller.new_context(b, r, store, decks)
var n := Roller.roll(b, "quest", r, 0, {}, ctx2)
_check((n["summary"] as String).contains("Hilltop"), "persistent var survives into the next roll")
_check(ctx2.chain_vars.has("hero") and not ctx2.chain_vars.has("town"), "chain vars are fresh per roll")
var inline_tables := []
for c: Dictionary in n["children"]:
inline_tables.append((c["table"] as RollTable).id)
_check(not inline_tables.has("towns"), "no reroll of Towns while @town is set")
# Through StateStore dictionaries (names without "@").
var dir := "user://test_integration_state"
var st := StateStore.new(dir)
st.reload()
for k in store:
st.set_variable(b.id, k, store[k]["value"], store[k]["source"])
st.save()
var st2 := StateStore.new(dir)
var back := st2.get_variables(b.id)
_check(back.has("town") and back["town"]["value"] == "Hilltop" and back["town"]["source"] == "towns", "persistent vars round-trip through StateStore")
var ctx3 := Roller.new_context(b, r, back, {})
_eq(ctx3.lookup("@town"), "Hilltop", "RollContext reads StateStore's variables")
DirAccess.remove_absolute(st.state_path())
DirAccess.remove_absolute(dir.path_join("state"))
DirAccess.remove_absolute(dir)
func _test_depth_limit() -> void:
_check(Roller.MAX_DEPTH == 32, "depth limit is 32")
var loop := _table("loop", "Loop", ["again [[Loop]]"])
var b := _board([loop])
var n := Roller.roll(b, "loop", _rng(6))
var steps := Roller.flatten(n, [])
_check(steps.size() == Roller.MAX_DEPTH + 1, "self-reference stops at the depth limit (%d steps)" % steps.size())
var deepest: Dictionary = steps[steps.size() - 1]
_check((deepest["text"] as String).contains(TextExpander.DEEP_TEXT), "deepest text shows the chain-too-deep marker")
_check(int(deepest["depth"]) == Roller.MAX_DEPTH, "deepest step is at the limit")
# Mixed: pipes no longer count toward the depth limit, but the references
# still nest at most MAX_DEPTH deep, so the chain ends.
var ta := _table("ta", "TA", ["[[TB]]"])
var tb := _table("tb", "TB", ["pipe"])
tb.entries[0].add_pipe("ta")
var b2 := _board([ta, tb])
var n2 := Roller.roll(b2, "ta", _rng(7))
var worst := 0
for s in Roller.flatten(n2, []):
worst = maxi(worst, int(s["depth"]))
var inline := 0
for s in Roller.flatten(n2, []):
if s.get("inline", false):
inline += 1
_check(inline <= Roller.MAX_DEPTH and worst <= 2 * Roller.MAX_DEPTH + 1, "mixed pipes and refs stop at the reference limit (%d refs, depth %d)" % [inline, worst])
func _test_missing_and_unset() -> void:
var t := _table("t", "T", ["[[Nowhere]] and {ghost}"])
var n := Roller.roll(_board([t]), "t", _rng(8))
_eq(n["summary"], "[url=missing:Nowhere]⚠ Nowhere[/url] and [url=unset:ghost]{ghost?}[/url]", "missing and unset markers")
_eq(Formatter.strip_tags(n["summary"]), "⚠ Nowhere (missing table) and {ghost?}", "markers read as text")
func _test_decks_through_state() -> void:
var deck := _table("deck", "Deck", ["A", "B", "C"])
deck.card_mode = true
var b := _board([deck])
var dir := "user://test_integration_decks"
var st := StateStore.new(dir)
st.reload()
var r := _rng(9)
var seen := {}
# Each roll loads the deck from the store and saves it back, like Main does.
for i in 3:
var decks := {}
var saved := st.get_deck(b.id, "deck")
if not saved.is_empty():
decks["deck"] = DeckState.from_dict(saved)
var n := Roller.roll(b, "deck", r, 0, decks)
seen[(n["entry"] as TableEntry).text] = true
_check(not n.has("reshuffled"), "no reshuffle while cards are left")
st.set_deck(b.id, "deck", (decks["deck"] as DeckState).to_dict())
st.save()
_check(seen.size() == 3, "three rolls through the store deal three different cards")
var st2 := StateStore.new(dir)
var restored := DeckState.from_dict(st2.get_deck(b.id, "deck"))
_check(restored.cards_left(deck) == Vector2i(0, 3), "a reloaded store remembers the empty deck")
var decks2 := {"deck": restored}
var n4 := Roller.roll(b, "deck", r, 0, decks2)
_check(n4.get("reshuffled", false), "empty deck from the store reshuffles")
_check(Roller.step_of(n4).get("reshuffled", false), "step notes the reshuffle")
st2.forget_table(b.id, "deck")
_check(st2.get_deck(b.id, "deck").is_empty(), "forget_table drops the deck")
DirAccess.remove_absolute(st.state_path())
DirAccess.remove_absolute(dir.path_join("state"))
DirAccess.remove_absolute(dir)
func _test_lit_and_steps() -> void:
var b := _quest_board()
b.get_table("quest").entries[0].add_pipe("names")
var n := Roller.roll(b, "quest", _rng(10))
var le := {}
var lp := {}
var lt := {}
Roller.collect_lit(n, le, lp, lt)
_check(lp.has(Roller.ref_key("quest", "quest0", "names")), "reference pipe is lit")
_check(lp.has(Roller.pipe_key("quest", "quest0", "names")), "real pipe is lit too")
_check(Roller.is_ref_key(Roller.ref_key("a", "b", "c")) and not Roller.is_ref_key(Roller.pipe_key("a", "b", "c")), "ref keys are told apart")
_check((lt[Roller.entry_key("quest", "quest0")] as String).contains("Aldric"), "lit texts hold the expanded text")
# Steps survive JSON (history is saved as JSON).
var steps := Roller.flatten(n, [])
var back: Variant = JSON.parse_string(JSON.stringify(steps))
_check(back is Array and (back as Array).size() == steps.size() and back[0]["text"] == steps[0]["text"], "steps round-trip through JSON")
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(got == want, "%s\n got: %s\n want: %s" % [what, str(got), str(want)])
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)