tests: characters, names, the encountered list and migration step 7 (#23)

This commit is contained in:
2026-11-15 12:01:30 +01:00
parent 20dcb87afb
commit f134534c6c
5 changed files with 1064 additions and 18 deletions
+318
View File
@@ -0,0 +1,318 @@
## Characters, the name rule, reveals and the encountered snapshot (#23, DESIGN 3.1, 4.4, 6.1, 8).
## Pure/unit level: the records, the name rule, the reveal set and the write-through persistence
## (including the reload a restart performs). The wire behaviour lives in tools/characters.test.mjs
## and the egress filtering in tests/tviews.nim.
import std/[json, options, os, sequtils, sets, strutils, tables, unittest]
import db_connector/db_sqlite
import auth, characters, db, props, tokens, world
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "fffchars-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc freshDb(): tuple[db: DbConn, dir: string] =
let d = tmpDir()
let conn = openDatabase(d / "state.db")
discard migrate(conn)
(conn, d)
proc ownedBy(conn: DbConn): int =
## A real owner id: the persisted characters have an FK to `player`, so a unit test needs one.
if gmPlayer(conn).isNone: discard ensureGm(conn)
parseInt(conn.getValue(sql"SELECT id FROM player ORDER BY id LIMIT 1"))
proc aChar(owner = 1, id = ""): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: "a grumpy man", actualName: "Lord Vex",
props: newProps())
proc plainToken(id = "tok1", owner = 0): TokenRec =
TokenRec(id: id, scene: 1, kind: "npc", descriptiveName: "a wolf", actualName: "Fang",
owner: owner, flags: %*{"vision": true}, props: newProps())
suite "the name rule (DESIGN 8: one copy, used by every frame)":
test "an owner, a reveal_all and a per-player reveal each expose the actual name":
check knowsActual(isOwner = true, revealAll = false, revealed = false)
check knowsActual(isOwner = false, revealAll = true, revealed = false)
check knowsActual(isOwner = false, revealAll = false, revealed = true)
check not knowsActual(isOwner = false, revealAll = false, revealed = false)
test "visibleName picks the name the recipient knows":
check visibleName("a grumpy man", "Lord Vex", false) == "a grumpy man"
check visibleName("a grumpy man", "Lord Vex", true) == "Lord Vex"
test "a character owner sees the actual name without any reveal row":
var reveals: Reveals
let c = aChar(owner = 2)
check subjectNamesOf(c).nameFor(2, reveals) == "Lord Vex"
check subjectNamesOf(c).nameFor(3, reveals) == "a grumpy man"
reveals.withReveal(3, c.id)
check subjectNamesOf(c).nameFor(3, reveals) == "Lord Vex"
test "a linked token borrows the character's names, so one reveal covers all of them":
var reveals: Reveals
let c = aChar(owner = 2, id = "char1")
var t = plainToken()
t.characterId = some("char1")
t.descriptiveName = ""
t.actualName = ""
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "a grumpy man"
check subjectNamesOf(t, @[c]).id == "char1" # the reveal key is the character, not the token
reveals.withReveal(3, "char1")
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "Lord Vex"
test "a plain token is nobody's character: only a reveal or reveal_all shows the actual name":
var reveals: Reveals
var t = plainToken(owner = 2) # its controller gets no free actual name
check subjectNamesOf(t, @[]).nameFor(2, reveals) == "a wolf"
t.revealAll = true
check subjectNamesOf(t, @[]).nameFor(3, reveals) == "Fang"
test "revealedPlayers lists the reveal rows of one subject, sorted":
var reveals: Reveals
for p in [4, 2, 3]: reveals.withReveal(p, "char1")
reveals.withReveal(2, "other")
check revealedPlayers(reveals, "char1") == @[2, 3, 4]
check revealedPlayers(reveals, "nothing") == newSeq[int]()
check reveals.isRevealed(3, "char1")
check not reveals.isRevealed(5, "char1")
test "player.remove takes that player's reveal rows with it":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(3, "b")
reveals.withoutRevealsOf(2)
check not reveals.isRevealed(2, "a")
check reveals.isRevealed(3, "b")
test "one reveal row per (player, subject): a repeated reveal changes nothing":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(2, "a")
check reveals.pairs.len == 1
suite "encountered snapshot (DESIGN 8: the name the player knows, frozen)":
test "a first sighting records what the player knows right now":
let c = aChar(owner = 2, id = "char1")
let names = subjectNamesOf(c)
let unknown = newEntry("t1", names, knowsActual = false)
check unknown.entryName == "a grumpy man"
check unknown.actualName.isNone
check unknown.characterId.get == "char1"
let known = newEntry("t1", names, knowsActual = true)
check known.entryName == "Lord Vex"
test "a rename follows the subject, and a player who was never told keeps not knowing":
let c = aChar(id = "char1")
var e = newEntry("t1", subjectNamesOf(c), knowsActual = false)
e = e.renamed("a tall stranger", "Lady Vex")
check e.entryName == "a tall stranger"
check e.actualName.isNone
var known = newEntry("t2", subjectNamesOf(c), knowsActual = true)
known = known.renamed("a tall stranger", "Lady Vex")
check known.entryName == "Lady Vex"
test "a reveal fills in the actual name and leaves the rest alone":
var e = newEntry("t1", subjectNamesOf(aChar(id = "char1")), knowsActual = false)
e = e.revealed("Lord Vex")
check e.entryName == "Lord Vex"
check e.descriptiveName == "a grumpy man"
suite "names and validation (6.5: 1..64 code points, trimmed, no control characters)":
test "a character needs two valid names and an owner":
let c = aChar()
check validCharacter(c)
check validCharacterName("Lord Vex")
check not validCharacterName("")
check not validCharacterName(" padded")
var bad = c
bad.actualName = ""
check not validCharacter(bad)
bad = c
bad.owner = 0
check not validCharacter(bad)
bad = c
bad.descriptiveName = repeat("x", 65)
check not validCharacter(bad)
test "a linked token carries no names of its own (they belong to the character)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plainToken()
t.characterId = some("char1")
check not validToken(sc, t) # still has plain-token names
t.descriptiveName = ""
t.actualName = ""
check validToken(sc, t)
test "parseSubject accepts exactly the two wire words":
check parseSubject("character").get == nsCharacter
check parseSubject("token").get == nsToken
check parseSubject("Character").isNone
check parseSubject("").isNone
suite "persistence (write-through, restart-identical)":
test "create assigns an id from the shared namespace, stores every column, reloads identically":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gm = ensureGm(conn)
let gmId = parseInt(conn.getValue(sql"SELECT id FROM player WHERE role = 'gm'"))
var c = aChar(owner = gmId)
c.props[pbPublic] = %*{"class": "fighter"}
c.props[pbOwner] = %*{"hp": 12}
c.props[pbGm] = %*{"secret": true}
let (outcome, stored) = addCharacter(conn, c, @[])
check outcome == coOk
check gm.key.len > 0
check stored.id.len == TokenIdLength
let reloaded = loadCharacters(conn)
check reloaded.len == 1
check reloaded[0].id == stored.id
check reloaded[0].owner == gmId
check reloaded[0].descriptiveName == "a grumpy man"
check reloaded[0].actualName == "Lord Vex"
check not reloaded[0].revealAll
check reloaded[0].props[pbOwner]["hp"].getInt == 12
check reloaded[0].props[pbGm]["secret"].getBool
test "the id namespace is shared with tokens: taken ids are never handed out again":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
# an exhaustive "taken" list is impossible; check the call site contract instead: the ids of
# every token AND every character are passed to freshId, so the two can never collide.
let (firstOutcome, first) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
let (secondOutcome, second) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[first.id])
check firstOutcome == coOk
check secondOutcome == coOk
check second.id != first.id
test "reveal_all and the props round-trip through a full replacement":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var changed = stored
changed.revealAll = true
changed.actualName = "Lady Vex"
changed.props[pbPublic] = %*{"aura": "cold"}
check storeCharacter(conn, changed) == coOk
let r = loadCharacters(conn)[0]
check r.revealAll
check r.actualName == "Lady Vex"
check r.props[pbPublic]["aura"].getStr == "cold"
var invalid = changed
invalid.descriptiveName = ""
check storeCharacter(conn, invalid) == coInvalid
check loadCharacters(conn)[0].descriptiveName == "a grumpy man"
test "remove deletes the row; a second remove reports nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
check removeCharacter(conn, stored.id)
check loadCharacters(conn).len == 0
check not removeCharacter(conn, stored.id)
test "a reveal row survives a reload and a repeated reveal":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
addReveal(conn, created.id, "char1")
addReveal(conn, created.id, "char1")
let r = loadReveals(conn)
check r.pairs.len == 1
check r.isRevealed(created.id, "char1")
deleteRevealsOf(conn, created.id)
check loadReveals(conn).pairs.len == 0
test "encountered rows survive a reload, keep their NULL actual name, and replace per entry":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man", actualName: none(string)))
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t2", characterId: none(string),
descriptiveName: "a wolf", actualName: some("Fang")))
var loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].actualName.isNone
check loaded[created.id]["t1"].characterId.get == "char1"
check loaded[created.id]["t2"].entryName == "Fang"
# an upsert replaces the snapshot of that (player, token)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a tall stranger", actualName: some("Lord Vex")))
loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].entryName == "Lord Vex"
check deleteEncountered(conn, created.id, "t1")
check not deleteEncountered(conn, created.id, "t1")
check loadEncountered(conn)[created.id].len == 1
test "a character rename follows the snapshots of everyone who met it":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
let p2 = createPlayerWithKey(conn)
writeEncountered(conn, p1.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: none(string)))
writeEncountered(conn, p2.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: some("Lord Vex")))
renameEncountered(conn, "char1", "a tall stranger", "Lady Vex")
let loaded = loadEncountered(conn)
check loaded[p1.id]["t1"].entryName == "a tall stranger" # still not told the actual name
check loaded[p1.id]["t1"].actualName.isNone
check loaded[p2.id]["t1"].entryName == "Lady Vex"
revealEncountered(conn, "char1", "Lady Vex")
check loadEncountered(conn)[p1.id]["t1"].entryName == "Lady Vex"
test "player.remove hands the player's characters to the GM (DESIGN 3.2)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gmId = int(insertID(conn, sql"INSERT INTO player (name, role, colour, created_at) VALUES ('GM','gm','#000','x')"))
let created = createPlayerWithKey(conn)
let (_, stored) = addCharacter(conn, aChar(owner = created.id), @[])
transferToGm(conn, created.id, gmId)
check loadCharacters(conn)[0].owner == gmId
check loadCharacters(conn)[0].id == stored.id
test "a character still figured by a token is in use (6.5)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var t = plainToken()
t.characterId = some(stored.id)
t.descriptiveName = ""
t.actualName = ""
let (outcome, added) = addToken(conn, sc, t, @[])
check outcome == toOk
check tokensLinkedTo(loadTokens(conn), stored.id) == 1
check tokensLinkedTo(loadTokens(conn), "other") == 0
check added.id.len == TokenIdLength
+18 -9
View File
@@ -38,9 +38,9 @@ suite "migrate":
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 6
check LatestVersion == 7
let rows = appliedMigrations(db)
check rows.len == 6
check rows.len == 7
check rows[0][0] == 1
check rows[0][1] == "meta"
check rows[1][0] == 2
@@ -53,6 +53,8 @@ suite "migrate":
check rows[4][1] == "explored"
check rows[5][0] == 6
check rows[5][1] == "token details"
check rows[6][0] == 7
check rows[6][1] == "characters"
# the steps' own DDL ran: meta and the auth tables exist and are empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0"
@@ -69,12 +71,18 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM entity_status") == "0"
for col in ["props_public", "props_owner", "props_gm"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('entity') WHERE name = '" & col & "'")) == "1"
# step 7 creates the character world and adds the link columns to the token table
check db.getValue(sql"SELECT count(*) FROM character") == "0"
check db.getValue(sql"SELECT count(*) FROM name_reveal") == "0"
check db.getValue(sql"SELECT count(*) FROM encountered") == "0"
for col in ["character_id", "reveal_all"]:
check db.getValue(sql("SELECT count(*) FROM pragma_table_info('entity') WHERE name = '" & col & "'")) == "1"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
block:
let db = openFresh(d)
check migrate(db) == 6
check migrate(db) == LatestVersion
close(db)
let db = openFresh(d)
defer:
@@ -83,7 +91,7 @@ suite "migrate":
let before = appliedMigrations(db)
check migrate(db) == 0
check migrate(db) == 0
check schemaVersion(db) == 6
check schemaVersion(db) == LatestVersion
check appliedMigrations(db) == before
test "history and user_version must agree":
@@ -157,8 +165,8 @@ suite "migrate":
check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == 4 # steps 3, 4, 5 and 6 run
check schemaVersion(db) == 6
check migrate(db) == LatestVersion - 2 # steps 3 to 7 run
check schemaVersion(db) == LatestVersion
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
@@ -190,11 +198,12 @@ suite "migrate":
check schemaVersion(db) == 4
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0"
check migrate(db) == 2 # steps 5 and 6 run
check schemaVersion(db) == 6
check appliedMigrations(db).len == 6
check migrate(db) == 3 # steps 5, 6 and 7 run
check schemaVersion(db) == LatestVersion
check appliedMigrations(db).len == 7
check appliedMigrations(db)[4] == (version: 5, name: "explored")
check appliedMigrations(db)[5] == (version: 6, name: "token details")
check appliedMigrations(db)[6] == (version: 7, name: "characters")
# step 6: the status table exists, and the old token's buckets default to empty objects
check db.getValue(sql"SELECT count(*) FROM entity_status") == "0"
check db.getValue(sql"SELECT props_public || props_owner || props_gm FROM entity") == "{}{}{}"
+7 -6
View File
@@ -40,7 +40,7 @@ suite "envelope (6.5 step 2)":
test "the catalogue is the 29 intents of 6.1 and the built set is a subset":
check IntentCatalogue.len == 29
check ImplementedIntents.len == 13 # slice 3's five + slice 4's four walls + slice 5's four token intents
check ImplementedIntents.len == 28 # 29 - `scene.set`, which is slice 10
for t in ImplementedIntents:
check t in IntentCatalogue
check isCatalogueIntent(t)
@@ -63,11 +63,12 @@ suite "envelope (6.5 step 2)":
check isGmOnlyIntent(t) # walls are GM-only (3.1, T2)
for t in ["token.create", "token.update", "token.move", "token.remove"]:
check isImplementedIntent(t)
check not isImplementedIntent("player.setname")
check not isImplementedIntent("scene.set")
check not isImplementedIntent("token.resize")
check not isImplementedIntent("status.set")
check not isImplementedIntent("character.create")
for t in ["player.setname", "player.rename", "key.show", "token.resize", "status.set",
"status.clear", "prop.set", "prop.unset", "character.create", "character.update",
"character.remove", "character.reassign", "name.reveal", "name.reveal_all",
"encountered.remove"]:
check isImplementedIntent(t)
check not isImplementedIntent("scene.set") # the only catalogue intent left for slice 10
suite "intent rate limit (6.4: 30/s, burst 100)":
test "a fresh bucket allows exactly the burst, then refuses":
+178 -3
View File
@@ -3,7 +3,7 @@
## that keep GM-only data out of a player's frames. The black-box proof over a real socket is
## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import geometry, props, tokens, views, vision, world
import characters, geometry, props, tokens, views, vision, world
const Pid = 2 # the subject player
const Other = 3 # another player
@@ -128,8 +128,10 @@ suite "diff (6.4: only what changed)":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first) == @["vision", "explored", "token"]
check first[1]["full"].getBool
check typesOf(first) == @["encountered", "vision", "explored", "token"]
check first[0]["full"].getBool # 6.3: the whole list on connect/resync
check first[0]["set"].len == 0
check first[2]["full"].getBool
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token that moved sends one `token` frame with the new position":
@@ -295,3 +297,176 @@ suite "props and statuses (#22, 6.1: the bucket and the source are per-recipient
check typesOf(frames) == @["token"]
check frames[0]["radius"].getFloat == 35.0
check not frames[0].hasKey("radius_own") # the GM-only own-radius field stays out
# ---------------------------------------------------------------------------------------------------
# Slice 8 (#23): characters, names and the encountered list in the typed view.
proc charOf(id: string, owner: int, dname = "a grumpy man", actual = "Lord Vex"): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: dname, actualName: actual, props: newProps())
proc withChar(ctx: var Context, c: CharacterRec): int =
ctx.characters.add c
ctx.characters.len - 1
proc linked(id: string, x, y: float, owner: int, characterId: string): TokenRec =
TokenRec(id: id, scene: 1, kind: "pc", characterId: some(characterId), pos: (x, y),
owner: owner, flags: %*{"vision": true}, props: newProps())
suite "characters in the egress (3.1, 6.1, 8)":
test "the GM gets every character with owner, reveal_all, revealed and all three buckets":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
var c = charOf("c1", 2)
c.revealAll = true
c.props[pbGm] = %*{"trap": true}
discard ctx.withChar(c)
ctx.reveals.withReveal(Other, "c1")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
check frames.len == 1
let f = frames[0]
check f["t"].getStr == "character"
check f["owner"].getInt == 2
check f["descriptive_name"].getStr == "a grumpy man"
check f["actual_name"].getStr == "Lord Vex"
check f["reveal_all"].getBool
check f["revealed"] == %*[Other]
check f["props"].keys.toSeq.sorted == @["gm", "owner", "public"]
test "a player gets only its own characters, without owner, reveal_all or revealed":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("mine", Pid))
discard ctx.withChar(charOf("theirs", Other))
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
let chars = frames.filterIt(it["t"].getStr == "character")
check chars.len == 1
check chars[0]["id"].getStr == "mine"
check chars[0]["actual_name"].getStr == "Lord Vex" # the owner always knows it (8)
check chars[0]["props"].keys.toSeq.sorted == @["owner", "public"]
for key in ["owner", "reveal_all", "revealed", "nhidden"]:
check not chars[0].hasKey(key)
test "a reassignment withdraws the record from the old owner and sends it to the new one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
var known: Known
check typesOf(egressFrames(Recipient(isGm: false, playerId: Other), ctx, known, resync = true))
.contains("character")
var otherKnown: Known
check not typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
ctx.characters[idx].owner = Pid
let otherFrames = egressFrames(Recipient(isGm: false, playerId: Other), ctx, known)
check typesOf(otherFrames) == @["character_gone"]
check otherFrames[0]["id"].getStr == "c1"
check typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
test "a linked token's name follows the character, and the owner sees the actual one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
# the subject controls the token but does not own the character
var known: Known
var frame = playerView(ctx, Pid).tokens[0]
check frame.name == "a grumpy man"
check frame.characterId.isNone # 6.1 leak note 2
check frame.cpropsPublic.len == 0
# the character's owner sees the actual name and the link
let owner = playerView(ctx, Other)
check owner.tokens.len == 0 # no LOS of its own: the token is not in its view
discard known
test "cprops carries the character's public bucket to a non-owner, and never the owner bucket":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
ctx.characters[idx].props[pbPublic] = %*{"rank": "noble"}
ctx.characters[idx].props[pbOwner] = %*{"hp": 3}
ctx.characters[idx].props[pbGm] = %*{"trap": true}
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
let frame = playerTokenFrame(playerView(ctx, Pid).tokens[0])
check frame["cprops"].keys.toSeq == @["public"]
check frame["cprops"]["public"]["rank"].getStr == "noble"
check "owner" notin keysDeep(frame["cprops"])
check "gm" notin keysDeep(frame)
check frame["props"].keys.toSeq.sorted == @["owner", "public"] # its own buckets
test "a player sees the actual name only when the GM revealed it to them (8)":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
var known: Known
check playerView(ctx, Pid).tokens[0].name == "a grumpy man"
ctx.reveals.withReveal(Pid, "c1")
check playerView(ctx, Pid).tokens[0].name == "Lord Vex"
discard known
suite "the encountered list (8)":
proc entryFor(id: string, name: string, grey = false): EncounteredView =
EncounteredView(id: id, name: name, grey: grey)
test "a resync sends the whole list, then only what changed, then what was removed":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
ctx.encountered[Pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine",
descriptiveName: "a mine")
var known: Known
let full = pass(ctx, known, resync = true)
let enc = full.filterIt(it["t"].getStr == "encountered")
check enc.len == 1
check enc[0]["full"].getBool
check enc[0]["set"] == %*[{"id": "mine", "name": "a mine", "grey": false}]
# nothing changed: no frame
check pass(ctx, known).len == 0
# greyed: the entry is re-sent, nothing is deleted
ctx.encountered[Pid]["mine"].actualName = some("Mine")
let changed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check changed.len == 1
check changed[0]["full"].getBool == false
check changed[0]["set"] == %*[{"id": "mine", "name": "Mine", "grey": false}]
check changed[0]["del"] == newJArray()
# removed: only a `del`
ctx.encountered[Pid].del "mine"
let removed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check removed.len == 1
check removed[0]["set"] == newJArray()
check removed[0]["del"] == %*["mine"]
test "an entry for a token that is gone (or out of view) is grey":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
check not ctx.greyFor(Pid, "near") # in LOS
check ctx.greyFor(Pid, "unknown") # removed from the world
ctx.tokens[1].pos = (3000.0, 3000.0)
check ctx.greyFor(Pid, "near") # moved away
ctx.tokens[1].gmOnly = true
ctx.tokens[1].pos = (500.0, 400.0)
check ctx.greyFor(Pid, "near") # a gm_only flip greys it, it is not deleted
test "the GM gets one list per player, tagged with the player id":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("theirs", 400, 400, Other)],
@[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine", descriptiveName: "a mine")
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
let lists = frames.filterIt(it["t"].getStr == "encountered")
check lists.len == 2
check lists[0]["player"].getInt == Pid
check lists[0]["set"][0]["id"].getStr == "mine"
check lists[1]["player"].getInt == Other
check lists[1]["set"][0]["id"].getStr == "theirs"
test "a player never receives another player's list":
var ctx = ctxOf(sceneWith(@[]), @[tok("theirs", 400, 400, Other)], @[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
for f in frames.filterIt(it["t"].getStr == "encountered"):
check f["set"].len == 0
check not f.hasKey("player")