aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 57d25ec1ef90537b629481b70b40bfd3a0f88d8f
parent 83e4048c1be06f446b12faa929425b34ff3f06a7
Author: anon <anon@example.com>
Date:   Fri,  6 Nov 2026 06:25:32 +0000

Move focused browser scenarios to an isolated test-only server API

Diffstat:
MDEVELOPERS.md | 29++++++++++++++++++++++++++---
MTODO.md | 12+++++++++++-
Mdocs/alpha-item-recovery.md | 2+-
Mdocs/inventory-stacks.md | 2+-
Mdocs/starter-progression.md | 2+-
Mserver/browser_game_test.go | 65-----------------------------------------------------------------
Dserver/browser_stack_overflow_test.go | 60------------------------------------------------------------
Mserver/browser_starter_cold_test.go | 55-------------------------------------------------------
Aserver/e2e_absent_test.go | 24++++++++++++++++++++++++
Aserver/e2e_api.go | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/entrypoint.go | 7+++++++
Aserver/entrypoint_e2e.go | 36++++++++++++++++++++++++++++++++++++
Mserver/main.go | 21++++-----------------
Aserver/simulation.go | 26++++++++++++++++++++++++++
Atests/e2e/browser.test.mjs | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atests/e2e/fixture.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atests/e2e/starter-cold.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Dtools/client/test_game.mjs | 64----------------------------------------------------------------
Dtools/client/test_stack_overflow.mjs | 52----------------------------------------------------
Mtools/client/test_starter_cold.mjs | 50+++-----------------------------------------------
20 files changed, 612 insertions(+), 367 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -558,13 +558,13 @@ available (`node` on PATH, `playwright` installed locally or on NODE_PATH, `/usr/bin/chromium` installed): ```sh -AO_GAME_TEST=1 go test ./server -run '^TestBrowser(GameHarness|StarterEquipment|StarterMissionTargets)$' -count=1 -timeout=95m -v +node --test tests/e2e/browser.test.mjs ``` For a short native cold-recovery check without replaying progression, run: ```sh -AO_GAME_TEST=1 go test ./server -run '^TestBrowserStarterColdRecovery$' -count=1 -timeout=4m -v +node --test --test-name-pattern='two starter accounts' tests/e2e/browser.test.mjs ``` This uses current-schema accounts and controlled level, wallet, equipment and @@ -579,9 +579,32 @@ posture, native world picking, UI input, resizing and reload reconstruction. The setup creates the scenario before connecting; all actions under test use normal browser input and the actual game/server protocol. The test closes its browser, streams and HTTP server even after failures. Reports and screenshots -remain in `local/game-tests/<run>/`. On the Linux desktop, use the same working +remain in `local/e2e/<run>/`. On the Linux desktop, use the same working DISPLAY/XAUTHORITY environment as the other GPU browser checks. +New browser scenarios belong in `tests/e2e/` and use `fixture.mjs`. Its shared +build step compiles `go build -tags=e2e`; each scenario owns a loopback server, +temporary database, asset-directory symlink and Playwright browser. Restart +closes browser contexts, checkpoints and exits the process, then starts a fresh +process against that same database. Cleanup runs in `finally`, including after +an assertion fails. The fixture verifies graceful server exit and removes only +its own temporary directory. + +The test-only `/_test/player` snapshot exposes identity, placement, posture, +progress, resources and explicit carried-item records. Setup operations prepare +position, progress, grants, item placement/charges and a stationary picking +target before the game connects. They use the server's locks and persistence +methods; they do not accept SQL, arbitrary field names or internal struct dumps. +The test executable runs the same simulation loops and shutdown checkpoint as +the normal server. `e2e_api.go` and its entry point are excluded from default +builds; `TestProductionOmitsBrowserSetupAPI` checks production route absence. + +The movement/targeting, overflow-refusal and starter cold-recovery scenarios +have moved from Go runners. Other browser runners migrate incrementally by +subsystem. The longer `TestBrowserStarterEquipment` runner retains its earned +checkpoint and invokes the shared cold-client assertions through its existing +adapter. Ordinary Go rule, transaction and HTTP-handler tests remain in Go. + The Chromium harness saves runtime exception details with each error, preserving stack frames even for primitive throws such as `unwind`. Verify that diagnostic path without loading the game with `node --test tools/client/test_game_errors.mjs`. diff --git a/TODO.md b/TODO.md @@ -399,7 +399,7 @@ rewriting this document does not close them. grids remain separate from original scenery. Corpse expiry and respawn tests now reach and pass their assertions; related roaming, checkpoint, teleport and fixture-isolation regressions pass as well. -- [ ] **Separate browser scenarios from Go internals through a test-only API.** +- [x] **Separate browser scenarios from Go internals through a test-only API.** Put browser scenarios and end-to-end assertions in JavaScript under `tests/e2e/`, reusing `tools/client/game_test.mjs`. A shared Playwright fixture owns server startup/shutdown, isolated temporary databases and cleanup, @@ -422,6 +422,16 @@ rewriting this document does not close them. Go browser runners and use this structure for new browser scenarios. Migrate remaining runners incrementally by subsystem; a full server package split or wholesale test migration is not an alpha prerequisite. + November 5: `tests/e2e/browser.test.mjs` now owns movement/targeting, overflow + refusal and two-account starter cold recovery. Their shared fixture builds + the `e2e` executable, owns isolated loopback servers/databases and Chromium, + and uses production simulation and shutdown checkpoints. All three scenarios + pass (33.48s, 36.58s and 54.28s). An intentional failure with a connected game + also verifies browser/process/port/database cleanup (21.24s). Default-build + route absence and build-file exclusion checks pass, as do both build modes' + vet checks. The three superseded Go runners are removed; the remaining earned + progression runner shares the cold-client assertions. See + [browser testing](DEVELOPERS.md#browser-game-testing). - [ ] Document/enforce server ownership boundaries as affected code changes: protocol/session handling, world simulation, game rules/content, and durable transactions. Keep low-significance simulation state in memory between diff --git a/docs/alpha-item-recovery.md b/docs/alpha-item-recovery.md @@ -12,7 +12,7 @@ paths. Shop breadth, human encounters and affordability remain A5/A7 work. | Action | Exact state and transaction coverage | Native evidence and limits | | --- | --- | --- | | Buy recovery, ammunition and equipment; sell loot | `shop_purchases_test.go` covers charged packages, exact slots/identities, concurrent accept, failed commit and retry. `shop_multi_sale_test.go` covers partial charges, zero-value rows and failed writes without partial cash/ownership. `shop_live_items_test.go` covers reply loss. | [NPC vendors](npc-shops.md) and [early stock](early-shop-stock.md) record the five vendors, four training terminals, three weapon shops and 36 nano terminals. Purchase/use, sale, cancel and reconnect are covered; the stock fixtures also check cold recovery. Controlled money/skills establish transactions, not affordability or earned progression. | -| Wear, remove and replace equipment | `equipment_test.go`, `equipment_replacement_test.go` and `equipment_conservation_test.go` cover delayed placement, requirements, full inventory, failed placement/retry, concurrent grants and lost replies with cold recovery. | [Inventory](inventory.md) records native equip/unequip/replacement and full-inventory refusal. `TestBrowserStarterColdRecovery` starts a new server and two native clients with a worn starter weapon, 17 lab charges and 50 credits. That checkpoint is seeded. `TestBrowserBackpackEquipment` covers bag-to-wear and exact ownership after cold load. | +| Wear, remove and replace equipment | `equipment_test.go`, `equipment_replacement_test.go` and `equipment_conservation_test.go` cover delayed placement, requirements, full inventory, failed placement/retry, concurrent grants and lost replies with cold recovery. | [Inventory](inventory.md) records native equip/unequip/replacement and full-inventory refusal. The `tests/e2e/browser.test.mjs` starter cold scenario starts a new server and two native clients with a worn starter weapon, 17 lab charges and 50 credits. That checkpoint is seeded. `TestBrowserBackpackEquipment` covers bag-to-wear and exact ownership after cold load. | | Put items in a backpack, withdraw them, split/join charges and use recovery | `backpacks_test.go` covers native wire/restart, transfers between bags, capacity, concurrent transfer and failed save, split/join and reclaim. `backpack_medical_test.go` covers exact source/patient, last-charge consumption and failed commit/retry. | [Backpacks](backpacks.md) records native storage, restart, withdrawal/equip, charged stacks and full bags. `TestBrowserBackpackMedical` checks native use and source charges; retained verification reports 24 focused roots and 34 race roots. | | Trade items and money with another player | `player_trading_test.go` covers both owners and cash in one transaction and failed persistence. `player_trading_lifecycle_test.go` covers cancellation, concurrent accept, lost completion replies and death. `player_trading_rejection_test.go` covers loaded weapons, filled bags and prospective capacity. | [Player trading](player-trading.md) records two-client charged-stack/cash exchange, filled bags, cancellation and restart. `TestBrowserTradedWeapon` transfers a loaded gun, equips/fires it, then restores it in a new server/native session. The high-skill checkpoint is controlled, not an early-game balance claim. | | Die, retain protected equipment, reclaim other items | `player_death_test.go` covers death/reclaim atomicity and failed writes. `reclaim_test.go` covers retained worn/NoDrop items, private pickup, full inventory, failed pickup/retry, concurrency and native wire/restart. | [Reclaim](reclaim.md) records Omni and Clan/Neutral insurance routes. `TestBrowserBulkReclaimColdRecovery` restores a controlled level-10 death, collects 24 reclaim items, then starts another server/native session; all 33 items across both owners retain identity, quality, charges, ammunition and placement, with 1,319 credits unchanged. | diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -83,7 +83,7 @@ establish the historical server's stack limit. `TestStackOverflowRefusalRestoresRemovedSource` checks both directions, exact source feedback, zero checkpoint writes and cold ownership. The existing ceiling regression still accepts 40000 plus 25535 and refuses 40000 plus 25536. -`TestBrowserStackJoinOverflowRefusal` sends two real joins from the same source, +The `overflow refusal` scenario in `tests/e2e/browser.test.mjs` sends two real joins from the same source, verifies both usable icons and all 65536 charges, then checks page replay and cold identities. These fixture quantities are controlled; no acquisition or earned-progression claim is made. Baseline failures and native captures are diff --git a/docs/starter-progression.md b/docs/starter-progression.md @@ -1749,7 +1749,7 @@ physical IDs, types, slots, qualities, quantities and endpoints must match the restored server, alongside cumulative XP, level, IP, wallet and health maxima. The named profiles' owned items and private progress must remain unchanged. -`TestBrowserStarterColdRecovery` exercises that same stage in a short current- +The `two starter accounts` scenario in `tests/e2e/browser.test.mjs` exercises that same stage in a short current- schema fixture. It creates accounts through the account API, then controls the owner's level/IP/wallet, worn bat and partial laboratory count before closing and restoring the server. These are controlled verification conditions, not diff --git a/server/browser_game_test.go b/server/browser_game_test.go @@ -2,9 +2,7 @@ package main import ( "context" - "crypto/sha256" "encoding/json" - "fmt" "net/http" "net/http/httptest" "os" @@ -16,69 +14,6 @@ import ( "time" ) -func TestBrowserGameHarness(t *testing.T) { - if os.Getenv("AO_GAME_TEST") != "1" { - t.Skip("set AO_GAME_TEST=1 to run the real WASM client in Chromium") - } - _, source, _, _ := runtime.Caller(0) - root := filepath.Dir(filepath.Dir(source)) - output := filepath.Join(root, "local", "game-tests", time.Now().Format("20060102-150405")) - world := newTestServer(t) - world.characters = make(map[uint32]*character) - world.mobileNPCs = nil - player := world.newCharacter() - player.playfield = 705 - player.position = [3]float32{960, 16.5, 510} - player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("game-harness"))) - if err := world.saveUser_locked(player); err != nil { - t.Fatal(err) - } - if granted, err := world.grantItem_locked(player, 121567); !granted || err != nil { - t.Fatal(granted, err) - } - world.characters[1000000] = &character{id: 1000000, name: "Harness Leet", npc: true, - playfield: 705, position: [3]float32{960, 16.5, 498}, rotation: [4]float32{0, 0, 0, 1}, - appearance: 229, monsterData: 17655, level: 1, health: 100} - mux := http.NewServeMux() - mux.Handle("/", world.httpHandler()) - mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { - world.mutex.Lock() - defer world.mutex.Unlock() - json.NewEncoder(w).Encode(map[string]any{"health": player.health, "sitting": player.sitting, - "items": player.inventory.Items, "position": player.position}) - }) - host := httptest.NewServer(mux) - defer host.Close() - defer func() { - world.mutex.Lock() - var streams []*browserStream - for _, stream := range world.browserStreams { - streams = append(streams, stream) - } - world.mutex.Unlock() - for _, stream := range streams { - stream.close() - } - }() - - ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) - defer cancel() - command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_game.mjs"), host.URL, output) - command.Dir = root - command.Stdout, command.Stderr = os.Stdout, os.Stderr - err := command.Run() - t.Logf("Browser artifacts: %s", output) - - if err != nil { - t.Fatal(err) - } - world.mutex.Lock() - defer world.mutex.Unlock() - if player.sitting || player.position[2] < 510.5 || len(player.inventory.Items) != 1 { - t.Fatalf("browser controls did not produce their authoritative outcomes: sitting=%t position=%v inventory=%+v", player.sitting, player.position, player.inventory) - } -} - func TestBrowserStarterEquipment(t *testing.T) { if os.Getenv("AO_GAME_TEST") != "1" { t.Skip("set AO_GAME_TEST=1 to run the real WASM client in Chromium") diff --git a/server/browser_stack_overflow_test.go b/server/browser_stack_overflow_test.go @@ -1,60 +0,0 @@ -package main - -import ( - "context" - "crypto/sha256" - "fmt" - "net/http/httptest" - "os" - "os/exec" - "path/filepath" - "runtime" - "slices" - "testing" - "time" -) - -func TestBrowserStackJoinOverflowRefusal(t *testing.T) { - if os.Getenv("AO_GAME_TEST") != "1" { - t.Skip("set AO_GAME_TEST=1 for stack overflow refusal") - } - - _, source, _, _ := runtime.Caller(0) - root := filepath.Dir(filepath.Dir(source)) - output := filepath.Join(root, "local/stack-overflow", time.Now().Format("20060102-150405")) - world := newTestServer(t) - player := world.newCharacter() - player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stack-overflow"))) - if err := world.saveUser_locked(player); err != nil { - t.Fatal(err) - } - for range 2 { - if granted, err := world.grantItem_locked(player, 152030); err != nil || !granted { - t.Fatal(granted, err) - } - } - player.inventory.Items[0].Count, player.inventory.Items[1].Count = 1, 65535 - if err := world.saveInventory_locked(player, player.inventory); err != nil { - t.Fatal(err) - } - expected := slices.Clone(player.inventory.Items) - host := httptest.NewServer(world.httpHandler()) - t.Cleanup(host.Close) - closeTestBrowserStreams(t, world) - ctx, cancel := context.WithTimeout(context.Background(), time.Minute) - defer cancel() - - command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_stack_overflow.mjs"), host.URL, output) - command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr - err := command.Run() - t.Logf("Browser artifacts: %s", output) - - if err != nil { - t.Fatal(err) - } - cold := newTestInventoryServer(t) - if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || - world.nextItem != 2 || cold.nextItem != 2 { - t.Fatal("overflow refusal changed quantities, identities or placements") - } -} diff --git a/server/browser_starter_cold_test.go b/server/browser_starter_cold_test.go @@ -9,66 +9,11 @@ import ( "os/exec" "path/filepath" "reflect" - "runtime" "slices" "testing" "time" ) -func TestBrowserStarterColdRecovery(t *testing.T) { - if os.Getenv("AO_GAME_TEST") != "1" { - t.Skip("set AO_GAME_TEST=1 for the focused starter cold check") - } - _, source, _, _ := runtime.Caller(0) - root := filepath.Dir(filepath.Dir(source)) - output := filepath.Join(root, "local/starter-native-cold", time.Now().Format("20060102-150405")) - world := newTestServer(t) - cookie := accountVisitor(t, world) - for _, name := range []string{"Starterowner", "Starterwatch"} { - fields := creationForm() - fields.Set("name", name) - fields.Set("password", "starter regression password") - fields.Set("profession", "9") - response := creationRequest(world, cookie, fields) - if response.Code != 204 { - t.Fatal(response.Code, response.Body.String()) - } - cookie = response.Result().Cookies()[0] - player := world.characters[world.nextCharacter] - if name == "Starterowner" { - // Seed the cold recovery condition; this fixture does not earn progress. - player.level, player.experience, player.stats.ImprovementPoints = 2, 150, 5006 - player.health = player.maximumHealth() - inventory := player.inventory - inventory.Items = slices.Clone(inventory.Items) - inventory.Credits = 50 - for index := range inventory.Items { - if inventory.Items[index].Template == 121564 { - inventory.Items[index].Slot = 6 - } - if inventory.Items[index].Template == 116628 { - inventory.Items[index].Count = 17 - } - } - if err := world.saveUser_locked(player); err != nil { - t.Fatal(err) - } - if err := world.saveInventory_locked(player, inventory); err != nil { - t.Fatal(err) - } - } - } - host := httptest.NewServer(world.httpHandler()) - host.Close() - closeTestSessions(t, world) - if err := world.db.Close(); err != nil { - t.Fatal(err) - } - restored := newServerForTest(t) - - testBrowserStarterCold(t, restored, root, output) -} - func testBrowserStarterCold(t *testing.T, world *server, root, output string) { t.Helper() items := make(map[string][]ownedItem) diff --git a/server/e2e_absent_test.go b/server/e2e_absent_test.go @@ -0,0 +1,24 @@ +//go:build !e2e + +package main + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestProductionOmitsBrowserSetupAPI(t *testing.T) { + world := newTestServer(t) + for _, request := range []*http.Request{ + httptest.NewRequest("GET", "/_test/player", nil), + httptest.NewRequest("POST", "/_test/player/progress", nil), + httptest.NewRequest("POST", "/_test/player/grant-item", nil), + } { + response := httptest.NewRecorder() + world.httpHandler().ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatal("production exposed a browser test route", request.URL.Path, response.Code) + } + } +} diff --git a/server/e2e_api.go b/server/e2e_api.go @@ -0,0 +1,142 @@ +//go:build e2e + +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" +) + +func (server *server) e2eHandler() http.Handler { + mux := http.NewServeMux() + mux.Handle("/", server.httpHandler()) + mux.HandleFunc("GET /_test/player", server.e2ePlayer) + mux.HandleFunc("POST /_test/player/{operation}", server.e2ePlayer) + return mux +} + +func (server *server) e2ePlayer(w http.ResponseWriter, r *http.Request) { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + player := server.browserCharacter_locked(r) + if player == nil { + http.Error(w, "a browser player is required", http.StatusUnauthorized) + return + } + if r.Method == "POST" && server.clients[player.id] != nil { + http.Error(w, "prepare conditions before connecting the game", http.StatusConflict) + return + } + if r.PathValue("operation") == "leet" { + var request struct{ Position [3]float32 } + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&request); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + // A stationary world-picking target uses the original Leet body. + id := server.nextNPC + server.nextNPC++ + server.characters[id] = &character{id: id, name: "Harness Leet", npc: true, + playfield: player.playfield, position: request.Position, rotation: [4]float32{0, 0, 0, 1}, + appearance: 229, monsterData: 17655, level: 1, health: 100} + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]uint32{"id": id}) + return + } + if r.Method == "POST" { + if err := server.e2eSetup_locked(player, r); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + } + + // Publish a deliberate contract, excluding credentials and internal containers. + items := make([]map[string]any, 0, len(player.inventory.Items)) + for _, item := range player.inventory.Items { + low, high := item.templateIDs() + items = append(items, map[string]any{"id": item.ID, "type": item.Type, + "slot": item.Slot, "quality": item.Quality, "count": item.Count, + "ammo": item.Ammo, "templates": [2]uint32{low, high}}) + } + lower, _ := player.experienceBounds() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"id": player.id, "name": player.name, + "playfield": player.playfield, "position": player.position, "sitting": player.sitting, + "level": player.level, "experience": lower + player.experience, + "ip": player.stats.ImprovementPoints, "credits": player.inventory.Credits, + "health": player.health, "maximumHealth": player.maximumHealth(), + "items": items, "lastItem": server.nextItem}) +} + +func (server *server) e2eSetup_locked(player *character, r *http.Request) error { + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + switch r.PathValue("operation") { + case "position": + var request struct { + Playfield uint32 + Position [3]float32 + Rotation [4]float32 + } + if err := decoder.Decode(&request); err != nil { + return err + } + player.playfield, player.position, player.rotation = request.Playfield, request.Position, request.Rotation + return server.savePosition_locked(player) + case "progress": + var request struct { + Level uint16 + Experience uint32 + IP uint32 + Credits uint32 + } + if err := decoder.Decode(&request); err != nil { + return err + } + player.level, player.experience, player.stats.ImprovementPoints = request.Level, request.Experience, request.IP + player.health = player.maximumHealth() + if err := server.saveUser_locked(player); err != nil { + return err + } + inventory := player.inventory + inventory.Credits = request.Credits + return server.saveInventory_locked(player, inventory) + case "grant-item": + var request struct{ Template uint32 } + if err := decoder.Decode(&request); err != nil { + return err + } + granted, err := server.grantItem_locked(player, request.Template) + if err != nil { + return err + } + if !granted { + return fmt.Errorf("inventory is full") + } + return nil + case "item": + var request struct { + ID, Slot uint32 + Count uint16 + } + if err := decoder.Decode(&request); err != nil { + return err + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + index := slices.IndexFunc(inventory.Items, func(item ownedItem) bool { return item.ID == request.ID }) + if index < 0 { + return fmt.Errorf("unknown carried item %d", request.ID) + } + inventory.Items[index].Slot, inventory.Items[index].Count = request.Slot, request.Count + return server.saveInventory_locked(player, inventory) + default: + return fmt.Errorf("unknown setup operation") + } +} diff --git a/server/entrypoint.go b/server/entrypoint.go @@ -0,0 +1,7 @@ +//go:build !e2e + +package main + +func main() { + runServer() +} diff --git a/server/entrypoint_e2e.go b/server/entrypoint_e2e.go @@ -0,0 +1,36 @@ +//go:build e2e + +package main + +import ( + "encoding/json" + "log" + "net" + "net/http" + "os" + "os/signal" + "syscall" +) + +func main() { + world := newServer() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + log.Fatal(err) + } + world.startSimulation() + go func() { + if err := http.Serve(listener, world.e2eHandler()); err != nil { + log.Fatal(err) + } + }() + stopping := make(chan os.Signal, 1) + signal.Notify(stopping, os.Interrupt, syscall.SIGTERM) + if err := json.NewEncoder(os.Stdout).Encode(map[string]string{"url": "http://" + listener.Addr().String()}); err != nil { + log.Fatal(err) + } + <-stopping + if err := world.shutdown(); err != nil { + log.Fatal(err) + } +} diff --git a/server/main.go b/server/main.go @@ -22,7 +22,7 @@ import ( // Detailed traces are disabled unless explicitly enabled at startup. var traceLog = log.New(io.Discard, "", log.LstdFlags) -func main() { +func runServer() { loginPort := flag.Int("login-port", 7500, "login port") worldPort := flag.Int("world-port", 7501, "world port") httpPort := flag.Int("http-port", 8080, "HTTP and admin port") @@ -71,10 +71,7 @@ func main() { }() go server.serveWorld() go server.serveChat() - go server.roamNPCs() - go server.movePlayers() - go server.saveWorld() - go server.checkZoneCrossings() + server.startSimulation() // Commit the current simulation before a development-server restart. stopping := make(chan os.Signal, 1) @@ -82,18 +79,8 @@ func main() { go func() { <-stopping log.Print("Server shutting down") - server.updateMutex.Lock() - if err := server.flushPositions(time.Now().Add(20 * time.Second)); err != nil { - log.Printf("Saving positions on shutdown: %v", err) - } - if err := server.flushWorld(); err != nil { - log.Printf("Saving world on shutdown: %v", err) - os.Exit(1) - } - // Keep checkpoint writers blocked until the process exits with its database closed. - server.mutex.Lock() - if err := server.db.Close(); err != nil { - log.Printf("Closing world database: %v", err) + if err := server.shutdown(); err != nil { + log.Printf("Server shutdown: %v", err) os.Exit(1) } os.Exit(0) diff --git a/server/simulation.go b/server/simulation.go @@ -0,0 +1,26 @@ +package main + +import ( + "log" + "time" +) + +func (server *server) startSimulation() { + go server.roamNPCs() + go server.movePlayers() + go server.saveWorld() + go server.checkZoneCrossings() +} + +// Call only before process exit: writers stay blocked after the final checkpoint. +func (server *server) shutdown() error { + server.updateMutex.Lock() + if err := server.flushPositions(time.Now().Add(20 * time.Second)); err != nil { + log.Printf("Saving positions on shutdown: %v", err) + } + if err := server.flushWorld(); err != nil { + return err + } + server.mutex.Lock() + return server.db.Close() +} diff --git a/tests/e2e/browser.test.mjs b/tests/e2e/browser.test.mjs @@ -0,0 +1,150 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {before, test} from 'node:test'; +import {buildServer, withFixture} from './fixture.mjs'; +import {checkStarterCold} from './starter-cold.mjs'; + +before(buildServer); + +// These scenarios use the normal client protocol after preparing their fixtures. +test('movement, targeting, posture and page recovery', {timeout: 180_000}, async () => { + await withFixture('interaction', async fixture => { + const context = await fixture.visitor(); + await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]}); + await fixture.setup(context, 'grant-item', {template: 121567}); + const target = await fixture.setup(context, 'leet', {position: [960, 16.5, 498]}); + const game = await fixture.game(context); + const page = game.page; + assert.equal(game.state.localId, 1); + assert.equal(game.local().inventory[0].templates[0], 121567); + const inventory = game.local().inventory; + + const z = game.local().position[2]; + await game.hold('KeyS', 'backward movement', state => game.local(state).position[2] < z - 0.5); + await game.hold('KeyW', 'forward movement', state => game.local(state).position[2] > z + 0.5); + await game.key('F1'); + await game.wait('self selection', state => state.selected[0] === 50000 && state.selected[1] === 1); + await game.key('x'); + await game.wait('sitting posture', state => game.local(state).stats[430] === 2); + assert.equal((await fixture.state(context)).sitting, true); + await game.key('x'); + await game.wait('standing posture', state => game.local(state).stats[430] !== 2); + await assert.rejects(game.hold('w', 'intentional timeout', () => false, 1), /intentional timeout/); + await game.snapshot(); + + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.hold('KeyD', 'turn toward the open street', state => Math.abs(game.local(state).rotation[3]) < 0.05); + const [x, y] = await game.pick(50000, target.id); + await game.click(x, y); + await game.wait('native world selection', state => state.selected[0] === 50000 && state.selected[1] === target.id); + await game.key('i'); + await game.save(fixture.output + '/inventory'); + await game.key('i'); + await page.setViewportSize({width: 800, height: 600}); + await game.wait('native resolution change', state => state.screen[0] === 800 && state.screen[1] === 600); + const position = game.local().position; + await page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory, inventory); + assert(Math.abs(game.local().position[2] - position[2]) < 0.2); + assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framesent')); + assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framereceived')); + assert(game.events.some(event => event.kind === 'input' && event.stage === 'consumed')); + const state = await fixture.state(context); + assert.equal(state.sitting, false); + assert(state.position[2] > 510.5); + assert.equal(state.items.length, 1); + assert.deepEqual(game.errors, []); + }); +}); + +test('overflow refusal preserves both stacks through restart', {timeout: 180_000}, async () => { + await withFixture('stack-overflow', async fixture => { + const context = await fixture.visitor(); + await fixture.setup(context, 'position', {playfield: 950, position: [52.625, 14.75, 56.875], rotation: [0, 0, 0, 1]}); + for (let index = 0; index < 2; ++index) await fixture.setup(context, 'grant-item', {template: 152030}); + await fixture.setup(context, 'item', {id: 1, slot: 64, count: 1}); + const before = await fixture.setup(context, 'item', {id: 2, slot: 65, count: 65535}); + const cookies = await context.cookies(); + const game = await fixture.game(context); + await game.key('i'); + const cell = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); + const click = async slot => { + const source = cell(slot); + assert(source, 'the exact source must be usable'); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + }; + for (const attempt of [0, 1]) { + const sequence = game.sequence; + await click(48); + await click(49); + await game.wait('actual overflow join request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); + await game.save(fixture.output + '/refused-' + attempt); + await game.wait('both overflow sources remain usable', () => cell(48) && cell(49)); + assert.deepEqual(game.state.dragged, [0, 0]); + assert.deepEqual(game.local().inventory.map(item => [item.slot, item.count]).sort((a, b) => a[0] - b[0]), + [[48, 1], [49, 65535]]); + const state = await fixture.state(context); + assert.deepEqual(state.items, before.items); + assert.equal(state.lastItem, 2); + } + await game.page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.count]).sort((a, b) => a[0] - b[0]), + [[1, 48, 1], [2, 49, 65535]]); + assert.deepEqual(game.errors, []); + await game.save(fixture.output + '/before-restart'); + await fixture.restart(); + const restored = await fixture.context(); + await restored.addCookies(cookies); + const state = await fixture.state(restored); + assert.deepEqual(state.items, before.items); + assert.equal(state.lastItem, 2); + }); +}); + +test('two starter accounts retain exact private progress after cold restart', {timeout: 240_000}, async () => { + await withFixture('starter-cold', async fixture => { + const context = await fixture.visitor(); + const expected = {}; + for (const name of ['Starterowner', 'Starterwatch']) { + const response = await context.request.post(fixture.url + '/browser-account/create', {form: { + name, password: 'starter regression password', head_mesh: '40681', + profession: '9', side: '2', build: '1', height: '100'}}); + assert.equal(response.status(), 204, await response.text()); + if (name === 'Starterowner') { + await fixture.setup(context, 'progress', {level: 2, experience: 150, ip: 5006, credits: 50}); + const state = await fixture.state(context); + for (const item of state.items) { + if (item.templates[0] === 121564) await fixture.setup(context, 'item', {id: item.id, slot: 6, count: item.count}); + if (item.templates[0] === 116628) await fixture.setup(context, 'item', {id: item.id, slot: item.slot, count: 17}); + } + } + const state = await fixture.state(context); + expected[name] = {items: state.items, level: state.level, experience: state.experience, ip: state.ip, credits: state.credits}; + } + await fixture.restart(); + const evidence = await checkStarterCold(fixture.browser, fixture.url, fixture.output, async page => { + const state = await fixture.state(page.context()); + assert.deepEqual({items: state.items, level: state.level, experience: state.experience, ip: state.ip, credits: state.credits}, expected[state.name]); + return {...state, items: state.items.map(item => [item.id, item.type, item.slot, item.quality, item.count, ...item.templates])}; + }); + assert.equal(evidence.Starterowner.credits, 50); + assert.equal(evidence.Starterowner.ip, 5006); + }); +}); + +test('a failing scenario closes its browser, server and temporary database', {timeout: 120_000}, async () => { + let fixture; + await assert.rejects(withFixture('cleanup-failure', async running => { + fixture = running; + await running.game(await running.visitor()); + throw new Error('intentional scenario failure'); + }), /intentional scenario failure/); + assert.equal(fixture.browser.isConnected(), false); + assert.equal(fixture.process.exitCode, 0); + await assert.rejects(fs.stat(fixture.directory), {code: 'ENOENT'}); + await assert.rejects(fetch(fixture.url), /fetch failed/); +}); diff --git a/tests/e2e/fixture.mjs b/tests/e2e/fixture.mjs @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict'; +import {spawn, execFile} from 'node:child_process'; +import {createWriteStream} from 'node:fs'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import {createInterface} from 'node:readline'; +import {fileURLToPath} from 'node:url'; +import {promisify} from 'node:util'; +import {GameTest} from '../../tools/client/game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const root = fileURLToPath(new URL('../../', import.meta.url)); +const binary = path.join(root, 'local/e2e-server'); + +export async function buildServer() { + await promisify(execFile)('go', ['build', '-tags=e2e', '-o', binary, './server'], {cwd: root}); +} + +class Fixture { + games = []; + starts = 0; + + async start() { + const child = spawn(binary, {cwd: this.directory, stdio: ['ignore', 'pipe', 'pipe']}); + this.process = child; + this.exited = new Promise(resolve => child.once('exit', (code, signal) => resolve({code, signal}))); + child.stderr.pipe(createWriteStream(path.join(this.output, `server-${++this.starts}.log`))); + const lines = createInterface({input: child.stdout}); + try { + this.url = await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error('Test server startup timed out')), 60_000); + const finish = callback => value => { clearTimeout(timeout); callback(value); }; + child.once('error', finish(reject)); + this.exited.then(finish(result => reject(new Error(`Test server exited before ready: ${JSON.stringify(result)}`)))); + lines.once('line', finish(line => { + try { resolve(JSON.parse(line).url); } + catch (error) { reject(error); } + })); + }); + } finally { + lines.close(); + } + assert.match(this.url, /^http:\/\/127\.0\.0\.1:\d+$/); + } + + async stop() { + if (!this.process?.pid) return; + if (this.process.exitCode === null && this.process.signalCode === null) this.process.kill('SIGTERM'); + const timeout = setTimeout(() => this.process.kill('SIGKILL'), 15_000); + try { + const result = await this.exited; + assert.deepEqual(result, {code: 0, signal: null}, 'The server must checkpoint and exit cleanly'); + } finally { + clearTimeout(timeout); + } + } + + async restart() { + for (const context of this.browser.contexts()) await context.close(); + await this.stop(); + await this.start(); + } + + async context() { + return this.browser.newContext({viewport: {width: 1024, height: 768}}); + } + + async visitor() { + const context = await this.context(); + const response = await context.request.post(this.url + '/browser-launch'); + assert.equal(response.status(), 200); + return context; + } + + async state(context) { + const response = await context.request.get(this.url + '/_test/player'); + assert.equal(response.status(), 200, await response.text()); + return response.json(); + } + + async setup(context, operation, data) { + const response = await context.request.post(this.url + '/_test/player/' + operation, {data}); + assert.equal(response.status(), 200, await response.text()); + return response.json(); + } + + async game(context) { + const page = await context.newPage(); + const game = await GameTest.attach(page); + this.games.push(game); + await page.goto(this.url); + await game.ready(); + return game; + } + + async close() { + try { + for (let index = 0; index < this.games.length; ++index) { + const game = this.games[index]; + if (!game.page.isClosed()) await game.save(path.join(this.output, 'final-' + index)); + } + } finally { + try { if (this.browser) await this.browser.close(); } + finally { + try { await this.stop(); } + finally { await fs.rm(this.directory, {recursive: true, force: true}); } + } + } + } +} + +export async function withFixture(name, run) { + const fixture = new Fixture(); + fixture.directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ao-e2e-')); + fixture.output = path.join(root, 'local/e2e', Date.now() + '-' + name); + try { + await fs.mkdir(fixture.output, {recursive: true}); + await fs.symlink(path.join(root, 'server/assets'), path.join(fixture.directory, 'assets')); + await fixture.start(); + fixture.browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); + await run(fixture); + } finally { + await fixture.close(); + } +} diff --git a/tests/e2e/starter-cold.mjs b/tests/e2e/starter-cold.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {GameTest} from '../../tools/client/game_test.mjs'; + +export async function checkStarterCold(browser, url, output, readState) { + const games = []; + const evidence = {}; + try { + for (const name of ['Starterowner', 'Starterwatch']) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + const page = await context.newPage(); + const game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.keyboard.press('Control+Alt+M'); + await page.locator('#login-button').click(); + await page.locator('#account-name').fill(name); + await page.locator('#account-password').fill('starter regression password'); + await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]); + await game.ready(); + const state = await readState(page); + assert.equal(state.name, name); + assert.equal(game.local().playfield, state.playfield); + assert.equal(game.local().stats[54], state.level); + assert.equal(game.local().stats[52], state.experience); + assert.equal(game.local().stats[53], state.ip); + assert.equal(game.local().stats[61], state.credits); + assert.equal(game.local().stats[27], state.health); + assert.equal(game.local().stats[1], state.maximumHealth); + const expected = state.items.map(([id, type, slot, quality, count, low, high]) => + [id, type, slot >= 64 ? slot - 16 : slot, quality, count, low, high]).sort((a, b) => a[0] - b[0]); + const actual = game.local().inventory.map(item => + [item.id, item.type, item.slot, item.quality, item.count, ...item.templates]).sort((a, b) => a[0] - b[0]); + assert.deepEqual(actual, expected); + assert.deepEqual(game.errors, []); + evidence[name] = state; + await game.key('KeyI'); + await game.save(output + '/' + name); + } + assert.equal(evidence.Starterowner.level, 2); + assert.equal(evidence.Starterwatch.level, 1); + assert.equal(evidence.Starterwatch.credits, 0); + assert.equal(evidence.Starterwatch.ip, 1500); + return evidence; + } finally { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + for (let index = 0; index < games.length; ++index) await games[index].save(output + '/final-' + index); + } +} diff --git a/tools/client/test_game.mjs b/tools/client/test_game.mjs @@ -1,64 +0,0 @@ -import assert from 'node:assert/strict'; -import {createRequire} from 'node:module'; -import {GameTest} from './game_test.mjs'; - -const {chromium} = createRequire(import.meta.url)('playwright'); -const [url, output] = process.argv.slice(2); -assert(url && output, 'Run through TestBrowserGameHarness'); -const browser = await chromium.launch({executablePath: '/usr/bin/chromium', - args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']}); -let game; -try { - const context = await browser.newContext({viewport: {width: 1024, height: 768}}); - await context.addCookies([{name: 'ao_client', value: 'game-harness', url}]); - const page = await context.newPage(); - game = await GameTest.attach(page); - - await page.goto(url); - await game.ready(); - assert.equal(game.state.localId, 1); - assert.equal(game.local().inventory[0].templates[0], 121567); - const inventory = game.local().inventory; - console.log('PASS: coherent actor, stats and inventory readiness'); - - const z = game.local().position[2]; - await game.hold('KeyS', 'backward movement', state => game.local(state).position[2] < z - 0.5); - await game.hold('KeyW', 'forward movement', state => game.local(state).position[2] > z + 0.5); - await game.key('F1'); - await game.wait('self selection', state => state.selected[0] === 50000 && state.selected[1] === 1); - await game.key('x'); - await game.wait('sitting posture', state => game.local(state).stats[430] === 2); - const posture = await (await context.request.get(url + '/test-state')).json(); - assert.equal(posture.sitting, true); - await game.key('x'); - await game.wait('standing posture', state => game.local(state).stats[430] !== 2); - await assert.rejects(game.hold('w', 'intentional timeout', () => false, 1), /intentional timeout/); - await game.snapshot(); - console.log('PASS: real movement, targeting and posture controls'); - - if (!game.state.camera.firstPerson) await game.key('F8'); - await game.hold('KeyD', 'turn toward the open street', state => Math.abs(game.local(state).rotation[3]) < 0.05); - const [x, y] = await game.pick(50000, 1000000); - await game.click(x, y); - await game.wait('native world selection', state => state.selected[0] === 50000 && state.selected[1] === 1000000); - console.log('PASS: projected coordinates, native picking and mouse input'); - - await game.key('i'); - await game.save(output + '/inventory'); - await game.key('i'); - await page.setViewportSize({width: 800, height: 600}); - await game.wait('native resolution change', state => state.screen[0] === 800 && state.screen[1] === 600); - const position = game.local().position; - await page.reload(); - await game.ready(); - - assert.deepEqual(game.local().inventory, inventory); - assert(Math.abs(game.local().position[2] - position[2]) < 0.2); - assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framesent')); - assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framereceived')); - assert(game.events.some(event => event.kind === 'input' && event.stage === 'consumed')); - console.log('PASS: viewport changes, reload reconstruction and bidirectional tracing'); -} finally { - try { if (game) await game.save(output); } - finally { await browser.close(); } -} diff --git a/tools/client/test_stack_overflow.mjs b/tools/client/test_stack_overflow.mjs @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import {createRequire} from 'node:module'; -import {GameTest} from './game_test.mjs'; - -const {chromium} = createRequire(import.meta.url)('playwright'); -const [url, output] = process.argv.slice(2); -const browser = await chromium.launch({executablePath: '/usr/bin/chromium', - args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', - '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); -let game; -try { - const context = await browser.newContext({viewport: {width: 1024, height: 768}}); - await context.addCookies([{name: 'ao_client', value: 'stack-overflow', url}]); - const page = await context.newPage(); - game = await GameTest.attach(page); - await page.goto(url); - await game.ready(); - await game.key('i'); - const cell = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => - cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); - const click = async slot => { - const source = cell(slot); - assert(source, 'the exact source must be usable'); - await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); - }; - - // Repeated real joins must be refused without hiding either retained stack. - for (const attempt of [0, 1]) { - const sequence = game.sequence; - await click(48); - await click(49); - await game.wait('actual overflow join request', () => game.events.some(event => event.sequence > sequence && - event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); - await game.save(output + '/refused-' + attempt); - await game.wait('both overflow sources remain usable', () => cell(48) && cell(49)); - assert.deepEqual(game.state.dragged, [0, 0]); - assert.deepEqual(game.local().inventory.map(item => [item.slot, item.count]).sort((a, b) => a[0] - b[0]), - [[48, 1], [49, 65535]]); - } - await page.reload(); - await game.ready(); - assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.count]).sort((a, b) => a[0] - b[0]), - [[1, 48, 1], [2, 49, 65535]]); - assert.deepEqual(game.errors, []); - console.log('PASS: repeated overflow refusal preserves usable icons and all 65536 charges through page recovery'); -} finally { - try { - await fs.mkdir(output, {recursive: true}); - if (game) await game.save(output + '/final'); - } finally { await browser.close(); } -} diff --git a/tools/client/test_starter_cold.mjs b/tools/client/test_starter_cold.mjs @@ -1,57 +1,13 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; import {createRequire} from 'node:module'; -import {GameTest} from './game_test.mjs'; +import {checkStarterCold} from '../../tests/e2e/starter-cold.mjs'; const {chromium} = createRequire(import.meta.url)('playwright'); const [url, output] = process.argv.slice(2); const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); -const games = []; -const evidence = {}; try { - for (const name of ['Starterowner', 'Starterwatch']) { - const context = await browser.newContext({viewport: {width: 1024, height: 768}}); - const page = await context.newPage(); - const game = await GameTest.attach(page); - games.push(game); - await page.goto(url); - await game.ready(); - await page.keyboard.press('Control+Alt+M'); - await page.locator('#login-button').click(); - await page.locator('#account-name').fill(name); - await page.locator('#account-password').fill('starter regression password'); - await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]); - await game.ready(); - const state = await (await page.request.get(url + '/test-state')).json(); - assert.equal(state.name, name); - assert.equal(game.local().playfield, state.playfield); - assert.equal(game.local().stats[54], state.level); - assert.equal(game.local().stats[52], state.experience); - assert.equal(game.local().stats[53], state.ip); - assert.equal(game.local().stats[61], state.credits); - assert.equal(game.local().stats[27], state.health); - assert.equal(game.local().stats[1], state.maximumHealth); - const expected = state.items.map(([id, type, slot, quality, count, low, high]) => - [id, type, slot >= 64 ? slot - 16 : slot, quality, count, low, high]).sort((a, b) => a[0] - b[0]); - const actual = game.local().inventory.map(item => - [item.id, item.type, item.slot, item.quality, item.count, ...item.templates]).sort((a, b) => a[0] - b[0]); - assert.deepEqual(actual, expected); - assert.deepEqual(game.errors, []); - evidence[name] = state; - await game.key('KeyI'); - await game.save(output + '/' + name); - } - assert.equal(evidence.Starterowner.level, 2); - assert.equal(evidence.Starterwatch.level, 1); - assert.equal(evidence.Starterwatch.credits, 0); - assert.equal(evidence.Starterwatch.ip, 1500); - console.log('PASS: two fresh native clients log into cold starter profiles with exact items, charges, levels, IP, wallets and resource maxima'); + await checkStarterCold(browser, url, output, async page => (await page.request.get(url + '/test-state')).json()); } finally { - try { - await fs.mkdir(output, {recursive: true}); - await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); - for (let index = 0; index < games.length; ++index) await games[index].save(output + '/final-' + index); - } finally { await browser.close(); } + await browser.close(); }