aorecomp

Anarchy Online classic in the browser

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


server/browser_faction_insurance_test.go (6322B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"context"
      6 	"crypto/sha256"
      7 	"encoding/json"
      8 	"fmt"
      9 	"net/http"
     10 	"net/http/httptest"
     11 	"os"
     12 	"os/exec"
     13 	"path/filepath"
     14 	"runtime"
     15 	"slices"
     16 	"testing"
     17 	"time"
     18 )
     19 
     20 func TestBrowserFactionInsuranceCheckpoint(t *testing.T) {
     21 	if os.Getenv("AO_GAME_TEST") != "1" {
     22 		t.Skip("set AO_GAME_TEST=1 for focused faction insurance recovery")
     23 	}
     24 	_, source, _, _ := runtime.Caller(0)
     25 	root := filepath.Dir(filepath.Dir(source))
     26 	output := filepath.Join(root, "local/faction-checkpoint", time.Now().Format("20060102-150405"))
     27 	configs := []struct {
     28 		city, scanner, reclaim uint32
     29 		appearance             uint16
     30 	}{
     31 		{640, 3221357184, 3221357184, 0x315},
     32 		{566, 3221357110, 3221291574, 0x115},
     33 	}
     34 
     35 	t.Chdir(t.TempDir())
     36 	for _, phase := range []string{"warm", "cold"} {
     37 		t.Run(phase, func(t *testing.T) {
     38 			world := newServerForTest(t)
     39 			world.combatRoll = landedCombatRoll
     40 			// Controlled scanner checkpoints isolate recovery without earning levels.
     41 			// Hold regeneration so one ordinary retaliatory hit is fatal.
     42 			if phase == "warm" {
     43 				world.characters = make(map[uint32]*character)
     44 				world.mobileNPCs = make(map[uint32][]*character)
     45 				world.nextNPC = 9000003
     46 				// Keep the encounter alive long enough to deliver fatal retaliation.
     47 				profile := *gamedata.NPCCombatProfiles[17655][1]
     48 				profile.Health = 100
     49 				for index, config := range configs {
     50 					player := world.newCharacter()
     51 					player.name, player.level, player.appearance = fmt.Sprint("InsuranceRoute", index), 10, config.appearance
     52 					player.rotation = [4]float32{0, 0, 0, 1}
     53 					player.playfield = config.city
     54 					player.position = gamedata.InsuranceTerminals.Scanners[config.scanner].Arrival.Position
     55 					player.health, player.nano = 1, 1
     56 					player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("faction-route-", index))))
     57 					if err := world.saveUser(player); err != nil {
     58 						t.Fatal(err)
     59 					}
     60 					for _, template := range []uint32{209283, 42640, 25812, 21609} {
     61 						if ok, err := world.grantItem(player, template); err != nil || !ok {
     62 							t.Fatal(ok, err)
     63 						}
     64 					}
     65 					inventory := player.inventory
     66 					inventory.Items[0].Slot, inventory.Credits = 6, 37
     67 					if err := world.saveInventory(player, inventory); err != nil {
     68 						t.Fatal(err)
     69 					}
     70 					scanner := gamedata.InsuranceTerminals.Scanners[config.scanner]
     71 					position := scanner.Arrival.Position
     72 					position[0] += 1
     73 					enemy := &character{id: 9000001 + uint32(index), name: "Insurance encounter", npc: true,
     74 						playfield: config.city, position: position, rotation: [4]float32{0, 0, 0, 1}, appearance: 229,
     75 						monsterData: 17655, level: 1, health: 100, combatProfile: &profile, geometry: world.geometry}
     76 					world.characters[enemy.id] = enemy
     77 				}
     78 			}
     79 			actors := world.characters
     80 			shutdown := startTestService(t, world)
     81 			mux := http.NewServeMux()
     82 			mux.Handle("/", world.httpHandler())
     83 			mux.HandleFunc("POST /test-defer-recovery", testBrowserHTTP(world, deferTestRecovery))
     84 			mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
     85 				var rows []json.RawMessage
     86 				for index, config := range configs {
     87 					response := httptest.NewRecorder()
     88 					world.servePlayerHTTP(response, r.Clone(r.Context()), uint32(index+1), func(world *server, response http.ResponseWriter, r *http.Request) {
     89 						player := world.characters[uint32(index+1)]
     90 						json.NewEncoder(response).Encode(map[string]any{"id": player.id, "field": player.playfield,
     91 							"position": predictedPosition(player, time.Now()), "health": player.health, "fighting": player.fighting,
     92 							"inventory": player.inventory, "scanner": player.resurrectionTerminal, "insured": player.insuredExperience,
     93 							"experience": player.experience, "stats": player.stats, "returnDoor": player.returnDoor,
     94 							"city": config.city, "scannerID": config.scanner, "reclaimID": config.reclaim,
     95 							"arrival":         gamedata.InsuranceTerminals.Scanners[config.scanner].Arrival.Position,
     96 							"scannerPosition": gamedata.InsuranceTerminals.Scanners[config.scanner].Position,
     97 							"reclaimPosition": gamedata.InsuranceTerminals.Reclaim[config.reclaim].Position, "enemy": 9000001 + uint32(index)})
     98 					})
     99 					if response.Code != http.StatusOK {
    100 						http.Error(w, response.Body.String(), response.Code)
    101 						return
    102 					}
    103 					rows = append(rows, json.RawMessage(response.Body.Bytes()))
    104 				}
    105 				json.NewEncoder(w).Encode(map[string]any{"phase": phase, "players": rows})
    106 			})
    107 			host := httptest.NewServer(mux)
    108 			t.Cleanup(host.Close)
    109 			ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
    110 			defer cancel()
    111 			if err := os.MkdirAll(filepath.Join(output, phase), 0755); err != nil {
    112 				t.Fatal(err)
    113 			}
    114 			command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_faction_insurance.mjs"), host.URL, filepath.Join(output, phase))
    115 			command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
    116 			err := command.Run()
    117 			cancel()
    118 			host.Close()
    119 			if err := shutdown(); err != nil {
    120 				t.Fatal(err)
    121 			}
    122 			copyTestDatabase(t, filepath.Join(output, phase, "world.sqlite"))
    123 			t.Logf("Browser artifacts: %s", output)
    124 
    125 			if err != nil {
    126 				t.Fatal(err)
    127 			}
    128 			for index, config := range configs {
    129 				player := actors[uint32(index+1)]
    130 				first := uint32(index*4 + 1)
    131 				expected := []ownedItem{
    132 					{ID: first, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1},
    133 					{ID: first + 1, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1},
    134 					{ID: first + 2, Type: 51005, Template: 25812, Quality: 1, Slot: 65, Count: 50},
    135 					{ID: first + 3, Type: 51005, Template: 21609, Quality: 1, Slot: 66, Count: 100},
    136 				}
    137 				if !slices.Equal(player.inventory.Items, expected) || len(player.inventory.Reclaim) != 0 ||
    138 					player.inventory.Credits != 37 || player.playfield != config.city || player.health != 1 || player.nano != 1 ||
    139 					player.resurrectionTerminal != config.scanner || player.insuredExperience != 38650 ||
    140 					player.level != 10 || player.experience != 0 || player.stats != defaultCharacterStats(player.appearance>>4&7) {
    141 					t.Fatal("faction recovery lost its save or exact ownership", player.userData(), player.inventory)
    142 				}
    143 			}
    144 		})
    145 		if t.Failed() {
    146 			return
    147 		}
    148 	}
    149 }