commit 008e2aff48a65a765c522eca0b4d2539ad6e5028 parent 9209d10da9b248a211b4b2384ec8572ff779ca38 Author: anon <anon@example.com> Date: Tue, 3 Nov 2026 07:10:29 +0000 Own fixture databases and drain sessions before cleanup Diffstat:
85 files changed, 275 insertions(+), 265 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -433,6 +433,11 @@ The full server suite includes many persistence and catalog cases and can exceed Go's default ten-minute timeout. See [tools/README.md](tools/README.md) for the smoke-test fixtures and tools. +Server fixtures use `newTestServer(t)` for an isolated directory and +`newServerForTest(t)` when reloading the current directory. Lazy fixtures +register `registerTestDatabaseCleanup(t, world)` before fallible operations. +These helpers drain live sessions before closing SQLite at scope exit. + For client smoke tests, confirm world loading has completed, open/close inventory (`I`) and map (`P`), move and turn, and inspect the rendered results. Use the browser harness below to wait for actual gameplay readiness. diff --git a/TODO.md b/TODO.md @@ -3642,6 +3642,13 @@ with payloads and known client/server provenance. test scopes repeated three times return both counts to zero after every scope. Cleanup is registered before fallible browser operations. This bounded fix does not establish full-suite resource bounds; see `local/fixture-cleanup-focused/`. + The wider ownership audit now routes all 78 direct test constructors through + registered cleanup. Lazy failure paths and world/chat session draining share + that lifecycle. Nested reload and live-nano + regressions reproduce retained connections and late logout writes respectively. + Focused lifecycle/race checks and a short two-character WASM bank/page/cold + check pass, returning handles/openers to zero. The instrumented full suite is + still running; evidence: `local/fixture-database-audit/`. - [ ] [P3] Reproduce stale shop interaction state after a live control-panel inventory edit. In the restoration smoke run, a nearby original terminal reported "Too far away" after the edit, while a fresh page could use it. diff --git a/server/aggdef_equipment_test.go b/server/aggdef_equipment_test.go @@ -106,7 +106,6 @@ func TestAggDefEquipmentOriginalWeaponCatalogAndTimings(t *testing.T) { func newAggDefEquipmentWorld(t *testing.T, template uint32) (*server, *combatTestConn) { t.Helper() world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.level, player.profession, player.nano = 200, 8, 5000 player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} diff --git a/server/armor_overequipping_test.go b/server/armor_overequipping_test.go @@ -17,7 +17,6 @@ func TestArmorOverequippingDustResourcesDamageAndRestart(t *testing.T) { } { t.Run(fmt.Sprint(scenario.computerLiteracy), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 1000, 850 @@ -61,7 +60,6 @@ func TestArmorOverequippingMetaplastTiersAndPerItemRounding(t *testing.T) { for _, stat := range []string{"strength", "agility"} { t.Run(fmt.Sprintf("%s/%d", stat, scenario.ability), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] for _, template := range []uint32{85686, 85742, 85742} { if granted, err := world.grantItem_locked(player, template); err != nil || !granted { @@ -111,7 +109,6 @@ func TestArmorOverequippingUsesInterpolatedRequirementsAtEachBoundary(t *testing } { t.Run(fmt.Sprintf("QL%d/%d", scenario.quality, scenario.strength), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = 461, 511 if granted, err := world.grantItem_locked(player, 85512); err != nil || !granted { @@ -224,7 +221,6 @@ func TestArmorOverequippingTitleRequirementIgnoresProfessionEquality(t *testing. }{{100, 750}, {49, 563}, {1, 188}} { t.Run(fmt.Sprint(scenario.level), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.level, player.profession, player.stats.Body.Adventuring = 100, 6, 1000 if granted, err := world.grantItem_locked(player, 206731); err != nil || !granted { @@ -248,7 +244,6 @@ func TestArmorOverequippingTitleRequirementIgnoresProfessionEquality(t *testing. func TestArmorOverequippingDoesNotUseThePreUniverseWieldRequirements(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.level = 150 player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy, player.stats.NanoAiding.TimeAndSpace = 1000, 1000, 1000 @@ -275,7 +270,6 @@ func TestArmorOverequippingSelectsRifleAndRangeButPreservesPioneerEffects(t *tes for _, template := range []uint32{157685, 156831} { t.Run(fmt.Sprint(template), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring = 1000 if granted, err := world.grantItem_locked(player, template); err != nil || !granted { diff --git a/server/armor_quality_persistence_test.go b/server/armor_quality_persistence_test.go @@ -13,7 +13,6 @@ func TestInterpolatedArmorBagSnapshotAndDeletion(t *testing.T) { for _, source := range []string{"ordinary", "container"} { t.Run(source, func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] world.grantItem_locked(player, 85557) world.grantItem_locked(player, 99228) @@ -98,7 +97,6 @@ func TestInterpolatedArmorLootRetainsQuality(t *testing.T) { func TestInterpolatedArmorReclaimRetainsQuality(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] world.grantItem_locked(player, 85557) player.inventory.Items[1].Quality = 101 @@ -144,7 +142,6 @@ func TestInterpolatedArmorPendingWearRechecksAndRollsBack(t *testing.T) { for _, scenario := range []string{"changed requirement", "failed save"} { t.Run(scenario, func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = 236, 261 world.grantItem_locked(player, 85557) diff --git a/server/armor_quality_test.go b/server/armor_quality_test.go @@ -65,7 +65,6 @@ func TestMetaplastIntermediateWearRemoveAndRestart(t *testing.T) { for _, piece := range metaplastQualityCases { t.Run(fmt.Sprintf("%d/QL%d/slot%d", piece.low, piece.quality, piece.slot), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = piece.strength, piece.agility if granted, err := world.grantItem_locked(player, piece.low); err != nil || !granted { @@ -136,7 +135,6 @@ func TestMetaplastIntermediateRequirementBoundaries(t *testing.T) { for _, ability := range []string{"strength", "agility"} { t.Run(fmt.Sprintf("QL%d/%s", piece.quality, ability), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = piece.strength, piece.agility if ability == "strength" { diff --git a/server/backpack_catalog_effects_test.go b/server/backpack_catalog_effects_test.go @@ -41,7 +41,6 @@ func TestBackpackCatalogEffectsAfterWearAndRemoval(t *testing.T) { } { t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy, player.stats.NanoAiding.TimeAndSpace = 1000, 1000, 1000 player.stats.Abilities.Intelligence = 420 diff --git a/server/backpack_effects_test.go b/server/backpack_effects_test.go @@ -18,7 +18,6 @@ func TestPioneerBonusesIncludeSignedScaleAndAbilityTrickle(t *testing.T) { }{{152039, 3, 2.06}, {156831, -3, 1.94}} { t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities = characterAbilitiesStats{12, 12, 12, 12, 12, 12} player.health = player.maximumHealth() @@ -69,7 +68,6 @@ func TestPioneerBonusesIncludeSignedScaleAndAbilityTrickle(t *testing.T) { func TestBackpackResourceRemovalClampsMemoryAndDatabaseBeforeReply(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 98, 848 world.grantItem_locked(player, 200461) @@ -107,7 +105,6 @@ func TestBackpackPendingWearRechecksRequirementsAndSaveFailure(t *testing.T) { for _, failure := range []string{"requirement changed", "database closed"} { t.Run(failure, func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring = 19 world.grantItem_locked(player, 99228) @@ -167,7 +164,6 @@ func TestBackpackResourceRemovalSaveFailureRetainsVitalsAndBonuses(t *testing.T) func TestBackpackSpeedChangeAnchorsHeldMovement(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring = 198 player.position, player.rotation, player.running = [3]float32{}, [4]float32{0, 0, 0, 1}, true diff --git a/server/backpack_quality_test.go b/server/backpack_quality_test.go @@ -21,7 +21,6 @@ func TestBackpackOfSurvivalInterpolatesEffectsAndNativeEndpoints(t *testing.T) { for _, template := range []uint32{206730, 206731} { t.Run(fmt.Sprintf("%d/QL%d", template, scenario.quality), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring, player.level, player.profession = 1000, 200, 6 world.saveUser_locked(player) diff --git a/server/backpack_requirements_test.go b/server/backpack_requirements_test.go @@ -41,7 +41,6 @@ func TestBackpackWearRequirementBoundaries(t *testing.T) { } { t.Run(fmt.Sprintf("%d/QL%d/stat%d/%d", scenario.template, scenario.quality, scenario.stat, scenario.value), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Body.Adventuring = 1000 player.stats.TradeRepair.ComputerLiteracy = 1000 @@ -108,7 +107,6 @@ func TestBackpackRejectsEveryUnauthoredEquipmentSlot(t *testing.T) { for _, template := range []uint32{99228, 168658} { t.Run(fmt.Sprint(template), func(t *testing.T) { world, conn := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] world.grantItem_locked(player, template) before, err := readTestItemStore(world) diff --git a/server/backyard_test.go b/server/backyard_test.go @@ -40,7 +40,6 @@ func newBackyardTestWorld(t *testing.T) *server { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - t.Cleanup(func() { world.db.Close() }) return world } diff --git a/server/bank_storage_test.go b/server/bank_storage_test.go @@ -15,8 +15,7 @@ func TestBankStoragePreservesFilledBackpack(t *testing.T) { world := newControlInventoryWorld(t) response := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) page, bag := httptest.NewRecorder(), httptest.NewRecorder() restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) restarted.httpHandler().ServeHTTP(bag, httptest.NewRequest("GET", "/control/items/3", nil)) @@ -75,8 +74,7 @@ func TestBankStorageRejectsAnotherPlayersInstance(t *testing.T) { } response := postControlForm(world, "/control/users/2", url.Values{"data": {"bank: {slot_1: 1}\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusBadRequest || len(restarted.characters[2].inventory.Bank) != 0 || len(restarted.characters[1].inventory.Bank) != 1 || restarted.characters[1].inventory.Bank[0].ID != 1 || len(restarted.items) != 4 { @@ -119,8 +117,7 @@ func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { } response := postControlForm(world, "/control/users/1", url.Values{"data": {document.String()}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || len(restarted.characters[1].inventory.Bank) != 102 || len(restarted.items) != 102 || len(restarted.characters[1].inventory.Items) != 0 || restarted.characters[1].inventory.Bank[101].Slot != 101 || restarted.characters[1].inventory.Bank[101].ID != 102 { diff --git a/server/bank_test.go b/server/bank_test.go @@ -20,7 +20,6 @@ func bankUseRequest(sequence uint32) []byte { func newBankWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, conn := newBackpackWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.playfield, player.position = 705, [3]float32{985, 20.2001, 580} if err := world.saveUser_locked(player); err != nil { diff --git a/server/bau_cyber_armor_test.go b/server/bau_cyber_armor_test.go @@ -111,7 +111,6 @@ func TestBauCyberArmorQualitiesWearRemoveAndRecover(t *testing.T) { for _, anchor := range []uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d/slot%d", anchor, scenario.quality, scenario.slot), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Intelligence, player.stats.Abilities.Psychic = scenario.intelligence+1, scenario.psychic+1 if err := world.saveUser_locked(player); err != nil { diff --git a/server/briefcase_weapon_test.go b/server/briefcase_weapon_test.go @@ -39,7 +39,6 @@ func TestBriefcaseWeaponEquipUseRemoveAndRestart(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) restarted := newTestInventoryServer(t) - t.Cleanup(func() { restarted.db.Close() }) conn.packets = nil request := backpackUseRequest(1, 6, 1)[20:] binary.BigEndian.PutUint32(request[40:44], 101) @@ -56,7 +55,6 @@ func TestBriefcaseWeaponEquipUseRemoveAndRestart(t *testing.T) { } world.advanceEquipment(client.equipment.readyAt) removed := newTestInventoryServer(t) - t.Cleanup(func() { removed.db.Close() }) if player.attackWeapon() != nil || removed.characters[1].attackWeapon() != nil || player.equipmentBonus(122) != 0 || player.equipmentBonus(146) != 0 || player.equipmentBonus(319) != 0 || removed.nextItem != 6 || !slices.ContainsFunc(removed.characters[1].inventory.Items, func(item ownedItem) bool { return item.ID == 6 && item.Slot == 69 && item.Count == 1 }) { diff --git a/server/browser_backyard_bank_test.go b/server/browser_backyard_bank_test.go @@ -82,11 +82,11 @@ func TestBrowserBackyardBank(t *testing.T) { t.Fatal(err) } host.Close() + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) for _, id := range []uint32{1, 2} { if len(world.characters[id].inventory.Items) != 0 || len(world.characters[id].inventory.Bank) != 1 || !slices.Equal(world.characters[id].inventory.Items, cold.characters[id].inventory.Items) || diff --git a/server/browser_banked_weapon_test.go b/server/browser_banked_weapon_test.go @@ -26,8 +26,7 @@ func TestBrowserBankedWeaponRecovery(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) if phase == "warm" { for index := 0; index < 2; index++ { player := world.newCharacter() diff --git a/server/browser_bau_cyber_test.go b/server/browser_bau_cyber_test.go @@ -25,8 +25,7 @@ func TestBrowserBauCyberArmorQualities(t *testing.T) { root := filepath.Dir(filepath.Dir(source)) output := filepath.Join(root, "local", "game-tests", "bau-cyber-"+time.Now().Format("20060102-150405")) t.Chdir(t.TempDir()) - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) owner := world.newCharacter() owner.name, owner.level, owner.appearance = "BauCyberowner", 100, 0x5b5 owner.playfield, owner.position = 1183, [3]float32{188, 5.11, 139.5} @@ -116,8 +115,7 @@ func TestBrowserBauCyberArmorQualities(t *testing.T) { if err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) for _, player := range []*character{owner, watcher} { restored := cold.characters[player.id] @@ -138,6 +136,7 @@ func TestBrowserBauCyberArmorQualities(t *testing.T) { // Reconstruct the completed item contract in two fresh native clients. host.Close() + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } diff --git a/server/browser_corpse_replay_test.go b/server/browser_corpse_replay_test.go @@ -58,11 +58,11 @@ func TestBrowserColdCorpsePickup(t *testing.T) { if err := world.flushWorld(); err != nil { t.Fatal(err) } + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } - world = newServer() - t.Cleanup(func() { world.db.Close() }) + world = newServerForTest(t) mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { diff --git a/server/browser_edge_less_katana_test.go b/server/browser_edge_less_katana_test.go @@ -26,8 +26,7 @@ func TestBrowserEdgeLessKatanaQualities(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) var target *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { diff --git a/server/browser_electronicum_test.go b/server/browser_electronicum_test.go @@ -26,8 +26,7 @@ func TestBrowserElectronicumQualities(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) var target *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { diff --git a/server/browser_equipment_replacement_test.go b/server/browser_equipment_replacement_test.go @@ -57,8 +57,7 @@ func TestBrowserEquipmentReplacement(t *testing.T) { if err := world.db.Close(); err != nil { t.Fatal(err) } - world = newServer() - t.Cleanup(func() { world.db.Close() }) + world = newServerForTest(t) } if !t.Run(phase, func(t *testing.T) { mux := http.NewServeMux() diff --git a/server/browser_game_test.go b/server/browser_game_test.go @@ -90,8 +90,7 @@ func TestBrowserStarterEquipment(t *testing.T) { // Use production initialization and random rolls in a disposable world. t.Chdir(t.TempDir()) - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { @@ -200,8 +199,7 @@ func TestBrowserStarterEquipment(t *testing.T) { t.Fatal(err) } - restored := newServer() - defer restored.db.Close() + restored := newServerForTest(t) world.mutex.Lock() defer world.mutex.Unlock() players := 0 diff --git a/server/browser_incoming_equipment_test.go b/server/browser_incoming_equipment_test.go @@ -26,9 +26,8 @@ func TestBrowserIncomingEquipment(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"live", "cold"} { if !t.Run(phase, func(t *testing.T) { - world := newServer() + world := newServerForTest(t) world.combatRoll = landedCombatRoll - t.Cleanup(func() { world.db.Close() }) var npc *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) { diff --git a/server/browser_item_proxy_test.go b/server/browser_item_proxy_test.go @@ -27,8 +27,7 @@ func TestBrowserAnonymousPurchasesAreUsable(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"purchase", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) if phase == "purchase" { for index := 0; index < 2; index++ { player := world.newCharacter() diff --git a/server/browser_katana_test.go b/server/browser_katana_test.go @@ -26,8 +26,7 @@ func TestBrowserKatanaQualities(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) var target *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { diff --git a/server/browser_leather_test.go b/server/browser_leather_test.go @@ -25,8 +25,7 @@ func TestBrowserLeatherArmorQualities(t *testing.T) { root := filepath.Dir(filepath.Dir(source)) output := filepath.Join(root, "local", "game-tests", "leather-"+time.Now().Format("20060102-150405")) t.Chdir(t.TempDir()) - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) owner := world.newCharacter() owner.name, owner.level, owner.appearance = "Leatherowner", 100, 0x525 owner.playfield, owner.position = 1183, [3]float32{188, 5.011, 139.5} @@ -116,8 +115,7 @@ func TestBrowserLeatherArmorQualities(t *testing.T) { if err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) for _, player := range []*character{owner, watcher} { restored := cold.characters[player.id] diff --git a/server/browser_loot_refusal_test.go b/server/browser_loot_refusal_test.go @@ -65,11 +65,11 @@ func TestBrowserCorpsePickupRefusal(t *testing.T) { if err := world.flushWorld(); err != nil { t.Fatal(err) } + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } - world = newServer() - t.Cleanup(func() { world.db.Close() }) + world = newServerForTest(t) player = world.characters[1] mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) diff --git a/server/browser_m103_test.go b/server/browser_m103_test.go @@ -26,8 +26,7 @@ func TestBrowserM103Qualities(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) var target *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { diff --git a/server/browser_m10_test.go b/server/browser_m10_test.go @@ -26,8 +26,7 @@ func TestBrowserM10Qualities(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"warm", "cold"} { t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) var target *character for _, actor := range world.characters { if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { diff --git a/server/browser_mission_backpack_test.go b/server/browser_mission_backpack_test.go @@ -33,8 +33,7 @@ func TestBrowserMissionBackpackReturn(t *testing.T) { if err := world.db.Close(); err != nil { t.Fatal(err) } - world = newServer() - t.Cleanup(func() { world.db.Close() }) + world = newServerForTest(t) mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { diff --git a/server/browser_reclaim_weapon_test.go b/server/browser_reclaim_weapon_test.go @@ -143,11 +143,11 @@ func TestBrowserReclaimWeapon(t *testing.T) { t.Fatal(err) } host.Close() + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) if !slices.Equal(player.inventory.Items, cold.characters[1].inventory.Items) || len(cold.characters[1].inventory.Reclaim) != 0 || cold.characters[1].equipmentBonus(21) != 15 || cold.characters[1].resurrectionShock != 0 { t.Fatal("cold recovery changed the reclaimed weapon, ammunition or Psychic bonus") } diff --git a/server/browser_steel_ribbed_test.go b/server/browser_steel_ribbed_test.go @@ -24,8 +24,7 @@ func TestBrowserSteelRibbedArmorQualities(t *testing.T) { root := filepath.Dir(filepath.Dir(source)) output := filepath.Join(root, "local/steel-ribbed-armor", time.Now().Format("20060102-150405")) t.Chdir(t.TempDir()) - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) owner := world.newCharacter() owner.name, owner.level, owner.appearance = "Steelowner", 100, 0x515 owner.playfield, owner.position = 1183, [3]float32{188, 5.11, 139.5} @@ -60,7 +59,7 @@ func TestBrowserSteelRibbedArmorQualities(t *testing.T) { // Each phase drains browser sessions before its database closes. t.Run("warm", func(t *testing.T) { - t.Cleanup(func() { world.db.Close() }) + registerTestDatabaseCleanup(t, world) mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { @@ -111,8 +110,7 @@ func TestBrowserSteelRibbedArmorQualities(t *testing.T) { return } t.Run("cold", func(t *testing.T) { - cold := newServer() - t.Cleanup(func() { cold.db.Close() }) + cold := newServerForTest(t) for _, player := range []*character{owner, watcher} { // Loaded inventory views share the world's last allocated item identity. expected := player.inventory diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -18,37 +18,79 @@ import ( ) func closeTestBrowserStreams(t *testing.T, world *server) { - t.Cleanup(func() { - world.mutex.Lock() - streams := make([]*browserStream, 0, len(world.browserStreams)) - for _, stream := range world.browserStreams { - streams = append(streams, stream) + t.Cleanup(func() { closeTestSessions(t, world) }) +} + +func closeTestSessions(t *testing.T, world *server) { + t.Helper() + world.mutex.Lock() + streams := make([]*browserStream, 0, len(world.browserStreams)) + for _, stream := range world.browserStreams { + streams = append(streams, stream) + } + world.mutex.Unlock() + for _, stream := range streams { + stream.close() + } + + // Retire live world writers before database cleanup, including plain sockets. + world.mutex.Lock() + clients := make(map[uint32]*worldClient) + for id, client := range world.clients { + if client.writeWake != nil { + clients[id] = client } - world.mutex.Unlock() - for _, stream := range streams { - stream.close() + } + chats := make(map[uint32]*chatClient) + for id, client := range world.chats { + if client.writeWake != nil { + chats[id] = client } + } + world.mutex.Unlock() + for _, client := range clients { + client.disconnect(client.conn) + } + for _, client := range chats { + client.disconnect(client.conn) + } - // World sessions save paused nano durations before removing their client entry. - deadline := time.Now().Add(5 * time.Second) - for { - world.mutex.Lock() - remaining := 0 - for _, client := range world.clients { - if client.stream != nil { - remaining++ - } + // World sessions save paused nano durations before removing their client entry. + deadline := time.Now().Add(5 * time.Second) + for { + world.mutex.Lock() + remaining := 0 + for id, client := range clients { + if world.clients[id] == client { + remaining++ + continue + } + select { + case <-client.writeDone: + default: + remaining++ } - world.mutex.Unlock() - if remaining == 0 { - return + } + for id, client := range chats { + if world.chats[id] == client { + remaining++ + continue } - if time.Now().After(deadline) { - t.Fatal("browser world sessions did not finish disconnecting") + select { + case <-client.writeDone: + default: + remaining++ } - time.Sleep(time.Millisecond) } - }) + world.mutex.Unlock() + if remaining == 0 { + return + } + if time.Now().After(deadline) { + t.Fatal("world sessions did not finish disconnecting") + } + time.Sleep(time.Millisecond) + } } func TestBrowserWorldResumesTheSameSessionWithoutLostOrDuplicatedBytes(t *testing.T) { diff --git a/server/browser_vektor_test.go b/server/browser_vektor_test.go @@ -122,11 +122,11 @@ func TestBrowserVektorQualities(t *testing.T) { t.Fatal(err) } host.Close() + closeTestSessions(t, world) if err := world.db.Close(); err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) if !reflect.DeepEqual(owner.inventory, cold.characters[owner.id].inventory) || owner.equipmentBonus(21) != 15 || cold.characters[owner.id].equipmentBonus(21) != 15 || owner.inventory.Items[1].Ammo != 39 || owner.inventory.Items[4].Count != 60 { diff --git a/server/browser_weapon_wear_admission_test.go b/server/browser_weapon_wear_admission_test.go @@ -26,8 +26,7 @@ func TestBrowserWeaponWearAdmission(t *testing.T) { t.Chdir(t.TempDir()) for _, phase := range []string{"live", "cold"} { if !t.Run(phase, func(t *testing.T) { - world := newServer() - t.Cleanup(func() { world.db.Close() }) + world := newServerForTest(t) if phase == "live" { for index := 0; index < 2; index++ { player := world.newCharacter() diff --git a/server/chat_history_test.go b/server/chat_history_test.go @@ -86,9 +86,9 @@ func TestChatHistoryPersistsAcrossDatabaseConnections(t *testing.T) { world := chatTestServer(t) world.sendVicinity(world.clients[1], 0, "first", nil) restarted := &server{characters: world.characters, clients: world.clients} + registerTestDatabaseCleanup(t, restarted) restarted.sendVicinity(restarted.clients[1], 0, "second", nil) - defer restarted.db.Close() history, err := restarted.chatHistory_locked(1) info, statErr := os.Stat("data/world.sqlite") @@ -186,6 +186,7 @@ func TestChatHistoryRestoresReceivedMessagesAfterMovingAndRestarting(t *testing. world.mutex.Unlock() restarted := &server{characters: world.characters, clients: world.clients, chats: make(map[uint32]*chatClient)} + registerTestDatabaseCleanup(t, restarted) alice = loginChatTest(t, restarted, 1) kind, body, err := readChatPacket(alice) message, valid := readChatString(&body) diff --git a/server/chat_test.go b/server/chat_test.go @@ -21,11 +21,7 @@ func chatTestServer(t *testing.T) *server { clients: map[uint32]*worldClient{1: {id: 1, ready: true}, 2: {id: 2, ready: true}}, chats: make(map[uint32]*chatClient), } - t.Cleanup(func() { - if world.db != nil { - world.db.Close() - } - }) + registerTestDatabaseCleanup(t, world) return world } @@ -34,8 +30,19 @@ func startChatTest(t *testing.T, server *server, boundID uint32) (net.Conn, <-ch host, peer := net.Pipe() peer.SetDeadline(time.Now().Add(3 * time.Second)) done := make(chan error, 1) - go func() { done <- server.serveChatClient(&chatClient{conn: host, id: boundID}) }() - t.Cleanup(func() { peer.Close() }) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + done <- server.serveChatClient(&chatClient{conn: host, id: boundID}) + }() + t.Cleanup(func() { + peer.Close() + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Error("chat session did not finish disconnecting") + } + }) kind, body, err := readChatPacket(peer) if err != nil || kind != 0 || len(body) != 34 || !bytes.Equal(body[:2], []byte{0, 32}) || bytes.ContainsRune(body[2:], 0) { t.Fatalf("chat seed: kind=%d body=%x error=%v", kind, body, err) diff --git a/server/combat_test.go b/server/combat_test.go @@ -43,12 +43,7 @@ func newCombatWorld(t *testing.T) (*server, *combatTestConn) { combatRoll: landedCombatRoll, } - // Close a database opened lazily by persistent actions. - t.Cleanup(func() { - if world.db != nil { - world.db.Close() - } - }) + registerTestDatabaseCleanup(t, world) return world, conn } diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -86,8 +86,7 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing contained := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) placed := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n"}}) filled := postControlForm(world, "/control/items/2", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {slot_1: 3}\n"}}) - restarted := newServer() - t.Cleanup(func() { restarted.db.Close() }) + restarted := newServerForTest(t) page := httptest.NewRecorder() restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items?q=Explorer", nil)) details := httptest.NewRecorder() @@ -128,11 +127,9 @@ func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) cleared := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) - unassigned := newServer() - t.Cleanup(func() { unassigned.db.Close() }) + unassigned := newServerForTest(t) transferred := postControlForm(world, "/control/users/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) - restarted := newServer() - t.Cleanup(func() { restarted.db.Close() }) + restarted := newServerForTest(t) postControlForm(restarted, "/control/items", url.Values{"template": {"121567"}}) if cleared.Code != http.StatusSeeOther || transferred.Code != http.StatusSeeOther || len(unassigned.items) != 1 || len(unassigned.characters[1].inventory.Items) != 0 { @@ -233,8 +230,7 @@ func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing contents := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 1\nstats:\n improvement_points: 12345\n ranged:\n rifle: 42\n spying:\n concealment: 87\n" response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) - restarted := newServer() - t.Cleanup(func() { restarted.db.Close() }) + restarted := newServerForTest(t) packet := fullCharacterPacket(restarted.characters[1]) values := make(map[uint32]uint32) count := binary.BigEndian.Uint32(packet[64:68])/1009 - 1 @@ -290,8 +286,7 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { } response := postControlForm(world, "/control/users/1", url.Values{"data": {string(contents)}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) var name string var x float32 var head, points, rifle, health, credits uint32 @@ -326,8 +321,7 @@ func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) { contents := "name: Changed\nposition: [53, 14, 60]\ninventory:\n credits: 913\n slots: {inventory_slot_7: 1}\nequipment: {clothes_head: 2}\n" response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) var name string var credits, locations uint32 if err := restarted.db.QueryRow("SELECT name, credits FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &credits); err != nil { diff --git a/server/control_inventory_test.go b/server/control_inventory_test.go @@ -40,8 +40,7 @@ func TestControlCharacterDocumentSeparatesEquipment(t *testing.T) { postControlForm(world, "/control/items", url.Values{"template": {"85557"}}) response := postControlForm(world, "/control/users/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) page := httptest.NewRecorder() restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) @@ -112,8 +111,7 @@ func TestControlEquipmentClearUnassignsWithoutLosingItems(t *testing.T) { world := newControlInventoryWorld(t) response := postControlForm(world, "/control/users/1", url.Values{"data": {"equipment: {clothes_head: null}\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) var placements int err := restarted.db.QueryRow("SELECT count(*) FROM item_locations").Scan(&placements) @@ -140,8 +138,7 @@ func TestControlEquipmentRejectsInvalidPlacementsAtomically(t *testing.T) { world := newControlInventoryWorld(t) response := postControlForm(world, "/control/users/1", url.Values{"data": {"name: Changed\n" + document}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusBadRequest || world.characters[1].name != "Explorer" || restarted.characters[1].name != "Explorer" { t.Fatalf("invalid placement changed profile: %d %s", response.Code, response.Body.String()) diff --git a/server/cyber_armor_test.go b/server/cyber_armor_test.go @@ -104,7 +104,6 @@ func TestCyberArmorQualitiesWearRemoveAndRecover(t *testing.T) { for _, anchor := range []uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d/slot%d", anchor, scenario.quality, scenario.slot), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Intelligence, player.stats.Abilities.Psychic = scenario.intelligence+1, scenario.psychic+1 if err := world.saveUser_locked(player); err != nil { diff --git a/server/database_test.go b/server/database_test.go @@ -117,8 +117,7 @@ func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { if err := world.flushWorld(); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) var integrity string if err := restarted.db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil { t.Fatal(err) @@ -172,8 +171,7 @@ func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { if err := world.flushWorld(); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if restarted.characters[1000000] != nil || len(restarted.npcRespawns) != 1 || len(restarted.items) != 0 { t.Fatal("expired corpse was restored or its respawn source was discarded") } @@ -181,8 +179,7 @@ func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { if err := restarted.flushWorld(); err != nil { t.Fatal(err) } - again := newServer() - defer again.db.Close() + again := newServerForTest(t) if len(again.characters) != 1 || again.characters[1000001] == nil || again.characters[1000001].position != [3]float32{52, 14, 56} || len(again.npcRespawns) != 0 || len(again.corpseExpiry) != 0 || len(again.mobileNPCs[950]) != 1 || again.nextItem != 17 || again.nextNPC != 1000002 { @@ -226,8 +223,7 @@ func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { world.characters[1].health, world.characters[1].nano = 30, 12 response := postControlForm(world, "/control/users/1", url.Values{"data": {"id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 2\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].level != 2 || restarted.characters[1].health != 30 || restarted.characters[1].nano != 12 { t.Fatal("profile edit saved stale health or nano") @@ -241,15 +237,13 @@ func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { if err := world.flushWorld(); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) restarted.characters[1000000].damageContributors[damageContributor{player: 1}] = 9 if err := restarted.flushWorld(); err != nil { t.Fatal(err) } - again := newServer() - defer again.db.Close() + again := newServerForTest(t) var damage uint32 err := again.db.QueryRow("SELECT damage FROM npc_damage_contributors WHERE npc_id=1000000 AND player_id=1").Scan(&damage) diff --git a/server/early_melee_test.go b/server/early_melee_test.go @@ -23,7 +23,6 @@ func TestAdvancedBaseballbatQualitiesEnforceEveryWearBoundaryAndRecover(t *testi for _, failed := range []uint32{0, 102, 146, 147, 142, 144} { t.Run(fmt.Sprintf("%d/QL%d/below%d", template, scenario.quality, failed), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = scenario.blunt, scenario.sneak, scenario.fast @@ -98,7 +97,6 @@ func TestAdvancedBaseballbatRejectsUnsupportedQualitiesWithoutLosingTheItem(t *t for _, selection := range [][2]uint32{{122691, 0}, {122691, 21}, {122692, 0}, {122692, 21}, {122693, 2}} { t.Run(fmt.Sprint(selection), func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 1000, 1000, 1000 diff --git a/server/equipment_conservation_test.go b/server/equipment_conservation_test.go @@ -12,7 +12,6 @@ func TestEquipmentPlacementFailurePreservesEveryItemThenRetries(t *testing.T) { for _, failure := range []string{"delete", "ignored delete", "insert", "ignored insert", "commit"} { t.Run(direction+"/"+failure, func(t *testing.T) { world, owner := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} @@ -94,7 +93,6 @@ func TestEquipmentPlacementFailurePreservesEveryItemThenRetries(t *testing.T) { func TestPendingEquipmentRetainsAnItemGrantedDuringItsDelay(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) client := world.clients[1] if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { t.Fatal("move admission", err) @@ -119,7 +117,6 @@ func TestEquipmentLostReplyRetainsCommittedPlacementAcrossRestart(t *testing.T) for _, direction := range []string{"wear", "remove"} { t.Run(direction, func(t *testing.T) { world, _ := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) client := world.clients[1] request := inventoryMovePacket(1, 64, 6) if direction == "remove" { diff --git a/server/fixture_database_test.go b/server/fixture_database_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "net" + "testing" + "time" +) + +func newServerForTest(t *testing.T) *server { + t.Helper() + world := newServer() + registerTestDatabaseCleanup(t, world) + return world +} + +func registerTestDatabaseCleanup(t *testing.T, world *server) { + t.Helper() + t.Cleanup(func() { + if world.db == nil { + return + } + if err := world.db.Close(); err != nil { + t.Error(err) + } + if connections := world.db.Stats().OpenConnections; connections != 0 { + t.Errorf("fixture retained %d database connections after Close", connections) + } + }) + closeTestBrowserStreams(t, world) +} + +func TestReloadFixtureClosesEveryDatabaseAtScopeExit(t *testing.T) { + t.Chdir(t.TempDir()) + var first, second *server + + if !t.Run("reload", func(t *testing.T) { + first = newServerForTest(t) + second = newServerForTest(t) + }) { + return + } + + if first.db.Stats().OpenConnections != 0 || second.db.Stats().OpenConnections != 0 { + t.Fatalf("reload fixture retained database connections: first=%d second=%d", + first.db.Stats().OpenConnections, second.db.Stats().OpenConnections) + } +} + +func TestFixtureDisconnectsWorldBeforeClosingDatabase(t *testing.T) { + seed, _ := newNanoBuffWorld(t) + castTestBuff(t, seed, 1, 1, 27169) + var world *server + stopped := make(chan struct{}) + peer, connection := net.Pipe() + defer peer.Close() + defer connection.Close() + + if !t.Run("connected", func(t *testing.T) { + world = newTestInventoryServer(t) + peer.SetDeadline(time.Now().Add(5 * time.Second)) + go func() { + defer close(stopped) + defer connection.Close() + world.serveWorldConnection(connection) + }() + if _, err := peer.Write(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})); err != nil { + t.Fatal(err) + } + readWorldUpdates(t, peer) + world.mutex.Lock() + running := !world.characters[1].activeNanos[0].expiresAt.IsZero() + world.mutex.Unlock() + if !running { + t.Fatal("login did not resume the saved nano") + } + }) { + return + } + + select { + case <-stopped: + case <-time.After(time.Second): + t.Fatal("fixture retained its world session") + } + if len(world.clients) != 0 || world.db.Stats().OpenConnections != 0 || !world.characters[1].activeNanos[0].expiresAt.IsZero() { + t.Fatal("fixture closed SQLite before retiring the session and pausing its nano") + } + paused := newTestInventoryServer(t).characters[1].activeNanos[0] + if paused.remaining != world.characters[1].activeNanos[0].remaining || !paused.expiresAt.IsZero() { + t.Fatal("fixture logout did not persist the paused nano duration") + } +} diff --git a/server/insurance_test.go b/server/insurance_test.go @@ -41,7 +41,7 @@ func TestInsuranceNativeUseSurvivesRestartAndReturnsAfterDeath(t *testing.T) { } } connection.Close() - world = newServer() + world = newServerForTest(t) player = world.characters[1] destination := player.userData() destination.Playfield = 950 @@ -59,7 +59,7 @@ func TestInsuranceNativeUseSurvivesRestartAndReturnsAfterDeath(t *testing.T) { t.Fatal(err) } } - restarted := newServer() + restarted := newServerForTest(t) world.mutex.Lock() defer world.mutex.Unlock() @@ -196,6 +196,7 @@ func TestInsuranceUnknownSavedScannerFailsLoading(t *testing.T) { } loaded := &server{characters: make(map[uint32]*character)} + registerTestDatabaseCleanup(t, loaded) err = loaded.loadUsers() if err == nil || !strings.Contains(err.Error(), "unknown resurrection terminal") { diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -166,6 +166,7 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) { func newTestInventoryServer(t *testing.T) *server { t.Helper() world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), combatRoll: landedCombatRoll} + registerTestDatabaseCleanup(t, world) var err error world.worldResources, err = readWorldResources() if err != nil { @@ -177,7 +178,6 @@ func newTestInventoryServer(t *testing.T) *server { if err := world.loadUsers(); err != nil { t.Fatal(err) } - t.Cleanup(func() { world.db.Close() }) return world } diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -41,7 +41,7 @@ func TestItemStoreLoadsUnassignedInstancesWithoutCharacters(t *testing.T) { world := newTestServer(t) response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - restarted := newServer() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || len(restarted.items) != 1 || restarted.items[1].Template != 121567 || restarted.nextItem != 1 { t.Fatalf("unassigned instance was lost: %d %s", response.Code, response.Body.String()) @@ -86,7 +86,7 @@ func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { bag := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:66"}}) postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) contained := postControlForm(world, "/control/items/4", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"3:20"}}) - restarted := newServer() + restarted := newServerForTest(t) if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "value='0:64'") || strings.Contains(page.Body.String(), "value='0:8'") || !strings.Contains(page.Body.String(), "value='0:6'") || !strings.Contains(page.Body.String(), "value='0:65'") { @@ -137,7 +137,7 @@ func TestControlConcurrentCreationAllocatesUniqueGlobalIDs(t *testing.T) { } ids[response.Header().Get("Location")] = true } - restarted := newServer() + restarted := newServerForTest(t) if len(ids) != 8 || len(restarted.items) != 8 || restarted.nextItem != 8 { t.Fatal("concurrent creation reused an instance ID or lost a committed instance") @@ -161,7 +161,7 @@ func TestControlConcurrentAssignmentCannotShareOneInstance(t *testing.T) { for range 2 { statuses[(<-responses).Code]++ } - restarted := newServer() + restarted := newServerForTest(t) if statuses[http.StatusSeeOther] != 1 || statuses[http.StatusBadRequest] != 1 || len(restarted.characters[1].inventory.Items)+len(restarted.characters[2].inventory.Items) != 1 || len(restarted.items) != 1 { diff --git a/server/leather_armor_test.go b/server/leather_armor_test.go @@ -104,7 +104,6 @@ func TestLeatherArmorQualitiesWearRemoveAndRecover(t *testing.T) { for _, anchor := range []uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d/slot%d", anchor, scenario.quality, scenario.slot), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Sense, player.stats.Abilities.Agility = scenario.sense+1, scenario.agility+1 if err := world.saveUser_locked(player); err != nil { diff --git a/server/loot_rights_test.go b/server/loot_rights_test.go @@ -19,7 +19,6 @@ func newLootRightsWorld(t *testing.T) *server { } world.clients[player.id] = &worldClient{id: player.id, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} } - t.Cleanup(func() { world.db.Close() }) // High melee AC makes ordinary fists deal exactly three damage. npc := world.characters[1000000] npc.monsterData = 17655 diff --git a/server/low_tech_armor_test.go b/server/low_tech_armor_test.go @@ -25,7 +25,6 @@ func TestLowTechGloveQualityWearAndRecovery(t *testing.T) { } { t.Run(fmt.Sprintf("%d/QL%d", anchor, scenario.quality), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = scenario.strength+1, scenario.agility+1 if err := world.saveUser_locked(player); err != nil { @@ -104,7 +103,6 @@ func TestLowTechBasicArmorPurchaseWearAndSale(t *testing.T) { for row, quality := range []uint32{1, 2} { t.Run(fmt.Sprintf("%d/QL%d", terminal.id, quality), func(t *testing.T) { world, _ := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] machine := gamedata.ShopMachines[terminal.id] player.playfield, player.position, player.appearance = machine.Playfield, machine.Position, 0x115|terminal.side<<9 @@ -181,7 +179,6 @@ func TestLowTechPurchaseFailureRetainsWalletAndRetries(t *testing.T) { } { t.Run(failure.name, func(t *testing.T) { world, _ := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.position = gamedata.ShopMachines[3221226655].Position request := shopUseRequest(2) diff --git a/server/low_tech_set_test.go b/server/low_tech_set_test.go @@ -47,7 +47,6 @@ func TestLowTechArmorQualityFamiliesWearAndRecover(t *testing.T) { for _, anchor := range []uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d", anchor, scenario.quality), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Strength, player.stats.Abilities.Agility = scenario.strength+1, scenario.agility+1 if err := world.saveUser_locked(player); err != nil { @@ -125,7 +124,6 @@ func TestLowTechCompleteShopSetKeepsBothSleevesAndExactPrice(t *testing.T) { for row, quality := range []uint32{1, 2} { t.Run(fmt.Sprintf("%d/QL%d", terminal.id, quality), func(t *testing.T) { world, _ := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] machine := gamedata.ShopMachines[terminal.id] player.playfield, player.position, player.appearance = machine.Playfield, machine.Position, 0x115|terminal.side<<9 @@ -206,7 +204,6 @@ func TestLowTechSetSecondSleeveFailureRollsBackTheWholeBasket(t *testing.T) { } { t.Run(failure.name, func(t *testing.T) { world, output := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.position = gamedata.ShopMachines[3221226655].Position player.stats.TradeRepair.ComputerLiteracy = 5 diff --git a/server/main_test.go b/server/main_test.go @@ -286,10 +286,11 @@ func TestLogoutCompletesAfterCountdown(t *testing.T) { func TestLoginChallengeAcrossSplitWrites(t *testing.T) { client, server := net.Pipe() defer client.Close() + world := newServerForTest(t) done := make(chan error, 1) go func() { defer server.Close() - done <- newServer().serveLogin(server) + done <- world.serveLogin(server) }() request, err := hex.DecodeString("0001000100010014000000000000000100000022") if err != nil { diff --git a/server/maps_test.go b/server/maps_test.go @@ -20,7 +20,7 @@ func TestMapTeleportUsesTerrainHeightAndPersists(t *testing.T) { response := httptest.NewRecorder() world.teleportPlayer(response, request) - restarted := newServer() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].position != [3]float32{52, 26.5, 56} { t.Fatalf("map teleport: status %d, position %v", response.Code, restarted.characters[1].position) diff --git a/server/mission_doors_test.go b/server/mission_doors_test.go @@ -13,7 +13,6 @@ import ( func newMissionDoorOfferWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { t.Fatal(err) } diff --git a/server/mission_encounters_test.go b/server/mission_encounters_test.go @@ -15,7 +15,6 @@ func newMissionEncounterOfferWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() encounters := gamedata.MissionTemplates[3221228472].Encounters world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) definition := gamedata.MissionTemplates[3221228472] definition.Encounters = encounters gamedata.MissionTemplates[3221228472] = definition diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go @@ -12,7 +12,6 @@ import ( func newMissionEntranceWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, output := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.geometry = world.geometry player.position, player.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0} @@ -27,6 +26,7 @@ func reloadMissionEntranceWorld(t *testing.T) *server { t.Helper() world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), geometry: missionGeometryFixture(t)} + registerTestDatabaseCleanup(t, world) world.geometry.models = make(map[uint32]collisionSphere) if _, err := world.loadNPCs(); err != nil { t.Fatal(err) @@ -34,7 +34,6 @@ func reloadMissionEntranceWorld(t *testing.T) *server { if err := world.loadUsers(); err != nil { t.Fatal(err) } - t.Cleanup(func() { world.db.Close() }) return world } diff --git a/server/mission_instance_test.go b/server/mission_instance_test.go @@ -12,7 +12,6 @@ import ( func TestMissionAssignmentPersistsDistinctWorldAndExactGenerator(t *testing.T) { world, _ := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) mission := world.characters[1].missions[0] for identity := range gamedata.Playfields { if identity >= 65536 { @@ -61,7 +60,6 @@ func TestMissionWorldAllocationRollsBackAllWritesAndRetries(t *testing.T) { } { t.Run(scenario.name, func(t *testing.T) { world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) client, player := world.clients[1], world.characters[1] if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { t.Fatal(err) @@ -100,7 +98,6 @@ func TestMissionWorldAllocationRollsBackAllWritesAndRetries(t *testing.T) { func TestMissionReloadPreservesAnAlternateSavedLayout(t *testing.T) { world, _ := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) layout := missionLayout{template: 331, width: 6, depth: 4, floorHeight: 10, ambient: [3]byte{11, 22, 33}, rooms: []missionRoom{{template: 0, x: 1, z: 1, rotation: 3}, {template: 37, x: 3, z: 1, rotation: 1}}} blob, err := layout.blob() @@ -122,7 +119,6 @@ func TestMissionReloadPreservesAnAlternateSavedLayout(t *testing.T) { func TestRetiredMissionWorldIdentityIsNeverReused(t *testing.T) { world, _ := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) first := world.characters[1].missions[0] if err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, first.id)[20:]); err != nil { @@ -144,7 +140,6 @@ func TestRetiredMissionWorldIdentityIsNeverReused(t *testing.T) { func TestMissionWorldAllocatorHandlesFinalIdentityAndRejectsExhaustion(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) if _, err := world.db.Exec("UPDATE world SET last_playfield_id=4294967294 WHERE id=1"); err != nil { t.Fatal(err) } @@ -172,7 +167,6 @@ func TestMissionWorldAllocatorHandlesFinalIdentityAndRejectsExhaustion(t *testin func TestMissionAssignmentsIsolateConcurrentOwners(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) data := world.characters[1].userData() data.ID, data.Name = 2, "Other owner" other := data.character() @@ -222,7 +216,6 @@ func TestMissionAssignmentsIsolateConcurrentOwners(t *testing.T) { func TestMissionLoadRejectsCorruptGeneratorWithoutSubstitutingDefaults(t *testing.T) { world, _ := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) if _, err := world.db.Exec("UPDATE missions SET layout=x'000300' WHERE id=2"); err != nil { t.Fatal(err) } @@ -284,7 +277,6 @@ func TestMissionLayoutBlobRejectsMalformedFramingAndPlacements(t *testing.T) { func TestMissionWorldExpiryRemovesAssignmentButKeepsCounter(t *testing.T) { world, _ := newAcceptedMissionWorld(t) - t.Cleanup(func() { world.db.Close() }) if err := world.expireMissions_locked(time.Now().Add(49*time.Hour), make(map[*worldClient][][]byte)); err != nil { t.Fatal(err) diff --git a/server/mission_levels_test.go b/server/mission_levels_test.go @@ -24,7 +24,6 @@ func TestMissionScalableRewardsFollowEveryDifficultyAndFamilyBoundary(t *testing for index, quality := range scenario.qualities { t.Run(fmt.Sprintf("level%d/difficulty%d", scenario.level, index+1), func(t *testing.T) { world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.level = scenario.level inventory := player.inventory @@ -82,7 +81,6 @@ func TestMissionScalableRewardsFollowEveryDifficultyAndFamilyBoundary(t *testing func TestMissionSelectedEncounterLevelsAndQualitySurviveRecipeAndPlayerChanges(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.level, world.nextNPC = 2, 2000000 definition := gamedata.MissionTemplates[3221228472] @@ -128,7 +126,6 @@ func TestMissionSelectedEncounterLevelsAndQualitySurviveRecipeAndPlayerChanges(t func TestMissionUnsupportedEncounterLevelDoesNotChargeOrAllocate(t *testing.T) { world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.level = 7 player.inventory.Credits = 20 @@ -163,7 +160,6 @@ func TestMissionUnsupportedEncounterLevelDoesNotChargeOrAllocate(t *testing.T) { func TestMissionExplicitQualityAndEncounterLevelRemainIndependentOfDifficulty(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) world.characters[1].level = 2 definition := gamedata.MissionTemplates[3221228472] definition.RewardItems, definition.RewardQuality = []uint32{122691}, 1 @@ -186,7 +182,6 @@ func TestMissionScalableRewardGenerationThroughReturnAndColdOwnership(t *testing for _, level := range []uint16{1, 2} { t.Run(fmt.Sprint(level), func(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.level = level definition := gamedata.MissionTemplates[3221228472] @@ -236,7 +231,6 @@ func TestMissionScalableRewardGenerationThroughReturnAndColdOwnership(t *testing func TestMissionScalableGenerationFeeFailureRetainsRecipeAndPermitsRetry(t *testing.T) { world, output := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) world.characters[1].level = 2 definition := gamedata.MissionTemplates[3221228472] definition.RewardItems = []uint32{122691} diff --git a/server/mission_movement_test.go b/server/mission_movement_test.go @@ -10,7 +10,6 @@ import ( func newMissionCollisionWorld(t *testing.T) *server { t.Helper() world := newPlayerCollisionWorld(t) - t.Cleanup(func() { world.db.Close() }) if err := world.geometry.addMission(9000001, fixedMissionLayout()); err != nil { t.Fatal(err) } diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -25,7 +25,6 @@ func newNanoCastingWorld(t *testing.T) (*server, *combatTestConn) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - t.Cleanup(func() { world.db.Close() }) return world, conn } @@ -191,7 +190,6 @@ func TestWinterBiteCancellationAndInvalidatedTargetRefundOnce(t *testing.T) { func TestWinterBiteDeathUsesSharedLootAndStopsPendingWeapons(t *testing.T) { t.Chdir(t.TempDir()) world, conn := newNanoCastingWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] npc.health, npc.monsterData = 1, 17655 npc.combatProfile = &gamedata.NPCCombatProfile{CorpseSeconds: 60, RespawnSeconds: 90} diff --git a/server/nano_reservation_test.go b/server/nano_reservation_test.go @@ -175,10 +175,10 @@ func TestNanoReservationStartupFailureRetainsRefundForRetry(t *testing.T) { t.Fatal(err) } restarted := &server{characters: make(map[uint32]*character)} + registerTestDatabaseCleanup(t, restarted) if _, err := restarted.database(); err != nil { t.Fatal(err) } - t.Cleanup(func() { restarted.db.Close() }) err := restarted.loadUsers() var nano, reserved uint32 diff --git a/server/npc_combat_test.go b/server/npc_combat_test.go @@ -79,7 +79,7 @@ func TestNPCProfileNativeSpawnUsesLeetBiteAfterRestart(t *testing.T) { if world.characters[1000000].health != map[uint16]uint32{1: 100, 2: 100, 6: 200, 10: 300}[level] { t.Fatal("profile did not initialize the NPC's health") } - world = newServer() + world = newServerForTest(t) } }) } diff --git a/server/npc_growth_test.go b/server/npc_growth_test.go @@ -18,7 +18,6 @@ func TestMissionEarlyGrowthLevelsSurviveColdAcceptance(t *testing.T) { } { t.Run(fmt.Sprint(expected.level), func(t *testing.T) { world, _ := newMissionOfferWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.level, world.nextNPC = expected.level, 2000000 player.inventory.Credits = 10 diff --git a/server/npcs_test.go b/server/npcs_test.go @@ -37,9 +37,8 @@ func TestMain(m *testing.M) { func newTestServer(t *testing.T) *server { t.Helper() t.Chdir(t.TempDir()) - world := newServer() + world := newServerForTest(t) world.combatRoll = landedCombatRoll - t.Cleanup(func() { world.db.Close() }) return world } diff --git a/server/portable_containers_test.go b/server/portable_containers_test.go @@ -58,7 +58,6 @@ var portableContainerCatalog = []struct { func newPortableContainerWorld(t *testing.T, template uint32) (*server, *combatTestConn) { t.Helper() world, conn := newStackWorld(t) - t.Cleanup(func() { world.db.Close() }) for _, id := range []uint32{template, 121567} { if granted, err := world.grantItem_locked(world.characters[1], id); err != nil || !granted { t.Fatal(granted, err) diff --git a/server/progression_test.go b/server/progression_test.go @@ -63,8 +63,7 @@ func TestExperienceEditAndCheckpointSurviveRestart(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) var experience uint32 err := restarted.db.QueryRow("SELECT experience FROM characters WHERE id=1").Scan(&experience) @@ -118,8 +117,7 @@ func TestExperienceEditorAcceptsLevelEndpoints(t *testing.T) { contents := fmt.Sprintf("level: %d\nexperience: %d\n", scenario.level, scenario.experience) response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].level != scenario.level || restarted.characters[1].experience != scenario.experience || restarted.characters[1].profile() != world.characters[1].profile() { @@ -137,8 +135,7 @@ func TestExperienceProfileUpdatePersistsImmediately(t *testing.T) { destination.Level, destination.Experience = 2, 50 err := world.updateUser(destination) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if err != nil || restarted.characters[1].level != 2 || restarted.characters[1].experience != 50 || player.savedProfile.Experience != 50 { t.Fatalf("profile update lost progression: %v", err) @@ -154,8 +151,7 @@ func TestExperienceEditFailureRollsBackThenRetries(t *testing.T) { } response := postControlForm(world, "/control/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if response.Code != http.StatusInternalServerError || world.characters[1].level != 1 || world.characters[1].experience != 0 || restarted.characters[1].level != 1 || restarted.characters[1].experience != 0 { @@ -167,8 +163,7 @@ func TestExperienceEditFailureRollsBackThenRetries(t *testing.T) { t.Fatal(err) } response = postControlForm(world, "/control/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) - retried := newServer() - defer retried.db.Close() + retried := newServerForTest(t) if response.Code != http.StatusSeeOther || retried.characters[1].level != 2 || retried.characters[1].experience != 50 { t.Fatal("the rejected progression edit could not be retried") } diff --git a/server/ranged_test.go b/server/ranged_test.go @@ -14,7 +14,6 @@ func newRangedWorld(t *testing.T) (*server, *combatTestConn) { t.Chdir(t.TempDir()) world, conn := newCombatWorld(t) world.nextNPC = 1000001 - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.name, player.level, player.appearance = "Pistol Owner", 1, 277 player.rotation[3] = 1 diff --git a/server/remote_bank_test.go b/server/remote_bank_test.go @@ -9,7 +9,6 @@ import ( func newRemoteBankWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, conn := newBackpackWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.level, player.profession = 100, 8 player.position = [3]float32{1100, 20, 700} @@ -136,7 +135,6 @@ func TestRemoteBankRepeatedUseCloseAndTransfersPreserveBriefcase(t *testing.T) { t.Fatal(err) } restarted := newTestInventoryServer(t) - t.Cleanup(func() { restarted.db.Close() }) after, _ := readTestItemStore(restarted) if client.bank == nil || len(world.characters[1].inventory.Bank) != 0 || len(conn.packets) != 8 || @@ -265,7 +263,6 @@ func TestRemoteBankNativeWireUsesClosedBackpackReference(t *testing.T) { t.Fatal(err) } world := newTestInventoryServer(t) - t.Cleanup(func() { world.db.Close() }) peer := connectZoningClient(t, world, true) for _, sequence := range []uint32{1, 2} { peer.Write(targetPacket(backpackUseRequest(1, 66, sequence))) diff --git a/server/resource_kit_quality_test.go b/server/resource_kit_quality_test.go @@ -71,7 +71,6 @@ func TestResourceKitSelectedQualityRestorationAndColdOwnership(t *testing.T) { t.Fatal(err) } cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) expected := []ownedItem{weapon, {ID: 2, Type: 51005, Template: anchor, Quality: scenario.quality, Slot: 65, Count: 2}} if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || @@ -191,7 +190,6 @@ func TestResourceKitSelectedQualityRollbackAndReplay(t *testing.T) { } } cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) if player.health != 770 || player.inventory.Items[1].Count != 2 || cold.characters[1].health != 770 || !slices.Equal(cold.characters[1].inventory.Items, player.inventory.Items) || world.nextItem != 2 || len(player.skillLocks) != 1 { @@ -242,7 +240,6 @@ func TestResourceKitSelectedQualityLastChargeRemovesItsNativeEndpoints(t *testin t.Fatal(err) } cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) var body []byte // Native inventory slot 49 represents the server's ordinary slot 65. diff --git a/server/respawn_test.go b/server/respawn_test.go @@ -95,8 +95,7 @@ func TestNPCRespawnWithoutObserversThenReentryAndRestart(t *testing.T) { world.clients[1].ready = true world.clients[1].npcs = make(map[uint32]bool) world.advanceNPCs(killed.Add(101 * time.Second)) - restarted := newServer() - t.Cleanup(func() { restarted.db.Close() }) + restarted := newServerForTest(t) spawns, corpses, profiles := 0, 0, 0 for _, packet := range conn.packets { diff --git a/server/resurrection_reconnect_test.go b/server/resurrection_reconnect_test.go @@ -12,7 +12,6 @@ import ( func pendingResurrectionWorld(t *testing.T, saved bool) *server { t.Helper() world, _ := newBuffedDeathWorld(t) - t.Cleanup(func() { world.db.Close() }) player := world.characters[1] player.level, player.experience, player.insuredExperience = 20, 1500, 140850 player.playfield, player.position = 950, [3]float32{178, 15, 57} diff --git a/server/resurrection_shock_test.go b/server/resurrection_shock_test.go @@ -38,8 +38,7 @@ func TestResurrectionShockStartsAtLevelFifteenAndPersists(t *testing.T) { if err := world.handleResurrection(world.clients[1], resurrectionRequest(1)[20:]); err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) want := uint32(0) if level == 15 { @@ -81,8 +80,7 @@ func TestResurrectionShockRecoversOnNativePhaseAndCheckpoints(t *testing.T) { if err := world.savePosition_locked(player); err != nil { t.Fatal(err) } - cold := newServer() - defer cold.db.Close() + cold := newServerForTest(t) if player.resurrectionShock != 0 || cold.characters[1].resurrectionShock != 0 { t.Fatal("shock underflowed or returned after a cold load") diff --git a/server/resurrection_test.go b/server/resurrection_test.go @@ -50,7 +50,7 @@ func TestResurrectionNativeRequestRedirectsAndPersistsBeforeReconnect(t *testing t.Fatalf("wrong native resurrection resources: %x", packet) } } - restarted := newServer() + restarted := newServerForTest(t) connection.Close() connection = connectZoningClient(t, world, true) world.mutex.Lock() diff --git a/server/shop_quality_test.go b/server/shop_quality_test.go @@ -18,7 +18,6 @@ func TestShopBasicArmorProductionQualityPurchase(t *testing.T) { } { t.Run(fmt.Sprint(scenario.machine), func(t *testing.T) { world, conn := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) client, player := world.clients[1], world.characters[1] machine := gamedata.ShopMachines[scenario.machine] player.playfield, player.position = machine.Playfield, machine.Position @@ -58,7 +57,6 @@ func TestShopBasicArmorProductionQualityPurchase(t *testing.T) { func TestShopQualityCatalogResolvesBothStoredAnchors(t *testing.T) { for _, anchor := range []uint32{85596, 85595} { world, conn := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) original := gamedata.ShopStock[99491] gamedata.ShopStock[99491] = []gamedata.ShopItem{{Template: anchor, Quality: 1}, {Template: anchor, Quality: 5}, {Template: anchor, Quality: 200}} request := shopUseRequest(2) @@ -82,7 +80,6 @@ func TestShopQualityCatalogResolvesBothStoredAnchors(t *testing.T) { func TestShopQualityRowsKeepDistinctPricesAndDelivery(t *testing.T) { world, conn := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) client, player := world.clients[1], world.characters[1] client.shop.stock = []gamedata.ShopItem{{Template: 85595, Quality: 1}, {Template: 85596, Quality: 5}, {Template: 85595, Quality: 6}} player.inventory.Credits = 2000 @@ -101,7 +98,6 @@ func TestShopQualityRowsKeepDistinctPricesAndDelivery(t *testing.T) { err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) restored := newTestInventoryServer(t) - t.Cleanup(func() { restored.db.Close() }) want := []ownedItem{ {ID: 2, Type: 51022, Template: 85595, Quality: 1, Count: 1, Slot: 65}, @@ -129,7 +125,6 @@ func TestShopQualityRowsKeepDistinctPricesAndDelivery(t *testing.T) { func TestShopQualityBasketCannotSpendEndpointPrice(t *testing.T) { world, conn := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) client, player := world.clients[1], world.characters[1] client.shop.stock = []gamedata.ShopItem{{Template: 85596, Quality: 5}} player.inventory.Credits = 685 @@ -145,7 +140,6 @@ func TestShopQualityBasketCannotSpendEndpointPrice(t *testing.T) { } } restored := newTestInventoryServer(t) - t.Cleanup(func() { restored.db.Close() }) if client.shop != nil || len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 2 || player.inventory.Credits != 685 || len(player.inventory.Items) != 1 || world.nextItem != 1 || !reflect.DeepEqual(restored.characters[1].inventory, player.inventory) { t.Fatal("basket used endpoint price or retained a rejected purchase") @@ -154,7 +148,6 @@ func TestShopQualityBasketCannotSpendEndpointPrice(t *testing.T) { func TestShopQualityPurchaseRollbackAndWearLifetime(t *testing.T) { world, conn := newPurchaseWorld(t) - t.Cleanup(func() { world.db.Close() }) client, player := world.clients[1], world.characters[1] client.shop.stock = []gamedata.ShopItem{{Template: 85596, Quality: 5}} add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:] @@ -197,7 +190,6 @@ func TestShopQualityPurchaseRollbackAndWearLifetime(t *testing.T) { } world.advanceEquipment(client.equipment.readyAt) restored := newTestInventoryServer(t) - t.Cleanup(func() { restored.db.Close() }) want := ownedItem{ID: 2, Type: 51022, Template: 85596, Quality: 5, Count: 1, Slot: 24} if restored.characters[1].inventory.Items[1] != want || restored.characters[1].inventory.Credits != 657 || world.nextItem != 2 { @@ -228,7 +220,6 @@ func TestShopQualityPurchaseRollbackAndWearLifetime(t *testing.T) { t.Fatal(err) } sold := newTestInventoryServer(t) - t.Cleanup(func() { sold.db.Close() }) if len(sold.characters[1].inventory.Items) != 1 || sold.characters[1].inventory.Credits != 677 || world.nextItem != 2 { t.Fatal("sale lost selected-quality price or retained sold ownership") diff --git a/server/starter_boss_test.go b/server/starter_boss_test.go @@ -62,7 +62,6 @@ func TestStarterBossProductionLootAcrossKillingActions(t *testing.T) { world.advanceCombat(time.Now().Add(time.Hour)) world.advanceNanos(time.Now().Add(time.Hour)) cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) want := []ownedItem{ {ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Count: 1}, @@ -128,7 +127,6 @@ func TestStarterBossSecondDropFailureRetainsLivingStateAndRetries(t *testing.T) attackForExperience(t, world, "unarmed") cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) for _, current := range []*server{world, cold} { if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || current.characters[1].experience != 0 || current.nextItem != before { @@ -146,7 +144,6 @@ func TestStarterBossSecondDropFailureRetainsLivingStateAndRetries(t *testing.T) } attackForExperience(t, world, "unarmed") again := newTestInventoryServer(t) - t.Cleanup(func() { again.db.Close() }) if len(again.characters[1000000].corpse.items) != 2 || again.nextItem != before+2 || again.characters[1].experience != 100 { t.Fatal("retry did not commit both boss drops exactly once") @@ -163,7 +160,6 @@ func TestStarterBossCodeRecheckedOnColdLoadAndReplacement(t *testing.T) { group.TemplateCode, group.MonsterData, group.Levels, group.AppearanceStatus = "BSML", 30354, [2]uint16{4, 4}, "inferred_species" useNPCData(t, data) world := newTestServer(t) - t.Cleanup(func() { world.db.Close() }) world.combatRoll = func(uint32) uint32 { return 0 } player := world.newCharacter() player.position = group.Positions[0] @@ -186,10 +182,8 @@ func TestStarterBossCodeRecheckedOnColdLoadAndReplacement(t *testing.T) { } cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) cold.advanceNPCRespawns(death.Add(100 * time.Second)) respawned := newTestInventoryServer(t) - t.Cleanup(func() { respawned.db.Close() }) for _, current := range []*server{cold, respawned} { if len(current.characters[1000000].corpse.items) != 2 || current.characters[player.id].experience != 100 || current.nextItem != 2 || @@ -222,7 +216,6 @@ func TestStarterBossLootPickupWearSaleAndRestore(t *testing.T) { } } world = newTestInventoryServer(t) - t.Cleanup(func() { world.db.Close() }) player = world.characters[1] client = &worldClient{id: 1, conn: conn, target: true, ready: true} world.clients[1] = client @@ -244,7 +237,6 @@ func TestStarterBossLootPickupWearSaleAndRestore(t *testing.T) { } world.advanceEquipment(client.equipment.readyAt) cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) want := []ownedItem{ {ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Count: 1, Slot: 24}, @@ -293,7 +285,6 @@ func TestStarterBossLootPickupWearSaleAndRestore(t *testing.T) { t.Fatal(err) } cancelled := newTestInventoryServer(t) - t.Cleanup(func() { cancelled.db.Close() }) want[1].Slot = 64 if !slices.Equal(cancelled.characters[1].inventory.Items, want) || cancelled.characters[1].inventory.Credits != 1 { @@ -315,7 +306,6 @@ func TestStarterBossLootPickupWearSaleAndRestore(t *testing.T) { } } sold := newTestInventoryServer(t) - t.Cleanup(func() { sold.db.Close() }) if !slices.Equal(sold.characters[1].inventory.Items, want[:1]) || sold.characters[1].inventory.Credits != 98 || sold.nextItem != before+2 || sold.characters[1].inventory.equipmentBonus(90) != 5 { t.Fatal("boss-loot sale lost worn gear or duplicated the selected-quality proceeds", sold.characters[1].inventory) @@ -365,7 +355,6 @@ func TestStarterBossFullInventoryPreservesBothDropsAndPartialPickup(t *testing.T t.Fatal(err) } cold := newTestInventoryServer(t) - t.Cleanup(func() { cold.db.Close() }) if len(cold.characters[1].inventory.Items) != 30 || !slices.Contains(cold.characters[1].inventory.Items, ownedItem{ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Slot: 64, Count: 1}) || !slices.Equal(cold.characters[1000000].corpse.items, []ownedItem{{ID: before + 2, Type: 51018, Template: 123742, Quality: 4, Slot: 1, Count: 1}}) || cold.nextItem != before+2 || cold.characters[1].inventory.Credits != 1 { diff --git a/server/starter_missions_test.go b/server/starter_missions_test.go @@ -26,7 +26,6 @@ var starterMissionBackyards = []struct { func newBackyardMissionWorld(t *testing.T, boothID uint32) (*server, *combatTestConn) { t.Helper() world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) world.geometry = missionGeometryFixture(t) world.geometry.models = make(map[uint32]collisionSphere) world.nextNPC = 2000000 diff --git a/server/stats_test.go b/server/stats_test.go @@ -54,7 +54,7 @@ func TestCharacterStatsPersistThroughProfileEditAndRestart(t *testing.T) { if err := world.updateUser(destination); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) if restarted.characters[1].baseStats().Abilities.Stamina != 60 || restarted.characters[1].baseStats().Body.BodyDevelopment != 200 || restarted.characters[1].maximumHealth() != 658 || restarted.characters[1].health != 34 { diff --git a/server/steel_ribbed_armor_test.go b/server/steel_ribbed_armor_test.go @@ -105,7 +105,6 @@ func TestSteelRibbedArmorQualitiesWearRemoveAndRecover(t *testing.T) { for _, anchor := range []uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d/slot%d", anchor, scenario.quality, scenario.slot), func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities.Sense, player.stats.Abilities.Agility = scenario.sense+1, scenario.agility+1 if err := world.saveUser_locked(player); err != nil { diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -210,7 +210,7 @@ func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) if restarted.characters[2].position != [3]float32{53, 14, 61} || restarted.characters[2].rotation != [4]float32{0, 0, 0, 1} { t.Fatalf("target movement corrupted saved coordinates: %+v", restarted.characters[2]) diff --git a/server/users_test.go b/server/users_test.go @@ -34,8 +34,7 @@ func TestUserRowsAreSeparateAndOnlyUpdatedProfileChanges(t *testing.T) { if err := world.updateUser(edited); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) after, err := readTestPlayerRecord(2, "player") var count, id int if err := world.db.QueryRow("SELECT count(*), player FROM profile_updates").Scan(&count, &id); err != nil { @@ -77,7 +76,7 @@ running: true if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) page := httptest.NewRecorder() restarted.controlPage(page, httptest.NewRequest("GET", "/control", nil)) @@ -129,7 +128,7 @@ func TestMovementModePersistsAndIsSuppliedOnReconnect(t *testing.T) { t.Fatal(err) } client.Close() - restarted := newServer() + restarted := newServerForTest(t) reconnected, connection := net.Pipe() defer reconnected.Close() reconnected.SetDeadline(time.Now().Add(5 * time.Second)) @@ -200,7 +199,7 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) } - restarted := newServer() + restarted := newServerForTest(t) client, connection := net.Pipe() defer client.Close() client.SetDeadline(time.Now().Add(5 * time.Second)) @@ -243,7 +242,7 @@ func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) client, connection := net.Pipe() defer client.Close() client.SetDeadline(time.Now().Add(5 * time.Second)) @@ -281,7 +280,7 @@ func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) { world.clients[1] = &worldClient{id: 1, ready: true} world.sendVicinity(world.clients[1], 0, "saved under player ID", nil) - restarted := newServer() + restarted := newServerForTest(t) restarted.clients[1] = &worldClient{id: 1, ready: true} peer := loginChatTest(t, restarted, 1) kind, body, err := readChatPacket(peer) @@ -346,7 +345,7 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) { if err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) after, err := readTestPlayerRecord(1, "player") if err != nil { t.Fatal(err) @@ -407,8 +406,7 @@ func TestFailedPositionTransactionPreservesProfileAndRetries(t *testing.T) { if err := world.flushPositions(time.Now().Add(40 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() - defer restarted.db.Close() + restarted := newServerForTest(t) if saveErr == nil || err != nil || !bytes.Equal(profile, savedProfile) || restarted.characters[1].position != destination.Position { t.Fatalf("position rollback or retry failed: %v %v", saveErr, err) @@ -502,8 +500,7 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) { func TestOfflinePositionSaveWithSparsePlayerIDs(t *testing.T) { useNPCData(t, testNPCData()) t.Chdir(t.TempDir()) - world := newServer() - defer world.db.Close() + world := newServerForTest(t) player := (userData{ID: 7, Name: "Explorer", Appearance: 789, Level: 1, Playfield: 950, Position: [3]float32{53, 14, 60}, Rotation: [4]float32{0, 0, 0, 1}}).character() world.characters[7], world.nextCharacter = player, 7 @@ -518,7 +515,7 @@ func TestOfflinePositionSaveWithSparsePlayerIDs(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) if response.Code != http.StatusSeeOther { t.Fatalf("offline teleport: HTTP %d, %s", response.Code, response.Body.String()) diff --git a/server/weapon_quality_lifecycle_test.go b/server/weapon_quality_lifecycle_test.go @@ -129,7 +129,6 @@ func TestWeaponQualityPendingWearRechecksSkillsAndRollsBack(t *testing.T) { for _, scenario := range []string{"Pistol fell", "Fling fell", "failed placement", "ignored placement"} { t.Run(scenario, func(t *testing.T) { world, output := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 24, 15 diff --git a/server/weapon_quality_test.go b/server/weapon_quality_test.go @@ -48,7 +48,6 @@ func TestWeaponQualityEquipRequiresInterpolatedSkillsAndRecovers(t *testing.T) { for _, template := range [2]uint32{scenario.low, scenario.high} { t.Run(fmt.Sprintf("%d/QL%d", template, scenario.quality), func(t *testing.T) { world, owner := newEquipmentWorld(t) - t.Cleanup(func() { world.db.Close() }) player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} diff --git a/server/zoning_test.go b/server/zoning_test.go @@ -77,7 +77,7 @@ func TestShopDoorReturnsToItsOriginalEntrance(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) arrived := restarted.characters[1].userData() offset := 20 @@ -107,7 +107,7 @@ func TestShopDoorReturnsToItsOriginalEntrance(t *testing.T) { if err := world.flushPositions(time.Now().Add(40 * time.Second)); err != nil { t.Fatal(err) } - restarted = newServer() + restarted = newServerForTest(t) returned := restarted.characters[1].userData() if returned.Playfield != 705 || returned.ReturnDoor != nil || math.Abs(float64(returned.Position[2]-514.007)) > 0.001 { @@ -309,7 +309,7 @@ func TestMovementBeforeCharacterReadyPreservesZoneArrival(t *testing.T) { if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } - restarted := newServer() + restarted := newServerForTest(t) if restarted.characters[1].position != [3]float32{727, 9.8, 2304} { t.Fatal("movement after CharacterReady was not persisted")