Files
FFF_vtt_frozen/tests/ttokens.nim
T
SirStone 20575f2147 tests: props, statuses, the resize rules and migration step 6 (#22)
tests/tprops.nim is new: the caps (per bucket, keys, values), the key rules,
the registry (empty fallback, a registered key's kind and bucket), set/unset
and the clone that keeps an edit away from the original bucket.

ttokens covers radius, the three buckets, the status set (round trip, sorted,
replaced rather than appended, removed by the FK cascade). tmoverules covers
per-token radius, shrink/grow/squeeze, the no-crossing rule, the corner
relaxation and the independence of the two sources; the old `blocked` tests
became `stuckWalls`. tviews covers the bucket and source filtering, one
`token` frame per change and the effective radius. tdb/tdb's fixtures move to
step 6, and tprobing follows the rename.
2026-11-15 11:02:43 +01:00

385 lines
13 KiB
Nim

## Tokens (#20, DESIGN 4.1, 4.4, 6.1, 8): ids, name/kind validation, the `vision` flag, the
## write-through persistence and the reload a restart performs, including the nullable columns and
## the FK that hands a removed player's tokens to the GM. The wire behaviour over a socket lives in
## tools/tokens.test.mjs and the leak harness.
import std/[json, options, os, sequtils, sets, strutils, unittest]
import db_connector/db_sqlite
import auth, db, props, tokens, world
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "ffftokens-" & $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 plain(id = "", x = 100.0, y = 100.0, owner = GmControlled): TokenRec =
TokenRec(id: id, kind: "npc", descriptiveName: "a grumpy man", actualName: "Lord Vex",
pos: (x, y), owner: owner, flags: %*{"vision": true})
suite "ids (DESIGN 8, FIXED #3: random, opaque, 12 chars)":
test "12 characters from the documented alphabet":
let allowed = TokenIdAlphabet.toHashSet
var seen = initHashSet[string]()
for i in 0 ..< 200:
let id = newTokenId()
check id.len == TokenIdLength
for c in id: check c in allowed
check id notin seen
seen.incl id
test "freshId never returns an id that is taken":
let a = newTokenId()
var taken = newSeq[string]()
# a taken list that is exhaustive in the only way a test can be: same length, one element
for i in 0 ..< 1000: taken.add newTokenId()
let id = freshId(taken & @[a])
check id notin taken
check id != a
suite "names and kinds (DESIGN 6.5: 1..64 code points, trimmed, no control characters)":
test "a name is trimmed, non-empty and free of control characters":
check validName("a grumpy man")
check validName("Lord Vex")
check validName(repeat("x", MaxNameLen))
check not validName("")
check not validName(" ")
check not validName(" padded")
check not validName("padded ")
check not validName("tab\there")
check not validName("nul\0here")
check not validName(repeat("x", MaxNameLen + 1))
check validName("café") # code points, not bytes
test "kind is a short free string":
check validKind("pc")
check validKind("npc")
check validKind("item")
check not validKind("")
check not validKind("two words but a very long kind that overflows")
test "vision_radius is a positive finite number or null":
check parseVisionRadius(nil).get.isNone # absent = the scene default
check parseVisionRadius(newJNull()).get.isNone
check parseVisionRadius(%300).get.get == 300.0
check parseVisionRadius(%150.5).get.get == 150.5
check parseVisionRadius(%0).isNone
check parseVisionRadius(%(-5)).isNone
check parseVisionRadius(%"300").isNone
check parseVisionRadius(%*[300]).isNone
suite "the `vision` flag (Q7, DESIGN 8)":
test "only a true boolean flag counts":
check plain().hasVision
var t = plain()
t.flags = %*{}
check not t.hasVision
t.flags = %*{"vision": false}
check not t.hasVision
t.flags = %*{"vision": "yes"}
check not t.hasVision
t.flags = newJNull()
check not t.hasVision
test "the range is the token's own radius when it has vision, else the scene default":
var sc = loadScene(freshDb()[0]).get
var t = plain()
check visionRange(sc, t) == 400.0
t.visionRadius = some(250.0)
check visionRange(sc, t) == 250.0
t.flags = %*{} # no vision flag: the scene default, whatever the radius
check visionRange(sc, t) == 400.0
test "the effective radius is the scene default in this slice":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
check effectiveRadius(sc, plain()) == 20.0 # #4 default; token.resize is slice 7
suite "persistence (write-through, restart-identical)":
test "create assigns the id, stores every column and reloads identically":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain(owner = 0)
t.visionRadius = some(250.0)
let (outcome, stored) = addToken(conn, sc, t, @[])
check outcome == toOk
check stored.id.len == TokenIdLength
check stored.scene == 1
let reloaded = loadTokens(conn)
check reloaded.len == 1
let r = reloaded[0]
check r.id == stored.id
check r.kind == "npc"
check r.descriptiveName == "a grumpy man"
check r.actualName == "Lord Vex"
check r.pos == (100.0, 100.0)
check r.radius.isNone # NULL -> the scene default
check r.owner == GmControlled # NULL -> the GM
check not r.gmOnly
check r.visionRadius.get == 250.0
check r.flags["vision"].getBool
check r.hasVision
test "a controller round-trips, and a move rewrites only the position":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
discard createPlayerWithKey(conn)
let pid = parseInt(conn.getValue(sql"SELECT id FROM player WHERE role = 'player'"))
let (_, stored) = addToken(conn, sc, plain(owner = pid), @[])
var t = loadTokens(conn)[0]
check t.owner == pid
t.pos = (1200.5, 3400.25)
check writePosition(conn, t)
let after = loadTokens(conn)[0]
check after.pos == (1200.5, 3400.25)
check after.owner == pid
check after.descriptiveName == "a grumpy man"
test "update replaces the whole row and keeps the id":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, stored) = addToken(conn, sc, plain(), @[])
var changed = stored
changed.descriptiveName = "a tall stranger"
changed.actualName = "Lady Vex"
changed.gmOnly = true
changed.visionRadius = some(90.0)
changed.flags = %*{"vision": false}
check storeToken(conn, sc, changed) == toOk
let r = loadTokens(conn)[0]
check r.id == stored.id
check r.descriptiveName == "a tall stranger"
check r.gmOnly
check r.visionRadius.get == 90.0
check not r.hasVision
var invalid = changed
invalid.descriptiveName = ""
check storeToken(conn, sc, invalid) == toInvalid
check loadTokens(conn)[0].descriptiveName == "a tall stranger"
test "remove deletes the row; a second remove reports nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, stored) = addToken(conn, sc, plain(), @[])
check removeToken(conn, stored.id)
check loadTokens(conn).len == 0
check not removeToken(conn, stored.id)
test "player.remove hands the player's tokens to the GM (DESIGN 3.2)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let created = createPlayerWithKey(conn)
discard addToken(conn, sc, plain(owner = created.id), @[])
check loadTokens(conn)[0].owner == created.id
check removePlayer(conn, created.id)
let r = loadTokens(conn)[0]
check r.owner == GmControlled
check r.id.len == TokenIdLength
test "tokens load in creation order":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var ids: seq[string]
for i in 0 ..< 5:
let (_, t) = addToken(conn, sc, plain(x = float(i) * 10), @[])
ids.add t.id
check loadTokens(conn).mapIt(it.id) == ids
suite "validation (DESIGN 6.1)":
test "an out-of-bounds position writes nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
check addToken(conn, sc, plain(x = -1), @[]).outcome == toInvalid
check addToken(conn, sc, plain(y = 4097), @[]).outcome == toInvalid
check loadTokens(conn).len == 0
test "an empty name writes nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
t.actualName = ""
check addToken(conn, sc, t, @[]).outcome == toInvalid
check loadTokens(conn).len == 0
test "the same id is never handed out twice by the caller-supplied taken list":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var ids: seq[string]
for i in 0 ..< 20:
let (outcome, t) = addToken(conn, sc, plain(x = float(i)), ids)
check outcome == toOk
ids.add t.id
check ids.toHashSet.len == 20
test "a lookup by id is exact":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, t) = addToken(conn, sc, plain(), @[])
check tokenById(@[t], t.id).isSome
check tokenById(@[t], "").isNone
check tokenById(@[t], t.id & "x").isNone
suite "size, props and statuses (slice 7: #4, #22)":
test "a per-token radius round-trips and overrides the scene default (5.6)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
t.radius = some(35.0)
let (outcome, stored) = addToken(conn, sc, t, @[])
check outcome == toOk
check effectiveRadius(sc, stored) == 35.0
let reloaded = loadTokens(conn)[0]
check reloaded.radius.get == 35.0
check effectiveRadius(sc, reloaded) == 35.0
# null again = the scene default
var cleared = reloaded
cleared.radius = none(float)
check storeToken(conn, sc, cleared) == toOk
check loadTokens(conn)[0].radius.isNone
check effectiveRadius(sc, loadTokens(conn)[0]) == 20.0
test "a non-positive radius is refused, and nothing is written":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
t.radius = some(0.0)
check addToken(conn, sc, t, @[]).outcome == toInvalid
t.radius = some(-5.0)
check addToken(conn, sc, t, @[]).outcome == toInvalid
check loadTokens(conn).len == 0
test "the three property buckets round-trip unchanged (6.1, 8)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
t.props[pbPublic] = %*{"aura": "cold", "hp": 3}
t.props[pbOwner] = %*{"notes": ["a", "b"]}
t.props[pbGm] = %*{"secret": true}
let (outcome, stored) = addToken(conn, sc, t, @[])
check outcome == toOk
let r = loadTokens(conn)[0]
check r.props[pbPublic] == stored.props[pbPublic]
check r.props[pbOwner] == stored.props[pbOwner]
check r.props[pbGm] == stored.props[pbGm]
check r.props[pbPublic]["hp"].getInt == 3
check r.props[pbGm]["secret"].getBool
# an update rewrites the buckets with the row
var changed = r
changed.props[pbPublic] = %*{"aura": "warm"}
check storeToken(conn, sc, changed) == toOk
let after = loadTokens(conn)[0]
check after.props[pbPublic]["aura"].getStr == "warm"
check after.props[pbGm]["secret"].getBool
test "a new token starts with three empty buckets, never null":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
discard addToken(conn, sc, plain(), @[])
let r = loadTokens(conn)[0]
for b in PropBucket:
check r.props[b].kind == JObject
check r.props[b].len == 0
test "statuses round-trip sorted, and a store replaces them (5.5)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
# added out of order on purpose
t.statuses = @[(stSqueezed, ssGM), (stStuck, ssWalls), (stStuck, ssGM)]
let (outcome, stored) = addToken(conn, sc, t, @[])
check outcome == toOk
check stored.statuses == @[(stStuck, ssWalls), (stStuck, ssGM), (stSqueezed, ssGM)]
let r = loadTokens(conn)[0]
check r.statuses == stored.statuses
check r.isLocked
check r.hasStatus(stStuck, ssWalls)
check not r.hasStatus(stSqueezed, ssWalls)
# a full store replaces the set instead of appending to it
var cleared = r
cleared.statuses = @[(stStuck, ssGM)]
check storeToken(conn, sc, cleared) == toOk
check loadTokens(conn)[0].statuses == @[(stStuck, ssGM)]
var none_left = cleared
none_left.statuses = @[]
check storeToken(conn, sc, none_left) == toOk
check loadTokens(conn)[0].statuses.len == 0
check not loadTokens(conn)[0].isLocked
test "removing a token removes its status rows (FK cascade)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plain()
t.statuses = @[(stStuck, ssWalls)]
let (_, stored) = addToken(conn, sc, t, @[])
check parseInt(conn.getValue(sql"SELECT count(*) FROM entity_status")) == 1
check removeToken(conn, stored.id)
check parseInt(conn.getValue(sql"SELECT count(*) FROM entity_status")) == 0
test "status helpers keep the entry set unique and ordered":
var t = plain()
t.addStatus(stSqueezed, ssGM)
t.addStatus(stStuck, ssWalls)
t.addStatus(stStuck, ssWalls) # a duplicate changes nothing
check t.statuses == @[(stStuck, ssWalls), (stSqueezed, ssGM)]
check t.removeStatus(stStuck, ssWalls)
check not t.removeStatus(stStuck, ssWalls) # already gone
check t.statuses == @[(stSqueezed, ssGM)]
check t.isLocked