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.
This commit is contained in:
2026-11-15 11:02:43 +01:00
parent 81898ab69c
commit 20575f2147
6 changed files with 537 additions and 95 deletions
+22 -11
View File
@@ -38,9 +38,9 @@ suite "migrate":
check migrate(db) == LatestVersion check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion check schemaVersion(db) == LatestVersion
check LatestVersion == 5 check LatestVersion == 6
let rows = appliedMigrations(db) let rows = appliedMigrations(db)
check rows.len == 5 check rows.len == 6
check rows[0][0] == 1 check rows[0][0] == 1
check rows[0][1] == "meta" check rows[0][1] == "meta"
check rows[1][0] == 2 check rows[1][0] == 2
@@ -51,6 +51,8 @@ suite "migrate":
check rows[3][1] == "tokens" check rows[3][1] == "tokens"
check rows[4][0] == 5 check rows[4][0] == 5
check rows[4][1] == "explored" check rows[4][1] == "explored"
check rows[5][0] == 6
check rows[5][1] == "token details"
# the steps' own DDL ran: meta and the auth tables exist and are empty # 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 meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0" check db.getValue(sql"SELECT count(*) FROM player") == "0"
@@ -63,12 +65,16 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM entity") == "0" check db.getValue(sql"SELECT count(*) FROM entity") == "0"
# step 5 creates the explored chunk store (DESIGN 4.4), empty # step 5 creates the explored chunk store (DESIGN 4.4), empty
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0" check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
# step 6 adds the three prop buckets and the status table (DESIGN 5.5, 8), empty
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"
test "re-open is a no-op: no step applied, history and timestamps untouched": test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir() let d = tmpDir()
block: block:
let db = openFresh(d) let db = openFresh(d)
check migrate(db) == 5 check migrate(db) == 6
close(db) close(db)
let db = openFresh(d) let db = openFresh(d)
defer: defer:
@@ -77,7 +83,7 @@ suite "migrate":
let before = appliedMigrations(db) let before = appliedMigrations(db)
check migrate(db) == 0 check migrate(db) == 0
check migrate(db) == 0 check migrate(db) == 0
check schemaVersion(db) == 5 check schemaVersion(db) == 6
check appliedMigrations(db) == before check appliedMigrations(db) == before
test "history and user_version must agree": test "history and user_version must agree":
@@ -151,16 +157,17 @@ suite "migrate":
check schemaVersion(db) == 2 check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0" check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == 3 # steps 3, 4 and 5 run check migrate(db) == 4 # steps 3, 4, 5 and 6 run
check schemaVersion(db) == 5 check schemaVersion(db) == 6
check db.getValue(sql"SELECT count(*) FROM scene") == "1" 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 next_wall_id FROM scene WHERE id = 1") == "1"
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1" check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
check db.getValue(sql"SELECT count(*) FROM entity") == "0" check db.getValue(sql"SELECT count(*) FROM entity") == "0"
test "a slice-5 DB migrates on: explored_chunk appears and the world survives": test "a schema-4 DB migrates on: explored_chunk and entity_status appear, the world survives":
# A fixture DB from the previous schema version (4, the slice-5 server): scene, a player, a key # A fixture DB from the previous schema version (4, the slice-5 server): scene, a player, a key
# and a token already in it. Step 5 must add the explored store and leave all of it alone. # and a token already in it. Steps 5 and 6 must add the explored store, the prop buckets and the
# status table, and leave all of it alone.
let d = tmpDir() let d = tmpDir()
let db = openFresh(d) let db = openFresh(d)
defer: defer:
@@ -183,10 +190,14 @@ suite "migrate":
check schemaVersion(db) == 4 check schemaVersion(db) == 4
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0" check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0"
check migrate(db) == 1 # only step 5 runs check migrate(db) == 2 # steps 5 and 6 run
check schemaVersion(db) == 5 check schemaVersion(db) == 6
check appliedMigrations(db).len == 5 check appliedMigrations(db).len == 6
check appliedMigrations(db)[4] == (version: 5, name: "explored") check appliedMigrations(db)[4] == (version: 5, name: "explored")
check appliedMigrations(db)[5] == (version: 6, name: "token details")
# 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") == "{}{}{}"
# the explored store exists, with both FKs and the 512-byte chunk invariant # the explored store exists, with both FKs and the 512-byte chunk invariant
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0" check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
check db.getValue(sql"SELECT sql FROM sqlite_master WHERE name = 'explored_chunk'").contains("length(bits) = 512") check db.getValue(sql"SELECT sql FROM sqlite_master WHERE name = 'explored_chunk'").contains("length(bits) = 512")
+173 -75
View File
@@ -7,12 +7,13 @@ let other = Actor(role: rolePlayer, player: 2)
let gm = Actor(role: roleGM) let gm = Actor(role: roleGM)
proc scene(walls: seq[Wall], toks: seq[Token] = @[]): Scene = proc scene(walls: seq[Wall], toks: seq[Token] = @[]): Scene =
Scene(w: 4096, h: 4096, tokenRadius: R, visionDefault: 400, walls: walls, tokens: toks) Scene(w: 4096, h: 4096, visionDefault: 400, walls: walls, tokens: toks)
proc tok(x, y: float, owner = 1, vision = false, vr = 0.0): Token = proc tok(x, y: float, owner = 1, vision = false, vr = 0.0, radius = R): Token =
Token(pos: (x, y), owner: owner, hasVision: vision, visionRadius: vr) ## `radius` is the token's *effective* radius (5.6): worldmap.ruleToken resolves the scene default.
Token(pos: (x, y), owner: owner, radius: radius, hasVision: vision, visionRadius: vr)
proc clearOfWalls(sc: Scene, t: Token): bool = proc clearOfWalls(sc: Scene, t: Token): bool =
for w in sc.walls: for w in sc.walls:
if w.blocks and segDist(t.pos, w.a, w.b) < sc.tokenRadius: return false if w.blocks and segDist(t.pos, w.a, w.b) < t.radius: return false
true true
proc ok(sc: Scene, s, d: Vec, r = R): bool = pathClear(sc.walls, s, d, r) proc ok(sc: Scene, s, d: Vec, r = R): bool = pathClear(sc.walls, s, d, r)
@@ -136,12 +137,12 @@ suite "move rules: player vs GM, step cap, uniform nack":
check s.moveToken(me, 2, (500.0 + 400, 500.0)).kind == mkAck # vision flag, radius unset: default check s.moveToken(me, 2, (500.0 + 400, 500.0)).kind == mkAck # vision flag, radius unset: default
check s.moveToken(me, 2, (500.0 + 400 + 400.5, 500.0)).kind == mkNack check s.moveToken(me, 2, (500.0 + 400 + 400.5, 500.0)).kind == mkNack
check stepCap(s, s.tokens[1]) == 100 check stepCap(s, s.tokens[1]) == 100
test "over-cap, blocked-by-wall, blocked-flag and out-of-bounds nacks are identical": test "over-cap, wall, lock-flag and out-of-bounds nacks are identical":
var s = scene(@[W(200, 0, 200, 1000)], @[tok(100, 500), tok(100, 500), tok(100, 500)]) var s = scene(@[W(200, 0, 200, 1000)], @[tok(100, 500), tok(100, 500), tok(100, 500)])
s.tokens[2].blocked = true s.tokens[2].locked = true
let cap = s.moveToken(me, 0, (100.0 + 2000, 500.0)) # over cap, nothing in the way let cap = s.moveToken(me, 0, (100.0 + 2000, 500.0)) # over cap, nothing in the way
let wal = s.moveToken(me, 1, (300.0, 500.0)) # in cap, through the wall let wal = s.moveToken(me, 1, (300.0, 500.0)) # in cap, through the wall
let flg = s.moveToken(me, 2, (130.0, 500.0)) # in cap, clear, but blocked let flg = s.moveToken(me, 2, (130.0, 500.0)) # in cap, clear, but locked
let oob = s.moveToken(me, 0, (-5.0, 500.0)) let oob = s.moveToken(me, 0, (-5.0, 500.0))
let nan = s.moveToken(me, 0, (NaN, 500.0)) let nan = s.moveToken(me, 0, (NaN, 500.0))
for r in [cap, wal, flg, oob, nan]: for r in [cap, wal, flg, oob, nan]:
@@ -158,93 +159,93 @@ suite "move rules: player vs GM, step cap, uniform nack":
check s.moveToken(me, 0, (490.0, 100.0)).kind == mkNack # would overlap check s.moveToken(me, 0, (490.0, 100.0)).kind == mkNack # would overlap
check s.moveToken(me, 0, (470.0, 100.0)).kind == mkAck check s.moveToken(me, 0, (470.0, 100.0)).kind == mkAck
check s.moveToken(me, 0, (530.0, 100.0)).kind == mkNack # through check s.moveToken(me, 0, (530.0, 100.0)).kind == mkNack # through
test "GM: ignores walls, step cap and blocked; bounds still apply": test "GM: ignores walls, step cap and the lock; bounds still apply":
var s = scene(@[W(200, 0, 200, 1000)], @[tok(100, 500, vision = true, vr = 50)]) var s = scene(@[W(200, 0, 200, 1000)], @[tok(100, 500, vision = true, vr = 50)])
s.tokens[0].blocked = true s.tokens[0].stuckWalls = true
check s.moveToken(gm, 0, (300.0, 500.0)).kind == mkAck # through a wall check s.moveToken(gm, 0, (300.0, 500.0)).kind == mkAck # through a wall
check s.moveToken(gm, 0, (3000.0, 3000.0)).kind == mkAck # far beyond the cap check s.moveToken(gm, 0, (3000.0, 3000.0)).kind == mkAck # far beyond the cap
check s.moveToken(gm, 0, (200.0, 500.0)).kind == mkAck # onto the wall check s.moveToken(gm, 0, (200.0, 500.0)).kind == mkAck # onto the wall
check s.moveToken(gm, 0, (-1.0, 0.0)) == MoveResult(kind: mkNack, pos: (200.0, 500.0)) check s.moveToken(gm, 0, (-1.0, 0.0)) == MoveResult(kind: mkNack, pos: (200.0, 500.0))
check s.moveToken(gm, 0, (5000.0, 0.0)).kind == mkNack check s.moveToken(gm, 0, (5000.0, 0.0)).kind == mkNack
check s.tokens[0].blocked # ended on the wall: GM move set the flag check s.tokens[0].stuckWalls # ended on the wall: GM move set the flag
check s.moveToken(gm, 9, (1.0, 1.0)).kind == mkError check s.moveToken(gm, 9, (1.0, 1.0)).kind == mkError
suite "blocked flag": suite "stuck/squeezed statuses (walls source)":
proc blockedSc(): Scene = scene(@[], @[tok(100, 100), tok(100, 300, owner = NoOwner), tok(900, 900)]) proc stuckSc(): Scene = scene(@[], @[tok(100, 100), tok(100, 300, owner = NoOwner), tok(900, 900)])
test "wall added within r of the circle (centre not on it) sets blocked; exactly r does not": test "wall added within r of the circle (centre not on it) sets stuck; exactly r does not":
var s = blockedSc() var s = stuckSc()
discard s.addWall(W(115, 0, 115, 200)) # 15 from token 0's centre: circle overlaps discard s.addWall(W(115, 0, 115, 200)) # 15 from token 0's centre: circle overlaps
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check not s.tokens[1].blocked # wall ends at y=200, token 1 is at y=300 check not s.tokens[1].stuckWalls # wall ends at y=200, token 1 is at y=300
check not s.tokens[2].blocked check not s.tokens[2].stuckWalls
var t = blockedSc() var t = stuckSc()
discard t.addWall(W(120, 0, 120, 200)) # exactly r: clear discard t.addWall(W(120, 0, 120, 200)) # exactly r: clear
check not t.tokens[0].blocked check not t.tokens[0].stuckWalls
test "GM-controlled tokens get the flag too; wall bbox does not matter, distance does": test "GM-controlled tokens get the flag too; wall bbox does not matter, distance does":
var s = blockedSc() var s = stuckSc()
discard s.addWall(W(0, 310, 200, 310)) discard s.addWall(W(0, 310, 200, 310))
check s.tokens[1].blocked and not s.tokens[0].blocked check s.tokens[1].stuckWalls and not s.tokens[0].stuckWalls
test "open door added or opened never sets; closing a door on a token pushes it, never sets": test "open door added or opened never sets; closing a door on a token pushes it, never sets":
var s = blockedSc() var s = stuckSc()
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.setDoor(id, false) check s.setDoor(id, false)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.tokens[0].pos != (100.0, 100.0) check s.tokens[0].pos != (100.0, 100.0)
test "blocked token: player moves refused, GM move allowed": test "a stuck token: player moves refused, GM move allowed":
var s = blockedSc() var s = stuckSc()
discard s.addWall(W(110, 0, 110, 200)) discard s.addWall(W(110, 0, 110, 200))
check s.moveToken(me, 0, (40.0, 100.0)).kind == mkNack # would be a perfectly clear step check s.moveToken(me, 0, (40.0, 100.0)).kind == mkNack # would be a perfectly clear step
check s.tokens[0].pos == (100.0, 100.0) check s.tokens[0].pos == (100.0, 100.0)
check s.moveToken(gm, 0, (40.0, 100.0)).kind == mkAck # GM bypasses `blocked` check s.moveToken(gm, 0, (40.0, 100.0)).kind == mkAck # GM bypasses the lock
check not s.tokens[0].blocked # and landed clear of every wall: cleared check not s.tokens[0].stuckWalls # and landed clear of every wall: cleared
test "cleared by removing the wall; unrelated removals keep it": test "cleared by removing the wall; unrelated removals keep it":
var s = blockedSc() var s = stuckSc()
let a = s.addWall(W(110, 0, 110, 200)) let a = s.addWall(W(110, 0, 110, 200))
let b = s.addWall(W(2000, 0, 2000, 200)) let b = s.addWall(W(2000, 0, 2000, 200))
check s.removeWall(b) check s.removeWall(b)
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.removeWall(a) check s.removeWall(a)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.moveToken(me, 0, (40.0, 100.0)).kind == mkAck check s.moveToken(me, 0, (40.0, 100.0)).kind == mkAck
check not s.removeWall(5) check not s.removeWall(5)
test "cleared by opening the door; a second open is a no-op": test "cleared by opening the door; a second open is a no-op":
var s = blockedSc() var s = stuckSc()
let id = s.addWall(W(110, 0, 110, 200, door = true)) let id = s.addWall(W(110, 0, 110, 200, door = true))
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.setDoor(id, true) check s.setDoor(id, true)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.setDoor(id, true) check s.setDoor(id, true)
check not s.setDoor(77, true) check not s.setDoor(77, true)
var w = blockedSc() var w = stuckSc()
check not w.setDoor(w.addWall(W(110, 0, 110, 200)), true) # a plain wall is not a door check not w.setDoor(w.addWall(W(110, 0, 110, 200)), true) # a plain wall is not a door
check w.tokens[0].blocked check w.tokens[0].stuckWalls
test "cleared by the GM; not re-set by itself": test "cleared by the GM; not re-set by itself":
var s = blockedSc() var s = stuckSc()
discard s.addWall(W(110, 0, 110, 200)) discard s.addWall(W(110, 0, 110, 200))
s.gmClearBlocked(0) s.gmClearBlocked(0)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.moveToken(me, 0, (100.0, 150.0)).kind == mkNack # clear flag, but the capsule still refuses (overlap, dest overlaps) check s.moveToken(me, 0, (100.0, 150.0)).kind == mkNack # clear flag, but the capsule still refuses (overlap, dest overlaps)
check s.moveToken(me, 0, (40.0, 100.0)).kind == mkAck # and it can walk out (escape) check s.moveToken(me, 0, (40.0, 100.0)).kind == mkAck # and it can walk out (escape)
test "wall update = remove then add": test "wall update = remove then add":
var s = blockedSc() var s = stuckSc()
let id = s.addWall(W(110, 0, 110, 200)) let id = s.addWall(W(110, 0, 110, 200))
check s.updateWall(id, W(500, 0, 500, 200)) # moved away: clears check s.updateWall(id, W(500, 0, 500, 200)) # moved away: clears
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.updateWall(id, W(105, 0, 105, 200)) # moved onto the token: sets check s.updateWall(id, W(105, 0, 105, 200)) # moved onto the token: sets
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.updateWall(id, W(110, 0, 110, 200, door = true, open = true)) # became an open door: clears check s.updateWall(id, W(110, 0, 110, 200, door = true, open = true)) # became an open door: clears
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check not s.updateWall(9, W(0, 0, 1, 1)) check not s.updateWall(9, W(0, 0, 1, 1))
test "GM placement and GM move onto a wall: blocked; player escape works only after a GM clear": test "GM placement and GM move onto a wall: blocked; player escape works only after a GM clear":
var s = scene(@[W(500, 0, 500, 1000)]) var s = scene(@[W(500, 0, 500, 1000)])
let i = s.addToken(tok(500, 400)) # placed exactly on the wall let i = s.addToken(tok(500, 400)) # placed exactly on the wall
check s.tokens[i].blocked check s.tokens[i].stuckWalls
check s.moveToken(me, i, (530.0, 400.0)).kind == mkNack # stuck check s.moveToken(me, i, (530.0, 400.0)).kind == mkNack # stuck
s.gmClearBlocked(i) s.gmClearBlocked(i)
check s.moveToken(me, i, (530.0, 400.0)).kind == mkAck # escape sideways check s.moveToken(me, i, (530.0, 400.0)).kind == mkAck # escape sideways
check s.moveToken(gm, i, (505.0, 400.0)).kind == mkAck # GM puts it back within r check s.moveToken(gm, i, (505.0, 400.0)).kind == mkAck # GM puts it back within r
check s.tokens[i].blocked check s.tokens[i].stuckWalls
s.gmClearBlocked(i) s.gmClearBlocked(i)
check s.moveToken(me, i, (505.0, 450.0)).kind == mkNack # still overlapped: refused check s.moveToken(me, i, (505.0, 450.0)).kind == mkNack # still overlapped: refused
check s.moveToken(me, i, (540.0, 400.0)).kind == mkAck # but it can leave check s.moveToken(me, i, (540.0, 400.0)).kind == mkAck # but it can leave
@@ -258,7 +259,7 @@ suite "blocked flag":
check s.tokens[0].pos.x >= 120.0 and s.tokens[0].pos.x < 120.001 and s.tokens[0].pos.y == 100.0 check s.tokens[0].pos.x >= 120.0 and s.tokens[0].pos.x < 120.001 and s.tokens[0].pos.y == 100.0
check s.tokens[1].pos.x <= 80.0 and s.tokens[1].pos.x > 79.999 check s.tokens[1].pos.x <= 80.0 and s.tokens[1].pos.x > 79.999
check s.tokens[2].pos == (130.0, 100.0) check s.tokens[2].pos == (130.0, 100.0)
for t in s.tokens: check not t.blocked and clearOfWalls(s, t) for t in s.tokens: check not t.stuckWalls and clearOfWalls(s, t)
check s.moveToken(me, 0, (150.0, 100.0)).kind == mkAck check s.moveToken(me, 0, (150.0, 100.0)).kind == mkAck
test "push: centre on the door line -> side of the previous position; no history -> left of a->b": test "push: centre on the door line -> side of the previous position; no history -> left of a->b":
for (prev, wantLeft) in [((130.0, 100.0), false), ((60.0, 100.0), true)]: # door runs +y: left = -x for (prev, wantLeft) in [((130.0, 100.0), false), ((60.0, 100.0), true)]: # door runs +y: left = -x
@@ -271,7 +272,7 @@ suite "blocked flag":
var s = scene(@[], @[tok(100, 100)]) var s = scene(@[], @[tok(100, 100)])
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
check s.setDoor(id, false) check s.setDoor(id, false)
check s.tokens[0].pos.x < 100.0 and not s.tokens[0].blocked # default: left side check s.tokens[0].pos.x < 100.0 and not s.tokens[0].stuckWalls # default: left side
test "push: past the end of the door the offset shrinks (minimal), still >= r from the door": test "push: past the end of the door the offset shrinks (minimal), still >= r from the door":
var s = scene(@[], @[tok(110, 160)]) # 10 beyond the end a-b = (100,50)-(100,150): dist 14.1 < 20 var s = scene(@[], @[tok(110, 160)]) # 10 beyond the end a-b = (100,50)-(100,150): dist 14.1 < 20
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
@@ -283,25 +284,28 @@ suite "blocked flag":
var s = scene(@[W(125, 0, 125, 300)], @[tok(110, 100)]) # +x side lands at 120, 5 from the wall var s = scene(@[W(125, 0, 125, 300)], @[tok(110, 100)]) # +x side lands at 120, 5 from the wall
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
check s.setDoor(id, false) check s.setDoor(id, false)
check s.tokens[0].pos.x <= 80.0 and not s.tokens[0].blocked check s.tokens[0].pos.x <= 80.0 and not s.tokens[0].stuckWalls
var b = scene(@[], @[tok(110, 100)]) var b = scene(@[], @[tok(110, 100)])
let j = b.addWall(W(100, 50, 100, 150, door = true, open = true)) let j = b.addWall(W(100, 50, 100, 150, door = true, open = true))
b.w = 110 # +x side (120) is out of bounds b.w = 110 # +x side (120) is out of bounds
check b.setDoor(j, false) check b.setDoor(j, false)
check b.tokens[0].pos.x <= 80.0 and not b.tokens[0].blocked check b.tokens[0].pos.x <= 80.0 and not b.tokens[0].stuckWalls
test "push: both sides invalid -> blocked in place; door open -> free; GM can still move it": test "push: both sides invalid -> squeezed in place; door open -> still squeezed (KEEP); GM can move it":
var s = scene(@[W(125, 0, 125, 300), W(75, 0, 75, 300)], @[tok(110, 100)]) var s = scene(@[W(125, 0, 125, 300), W(75, 0, 75, 300)], @[tok(110, 100)])
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
var pushed: seq[Push] var pushed: seq[Push]
check s.setDoor(id, false, pushed) check s.setDoor(id, false, pushed)
check pushed.len == 0 and s.tokens[0].blocked and s.tokens[0].pos == (110.0, 100.0) check pushed.len == 0 and s.tokens[0].squeezedWalls and not s.tokens[0].stuckWalls
check s.tokens[0].pos == (110.0, 100.0)
check s.moveToken(me, 0, (112.0, 100.0)).kind == mkNack check s.moveToken(me, 0, (112.0, 100.0)).kind == mkNack
check s.setDoor(id, true) check s.setDoor(id, true)
check s.tokens[0].blocked # 125-wall still overlaps (KEEP) check s.tokens[0].squeezedWalls # 125-wall still overlaps (KEEP)
check s.moveToken(gm, 0, (400.0, 100.0)).kind == mkAck
check not s.tokens[0].squeezedWalls # GM moved it clear
test "push: wall added on a token still sticks it (regression); closing on nobody pushes nobody": test "push: wall added on a token still sticks it (regression); closing on nobody pushes nobody":
var s = scene(@[], @[tok(110, 100)]) var s = scene(@[], @[tok(110, 100)])
discard s.addWall(W(100, 50, 100, 150)) discard s.addWall(W(100, 50, 100, 150))
check s.tokens[0].blocked and s.tokens[0].pos == (110.0, 100.0) check s.tokens[0].stuckWalls and s.tokens[0].pos == (110.0, 100.0)
var t = scene(@[], @[tok(300, 300)]) var t = scene(@[], @[tok(300, 300)])
let id = t.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = t.addWall(W(100, 50, 100, 150, door = true, open = true))
var pushed: seq[Push] var pushed: seq[Push]
@@ -310,7 +314,7 @@ suite "blocked flag":
var s = scene(@[], @[tok(100, 100)]) var s = scene(@[], @[tok(100, 100)])
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true)) let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
check s.setDoor(id, false) check s.setDoor(id, false)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
let p = s.tokens[0].pos let p = s.tokens[0].pos
check s.moveToken(me, 0, (p.x - 40.0, 100.0)).kind == mkAck check s.moveToken(me, 0, (p.x - 40.0, 100.0)).kind == mkAck
check s.setDoor(id, true) and s.setDoor(id, false) check s.setDoor(id, true) and s.setDoor(id, false)
@@ -319,56 +323,56 @@ suite "blocked flag":
var s = scene(@[], @[tok(100, 100)]) var s = scene(@[], @[tok(100, 100)])
let a = s.addWall(W(110, 0, 110, 200)) let a = s.addWall(W(110, 0, 110, 200))
let door = s.addWall(W(100, 0, 100, 200, door = true)) let door = s.addWall(W(100, 0, 100, 200, door = true))
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.setDoor(door, true) check s.setDoor(door, true)
check s.tokens[0].blocked # plain wall still overlaps check s.tokens[0].stuckWalls # plain wall still overlaps
check s.moveToken(me, 0, (40.0, 100.0)).kind == mkNack check s.moveToken(me, 0, (40.0, 100.0)).kind == mkNack
check s.removeWall(a) check s.removeWall(a)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
var t = scene(@[], @[tok(100, 100)]) var t = scene(@[], @[tok(100, 100)])
let x = t.addWall(W(110, 0, 110, 200)) let x = t.addWall(W(110, 0, 110, 200))
let y = t.addWall(W(90, 0, 90, 200)) let y = t.addWall(W(90, 0, 90, 200))
check t.removeWall(y) check t.removeWall(y)
check t.tokens[0].blocked check t.tokens[0].stuckWalls
check t.removeWall(x) check t.removeWall(x)
check not t.tokens[0].blocked check not t.tokens[0].stuckWalls
test "KEEP: wall update away from one of two overlapping walls keeps blocked": test "KEEP: wall update away from one of two overlapping walls keeps blocked":
var s = scene(@[], @[tok(100, 100)]) var s = scene(@[], @[tok(100, 100)])
let a = s.addWall(W(110, 0, 110, 200)) let a = s.addWall(W(110, 0, 110, 200))
let b = s.addWall(W(90, 0, 90, 200)) let b = s.addWall(W(90, 0, 90, 200))
check s.updateWall(b, W(500, 0, 500, 200)) check s.updateWall(b, W(500, 0, 500, 200))
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.updateWall(a, W(500, 0, 500, 100)) check s.updateWall(a, W(500, 0, 500, 100))
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
test "GM moves a stuck token clear -> free; to another wall-overlapping spot -> still blocked": test "GM moves a stuck token clear -> free; to another wall-overlapping spot -> still blocked":
var s = scene(@[W(110, 0, 110, 200), W(500, 0, 500, 200)], @[]) var s = scene(@[W(110, 0, 110, 200), W(500, 0, 500, 200)], @[])
let i = s.addToken(tok(100, 100)) let i = s.addToken(tok(100, 100))
check s.tokens[i].blocked check s.tokens[i].stuckWalls
check s.moveToken(gm, i, (505.0, 100.0)).kind == mkAck check s.moveToken(gm, i, (505.0, 100.0)).kind == mkAck
check s.tokens[i].blocked # other wall overlaps check s.tokens[i].stuckWalls # other wall overlaps
check s.moveToken(gm, i, (300.0, 100.0)).kind == mkAck check s.moveToken(gm, i, (300.0, 100.0)).kind == mkAck
check not s.tokens[i].blocked check not s.tokens[i].stuckWalls
check s.moveToken(me, i, (330.0, 100.0)).kind == mkAck check s.moveToken(me, i, (330.0, 100.0)).kind == mkAck
test "GM drops a token inside a wall -> blocked; a door counts only while closed": test "GM drops a token inside a wall -> blocked; a door counts only while closed":
var s = scene(@[W(110, 0, 110, 200, door = true, open = true)], @[tok(300, 300), tok(100, 100)]) var s = scene(@[W(110, 0, 110, 200, door = true, open = true)], @[tok(300, 300), tok(100, 100)])
check not s.tokens[1].blocked check not s.tokens[1].stuckWalls
check s.moveToken(gm, 0, (100.0, 100.0)).kind == mkAck check s.moveToken(gm, 0, (100.0, 100.0)).kind == mkAck
check not s.tokens[0].blocked # open door: no wall check not s.tokens[0].stuckWalls # open door: no wall
check s.setDoor(0, false) # both pushed clear, none stuck check s.setDoor(0, false) # both pushed clear, none stuck
check not s.tokens[0].blocked and not s.tokens[1].blocked check not s.tokens[0].stuckWalls and not s.tokens[1].stuckWalls
check s.moveToken(gm, 0, (112.0, 100.0)).kind == mkAck # GM drop back inside the closed door: stuck check s.moveToken(gm, 0, (112.0, 100.0)).kind == mkAck # GM drop back inside the closed door: stuck
check s.tokens[0].blocked check s.tokens[0].stuckWalls
check s.setDoor(0, true) check s.setDoor(0, true)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
var t = scene(@[W(110, 0, 110, 200)], @[tok(300, 300)]) var t = scene(@[W(110, 0, 110, 200)], @[tok(300, 300)])
check t.moveToken(gm, 0, (100.0, 100.0)).kind == mkAck check t.moveToken(gm, 0, (100.0, 100.0)).kind == mkAck
check t.tokens[0].blocked check t.tokens[0].stuckWalls
test "GM manual clear inside a wall: player escapes sideways, cannot cross": test "GM manual clear inside a wall: player escapes sideways, cannot cross":
var s = scene(@[W(500, 0, 500, 1000)], @[tok(500, 400)]) var s = scene(@[W(500, 0, 500, 1000)], @[tok(500, 400)])
check s.moveToken(gm, 0, (505.0, 400.0)).kind == mkAck check s.moveToken(gm, 0, (505.0, 400.0)).kind == mkAck
check s.tokens[0].blocked check s.tokens[0].stuckWalls
s.gmClearBlocked(0) s.gmClearBlocked(0)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.moveToken(me, 0, (530.0, 400.0)).kind == mkAck # sideways out check s.moveToken(me, 0, (530.0, 400.0)).kind == mkAck # sideways out
var t = scene(@[W(500, 0, 500, 1000)], @[tok(505, 400)]) var t = scene(@[W(500, 0, 500, 1000)], @[tok(505, 400)])
t.gmClearBlocked(0) t.gmClearBlocked(0)
@@ -376,16 +380,16 @@ suite "blocked flag":
check t.moveToken(me, 0, (510.0, 450.0)).kind == mkNack # destination still overlapping check t.moveToken(me, 0, (510.0, 450.0)).kind == mkNack # destination still overlapping
test "an unrelated wall change elsewhere does not re-block a GM-cleared token": test "an unrelated wall change elsewhere does not re-block a GM-cleared token":
var s = scene(@[W(110, 0, 110, 200)], @[tok(100, 100)]) var s = scene(@[W(110, 0, 110, 200)], @[tok(100, 100)])
s.tokens[0].blocked = true s.tokens[0].stuckWalls = true
s.gmClearBlocked(0) s.gmClearBlocked(0)
let far = s.addWall(W(2000, 0, 2000, 200)) let far = s.addWall(W(2000, 0, 2000, 200))
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
check s.updateWall(far, W(2100, 0, 2100, 200)) check s.updateWall(far, W(2100, 0, 2100, 200))
check s.removeWall(far) check s.removeWall(far)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
let d = s.addWall(W(3000, 0, 3000, 200, door = true)) let d = s.addWall(W(3000, 0, 3000, 200, door = true))
check s.setDoor(d, true) and s.setDoor(d, false) check s.setDoor(d, true) and s.setDoor(d, false)
check not s.tokens[0].blocked check not s.tokens[0].stuckWalls
suite "seed scene": suite "seed scene":
test "no escape hatch: a player cannot walk through any wall of a boxed room": test "no escape hatch: a player cannot walk through any wall of a boxed room":
@@ -396,3 +400,97 @@ suite "seed scene":
check r.kind == mkNack check r.kind == mkNack
check r.pos == p check r.pos == p
check s.moveToken(me, 0, (370.0, 200.0)).kind == mkAck # 30 from the wall check s.moveToken(me, 0, (370.0, 200.0)).kind == mkAck # 30 from the wall
suite "per-token radius (5.6, #4)":
test "the overlap test, the escape and the push use the token's own radius":
# a token the scene default (20) would refuse, but whose own radius is 10, fits in the gap
var s = scene(@[W(0, -100, 0, 100)])
var small = tok(15, 0, radius = 10.0)
s.tokens = @[small]
check s.moveToken(me, 0, (15.0, 40.0)).kind == mkAck # 15 away: clear for r=10
var big = scene(@[W(0, -100, 0, 100)], @[tok(15, 0, radius = 20.0)])
check big.moveToken(me, 0, (15.0, 40.0)).kind == mkNack # still overlapping with r=20
test "a big token is refused where a small one passes, on the same geometry":
var s = scene(@[W(0, -100, 0, 100)], @[tok(30, 0, radius = 40.0)])
check not s.tokens[0].stuckWalls # set directly, not by the rules
check s.moveToken(me, 0, (30.0, 60.0)).kind == mkNack # escaping, but the destination overlaps
check s.moveToken(me, 0, (90.0, 0.0)).kind == mkAck # away from the wall: clear of r=40
test "the door push clears the token's own radius":
var s = scene(@[], @[tok(110, 100, radius = 40.0)])
let id = s.addWall(W(100, 50, 100, 150, door = true, open = true))
check s.setDoor(id, false)
check segDist(s.tokens[0].pos, (100.0, 50.0), (100.0, 150.0)) >= 40.0
check s.tokens[0].pos.x >= 140.0
suite "resize: shrink never pushes, grow pushes or squeezes (5.6)":
test "a grow that already fits does not move the token":
var s = scene(@[W(0, -100, 0, 100)], @[tok(400, 0, radius = 20.0)])
let before = s.tokens[0].pos
check s.resizeToken(0, 30.0) == rkUnchanged
check s.tokens[0].pos == before and s.tokens[0].radius == 30.0
test "grow inside r of a wall pushes it out by the minimal perpendicular distance":
var s = scene(@[W(0, -100, 0, 100)], @[tok(15, 0, radius = 10.0)])
check s.tokens[0].stuckWalls == false
check s.resizeToken(0, 30.0) == rkPushed
check s.tokens[0].radius == 30.0
check abs(s.tokens[0].pos.x - 30.0) <= 1e-4 # 30 from the wall, on the side it was on
check s.tokens[0].pos.y == 0.0 # perpendicular: no along-axis drift
check s.tokens[0].prev == (15.0, 0.0) and s.tokens[0].hasPrev
test "grow with no room on either side squeezes the token and leaves it in place":
var s = scene(@[W(0, -300, 0, 300), W(60, -300, 60, 300)], @[tok(30, 0, radius = 10.0)])
check s.resizeToken(0, 40.0) == rkSqueezed
check s.tokens[0].squeezedWalls and not s.tokens[0].stuckWalls
check s.tokens[0].pos == (30.0, 0.0)
check s.moveToken(me, 0, (31.0, 0.0)).kind == mkNack # locked for its player
test "a squeeze from a failed grow clears when a later shrink ends the overlap":
var s = scene(@[W(0, -300, 0, 300), W(60, -300, 60, 300)], @[tok(30, 0, radius = 10.0)])
check s.resizeToken(0, 40.0) == rkSqueezed
check s.resizeToken(0, 10.0) == rkUnchanged
check not s.tokens[0].squeezedWalls # shrink ended the overlap: CLEAR
check s.moveToken(me, 0, (45.0, 0.0)).kind == mkAck # and the token is free again
test "a shrink that still overlaps keeps the stuck entry":
var s = scene(@[W(0, -300, 0, 300)], @[tok(15, 0, radius = 30.0)])
s.tokens[0].stuckWalls = true # as a wall add would have set it
check s.resizeToken(0, 20.0) == rkUnchanged
check s.tokens[0].stuckWalls # 15 < 20: still overlapping
check s.resizeToken(0, 10.0) == rkUnchanged
check not s.tokens[0].stuckWalls # 15 >= 10: clear
test "a grow out of a corner relaxes off both walls":
let corner = @[W(1000, 900, 1000, 1100), W(900, 1000, 1100, 1000)]
var s = scene(corner, @[tok(985, 985, radius = 10.0)])
check s.resizeToken(0, 30.0) == rkPushed
check segDist(s.tokens[0].pos, (1000.0, 900.0), (1000.0, 1100.0)) >= 30.0 - 1e-6
check segDist(s.tokens[0].pos, (900.0, 1000.0), (1100.0, 1000.0)) >= 30.0 - 1e-6
check s.tokens[0].pos.x < 1000.0 and s.tokens[0].pos.y < 1000.0 # pushed away from both
test "a grow that would have to cross a wall squeezes instead of jumping through it":
# a corridor narrower than the grown token: the relaxation may not step across x=500 or x=540
var s = scene(@[W(500, 0, 500, 900), W(540, 0, 540, 900)], @[tok(505, 400, radius = 15.0)])
check s.resizeToken(0, 40.0) == rkSqueezed
check s.tokens[0].squeezedWalls and not s.tokens[0].stuckWalls
check s.tokens[0].pos == (505.0, 400.0)
test "a grow that would leave the world squeezes instead of teleporting the token":
var s = scene(@[W(20, -400, 20, 400)], @[tok(10, 0, radius = 5.0)])
s.w = 15.0 # 25 px either side, r = 30 needs 30
check s.resizeToken(0, 30.0) == rkSqueezed
check s.tokens[0].squeezedWalls and s.tokens[0].pos == (10.0, 0.0)
test "resize ignores an out-of-range token index":
var s = scene(@[], @[])
check s.resizeToken(3, 30.0) == rkUnchanged
suite "status sources (5.5: walls and GM are independent entries)":
test "a GM-sourced lock refuses player moves without touching the walls entries":
var s = scene(@[], @[tok(100, 100)])
s.tokens[0].locked = true # what a GM-sourced entry means to the rules
check s.moveToken(me, 0, (140.0, 100.0)).kind == mkNack
check s.moveToken(gm, 0, (140.0, 100.0)).kind == mkAck # the GM always moves it
check not s.tokens[0].stuckWalls
test "a wall added over a GM-locked token only adds the walls entry":
var s = scene(@[], @[tok(100, 100)])
s.tokens[0].locked = true
discard s.addWall(W(110, 0, 110, 200))
check s.tokens[0].stuckWalls
test "the GM clear of the walls entries leaves a GM-sourced entry alone (no rule runs)":
var s = scene(@[W(110, 0, 110, 200)], @[tok(100, 100)])
s.tokens[0].stuckWalls = true
s.gmClearBlocked(0)
check not s.tokens[0].stuckWalls and not s.tokens[0].squeezedWalls
+8 -7
View File
@@ -3,14 +3,14 @@
## Attacker model: owns one token and may send any destination, any number of times (rate limit is a transport ## Attacker model: owns one token and may send any destination, any number of times (rate limit is a transport
## concern, M3). It sees only the reply (ack/nack + position), exactly what the wire carries. ## concern, M3). It sees only the reply (ack/nack + position), exactly what the wire carries.
## ##
## CONCRETE BOUND B = stepCap + tokenRadius (token vision radius, or the scene default, plus r): ## CONCRETE BOUND B = stepCap + r (token vision radius, or the scene default, plus the token radius):
## P1 a probe longer than the cap always gets the same nack, whatever the walls and doors are; ## P1 a probe longer than the cap always gets the same nack, whatever the walls and doors are;
## P2 the reply to any probe from position s depends on walls only within distance B of s; so by induction two ## P2 the reply to any probe from position s depends on walls only within distance B of s; so by induction two
## scenes that differ only in walls/doors farther than B from every position the token ever occupied produce ## scenes that differ only in walls/doors farther than B from every position the token ever occupied produce
## IDENTICAL reply sequences (no wall or door state beyond B is recoverable, however many probes); ## IDENTICAL reply sequences (no wall or door state beyond B is recoverable, however many probes);
## P3 inside B, one probe yields one bit (ack/nack): it can reveal walls behind a wall within the disc, which is ## P3 inside B, one probe yields one bit (ack/nack): it can reveal walls behind a wall within the disc, which is
## what the cap allows (cap = LOS radius); the negative control shows the harness does detect that; ## what the cap allows (cap = LOS radius); the negative control shows the harness does detect that;
## P4 nacks mutate nothing (position, blocked flag), so probing cannot be used to move or unflag a token. ## P4 nacks mutate nothing (position, lock status), so probing cannot be used to move or unlock a token.
import std/[unittest, math] import std/[unittest, math]
import geometry, moverules, testutil import geometry, moverules, testutil
@@ -22,8 +22,9 @@ const
let me = Actor(role: rolePlayer, player: 1) let me = Actor(role: rolePlayer, player: 1)
proc mkScene(walls: seq[Wall]): Scene = proc mkScene(walls: seq[Wall]): Scene =
Scene(w: WorldW, h: WorldW, tokenRadius: R, visionDefault: Cap, walls: walls, Scene(w: WorldW, h: WorldW, visionDefault: Cap, walls: walls,
tokens: @[Token(pos: (300.0, 2000.0), owner: 1, hasVision: true, visionRadius: Cap)]) tokens: @[Token(pos: (300.0, 2000.0), owner: 1, radius: R, hasVision: true,
visionRadius: Cap)])
type Trace = object type Trace = object
replies: seq[MoveResult] replies: seq[MoveResult]
@@ -106,14 +107,14 @@ suite "probing (T8)":
check ca.moveToken(me, 0, (500.0, 2000.0)).kind == mkAck check ca.moveToken(me, 0, (500.0, 2000.0)).kind == mkAck
check cb.moveToken(me, 0, (500.0, 2000.0)).kind == mkNack check cb.moveToken(me, 0, (500.0, 2000.0)).kind == mkNack
test "P4: probing cannot unflag or move a blocked token": test "P4: probing cannot unlock or move a locked token":
var s = mkScene(@[W(310, 1900, 310, 2100)]) # overlaps the token at (300,2000) var s = mkScene(@[W(310, 1900, 310, 2100)]) # overlaps the token at (300,2000)
s.tokens[0].blocked = true s.tokens[0].locked = true
var r = Rng(s: 11) var r = Rng(s: 11)
for i in 0 ..< 500: for i in 0 ..< 500:
let res = s.moveToken(me, 0, (r.uni(0, 600), r.uni(1700, 2300))) let res = s.moveToken(me, 0, (r.uni(0, 600), r.uni(1700, 2300)))
check res == MoveResult(kind: mkNack, pos: (300.0, 2000.0)) check res == MoveResult(kind: mkNack, pos: (300.0, 2000.0))
check s.tokens[0].blocked and s.tokens[0].pos == (300.0, 2000.0) check s.tokens[0].locked and s.tokens[0].pos == (300.0, 2000.0)
test "doors beyond the bound: opening or closing them changes no reply": test "doors beyond the bound: opening or closing them changes no reply":
var r = Rng(s: 31) var r = Rng(s: 31)
+135
View File
@@ -0,0 +1,135 @@
## Property buckets, caps and the schema registry (#22, DESIGN 6.1 prop payload rules, 8, 9). Pure
## unit tests: no DB, no socket. The wire behaviour (the ack codes, the bucket filtering a player
## sees) lives in tools/details.test.mjs and tests/tviews.nim.
import std/[algorithm, json, options, sequtils, strutils, tables, unittest]
import props
proc bucketed(): Props =
result = newProps()
result[pbPublic] = %*{"aura": "cold"}
result[pbOwner] = %*{"hp": 7}
result[pbGm] = %*{"secret": "yes"}
suite "caps (6.1, numbers FIXED owner-delegated by #22)":
test "64 keys per bucket, the 65th is refused and nothing changes":
var p = newProps()
for i in 0 ..< MaxPropKeys:
check p.setProp(pbPublic, "k" & $i, %i)
check p[pbPublic].len == MaxPropKeys
check not p.setProp(pbPublic, "one-too-many", %1)
check p[pbPublic].len == MaxPropKeys
check not p.contains(pbPublic, "one-too-many")
# a bucket has its own budget: the owner bucket is still empty
check p.setProp(pbOwner, "k0", %1)
test "an existing key can still be overwritten at the cap":
var p = newProps()
for i in 0 ..< MaxPropKeys: check p.setProp(pbPublic, "k" & $i, %i)
check p.setProp(pbPublic, "k0", %"replaced")
check p[pbPublic]["k0"].getStr == "replaced"
test "a key is 1..64 code points, trimmed, with no control characters":
check validPropKey("hp")
check validPropKey(repeat("x", MaxPropKeyLen))
check validPropKey("café") # code points, not bytes
check not validPropKey("")
check not validPropKey(" padded")
check not validPropKey("padded ")
check not validPropKey(repeat("x", MaxPropKeyLen + 1))
check not validPropKey("tab\there")
test "a value is at most 8 KB of serialized JSON":
var p = newProps()
let small = %repeat("x", 8000) # ~8 KB with the quotes
check valueBytes(small) <= MaxPropValueBytes
check p.setProp(pbPublic, "small", small)
let big = %repeat("x", MaxPropValueBytes + 1)
check valueBytes(big) > MaxPropValueBytes
suite "parseProps (the `props` field of token.create)":
test "absent and null mean three empty buckets":
for node in [JsonNode(nil), newJNull()]:
let parsed = parseProps(defaultRegistry(), node)
check parsed.isSome
for b in PropBucket: check parsed.get[b].kind == JObject and parsed.get[b].len == 0
test "the three bucket names are the only ones accepted":
let reg = defaultRegistry()
check parseProps(reg, %*{"public": {"a": 1}}).isSome
check parseProps(reg, %*{"public": {}, "owner": {}, "gm": {}}).isSome
check parseProps(reg, %*{"secret": {}}).isNone
check parseProps(reg, %*{"public": 3}).isNone
check parseProps(reg, %*{"public": {"k": newJNull()}}).isNone
check parseProps(reg, %*[1, 2]).isNone
check parseProps(reg, %*{"public": {"": 1}}).isNone
test "the caps are enforced while parsing":
let many = newJObject()
for i in 0 ..< MaxPropKeys + 1: many["k" & $i] = %i
check parseProps(defaultRegistry(), %*{"public": many}).isNone
let tooBig = newJObject()
tooBig["k"] = %repeat("x", MaxPropValueBytes + 1)
check parseProps(defaultRegistry(), %*{"public": tooBig}).isNone
suite "the registry (DESIGN 8/9: v1 is empty and permissive)":
test "with no entries every key is accepted in every bucket":
let reg = defaultRegistry()
for b in PropBucket:
check reg.checkWrite(b, "anything", %*{"nested": [1, 2, 3]})
check reg.checkWrite(b, "anything", %"text")
check reg.checkWrite(b, "anything", %12.5)
check reg.checkWrite(b, "anything", %true)
test "a registered key is enforced: kind and bucket":
var reg = defaultRegistry()
reg.schemas["hp"] = PropSchema(kind: pkNumber, bucket: some(pbOwner))
check reg.checkWrite(pbOwner, "hp", %7)
check not reg.checkWrite(pbOwner, "hp", %"seven") # wrong kind
check not reg.checkWrite(pbPublic, "hp", %7) # wrong bucket
check reg.checkWrite(pbPublic, "other", %"anything") # unregistered keys still use the fallback
check parseProps(reg, %*{"owner": {"hp": 3}}).isSome
check parseProps(reg, %*{"owner": {"hp": "three"}}).isNone
check parseProps(reg, %*{"public": {"hp": 3}}).isNone
test "a schema with no bucket accepts the key anywhere":
var reg = defaultRegistry()
reg.schemas["note"] = PropSchema(kind: pkString, bucket: none(PropBucket))
for b in PropBucket: check reg.checkWrite(b, "note", %"hi")
for b in PropBucket: check not reg.checkWrite(b, "note", %1)
suite "set / unset":
test "unsetting an absent key is allowed and reports it did nothing":
var p = bucketed()
check p.unsetProp(pbPublic, "aura")
check not p.contains(pbPublic, "aura")
check not p.unsetProp(pbPublic, "aura")
test "buckets are independent: the same key may live in all three":
var p = newProps()
check p.setProp(pbPublic, "hp", %1)
check p.setProp(pbOwner, "hp", %2)
check p.setProp(pbGm, "hp", %3)
check p[pbPublic]["hp"].getInt == 1
check p[pbOwner]["hp"].getInt == 2
check p[pbGm]["hp"].getInt == 3
test "propsJson carries all three buckets, always as objects":
let node = propsJson(bucketed())
check node.kind == JObject
check node.keys.toSeq.sorted == @["gm", "owner", "public"]
check node["public"]["aura"].getStr == "cold"
check node["gm"]["secret"].getStr == "yes"
test "clone gives fresh buckets: editing the copy cannot reach the original":
var original = bucketed()
var copy = original.clone()
check copy.setProp(pbPublic, "new", %1)
check copy.unsetProp(pbPublic, "aura")
check not original.contains(pbPublic, "new")
check original.contains(pbPublic, "aura")
check copy[pbOwner]["hp"].getInt == 7 # untouched values are shared, not lost
test "normalize repairs nil buckets":
var p: Props
let fixed = normalize(p)
for b in PropBucket: check fixed[b].kind == JObject
+126 -1
View File
@@ -4,7 +4,7 @@
## tools/tokens.test.mjs and the leak harness. ## tools/tokens.test.mjs and the leak harness.
import std/[json, options, os, sequtils, sets, strutils, unittest] import std/[json, options, os, sequtils, sets, strutils, unittest]
import db_connector/db_sqlite import db_connector/db_sqlite
import auth, db, tokens, world import auth, db, props, tokens, world
var tmpCount = 0 var tmpCount = 0
proc tmpDir(): string = proc tmpDir(): string =
@@ -257,3 +257,128 @@ suite "validation (DESIGN 6.1)":
check tokenById(@[t], t.id).isSome check tokenById(@[t], t.id).isSome
check tokenById(@[t], "").isNone check tokenById(@[t], "").isNone
check tokenById(@[t], t.id & "x").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
+73 -1
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 ## 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. ## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest] import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import geometry, tokens, views, vision, world import geometry, props, tokens, views, vision, world
const Pid = 2 # the subject player const Pid = 2 # the subject player
const Other = 3 # another player const Other = 3 # another player
@@ -223,3 +223,75 @@ suite "frames (6.1)":
check sceneJson["art_version"].getInt == 1 check sceneJson["art_version"].getInt == 1
for key in ["walls", "tokens", "entities", "walls_count", "count"]: for key in ["walls", "tokens", "entities", "walls_count", "count"]:
check not sceneJson.hasKey(key) check not sceneJson.hasKey(key)
suite "props and statuses (#22, 6.1: the bucket and the source are per-recipient)":
proc withProps(id: string, x, y: float, owner: int): TokenRec =
result = tok(id, x, y, owner)
result.props[pbPublic] = %*{"aura": "cold", "tag": "wolf"}
result.props[pbOwner] = %*{"hp": 7}
result.props[pbGm] = %*{"secret": "the duke"}
test "the GM frame carries all three buckets and the source of every status":
var t = withProps("a", 100, 100, 0)
t.statuses = @[(stStuck, ssWalls), (stSqueezed, ssGM)]
let frame = gmTokenFrame(gmView(ctxOf(sceneWith(@[]), @[t], @[Pid])).tokens[0])
check frame["props"].keys.toSeq.sorted == @["gm", "owner", "public"]
check frame["props"]["public"]["aura"].getStr == "cold"
check frame["props"]["owner"]["hp"].getInt == 7
check frame["props"]["gm"]["secret"].getStr == "the duke"
check frame["statuses"] == %*[{"status": "stuck", "source": "walls"},
{"status": "squeezed", "source": "GM"}]
test "a player who sees the token gets the public bucket only":
let sc = sceneWith(@[])
let tokens = @[withProps("mine", 400, 400, Pid), withProps("near", 500, 400, 0)]
let view = playerView(ctxOf(sc, tokens, @[Pid]), Pid)
let other = playerTokenFrame(view.tokens[1])
check other["props"].keys.toSeq == @["public"]
check other["props"]["public"]["tag"].getStr == "wolf"
check not other["props"].hasKey("owner")
check not other["props"].hasKey("gm")
test "the controller gets public + owner, never the gm bucket":
let sc = sceneWith(@[])
let view = playerView(ctxOf(sc, @[withProps("mine", 400, 400, Pid)], @[Pid]), Pid)
let frame = playerTokenFrame(view.tokens[0])
check frame["props"].keys.toSeq.sorted == @["owner", "public"]
check frame["props"]["owner"]["hp"].getInt == 7
check not frame["props"].hasKey("gm")
test "the controller is not told what caused a status either (5.5, 6.1 note 6)":
var t = withProps("mine", 400, 400, Pid)
t.statuses = @[(stStuck, ssWalls), (stSqueezed, ssGM)]
let frame = playerTokenFrame(playerView(ctxOf(sceneWith(@[]), @[t], @[Pid]), Pid).tokens[0])
check frame["statuses"] == %*[{"status": "stuck"}, {"status": "squeezed"}]
check "source" notin keysDeep(frame)
check frame["statuses"][0].len == 1
test "a prop change and a status change each reach a viewer as one `token` frame":
var ctx = ctxOf(sceneWith(@[]), @[withProps("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
check typesOf(pass(ctx, known)) == newSeq[string]()
var changed = ctx.tokens[0]
changed.props[pbPublic] = %*{"aura": "warm", "tag": "wolf"}
ctx.tokens[0] = changed
let frames = pass(ctx, known)
check typesOf(frames) == @["token"]
check frames[0]["props"]["public"]["aura"].getStr == "warm"
var stuck = ctx.tokens[0]
stuck.statuses = @[(stStuck, ssWalls)]
ctx.tokens[0] = stuck
let after = pass(ctx, known)
check typesOf(after) == @["token"]
check after[0]["statuses"] == %*[{"status": "stuck"}]
test "a radius change reaches every viewer as the effective radius":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[1].radius = some(35.0)
let frames = pass(ctx, known)
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