aorecomp

Anarchy Online classic in the browser

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


server/control_player_form_test.go (6389B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"html"
      6 	"net/http"
      7 	"net/http/httptest"
      8 	"net/url"
      9 	"regexp"
     10 	"strconv"
     11 	"strings"
     12 	"testing"
     13 
     14 	"go.yaml.in/yaml/v3"
     15 )
     16 
     17 // Existing gameplay fixtures use YAML for concise setup, then submit actual form fields.
     18 func playerFixtureForm(document string) url.Values {
     19 	if document == "" {
     20 		return make(url.Values)
     21 	}
     22 	var node yaml.Node
     23 	if err := yaml.Unmarshal([]byte(document), &node); err != nil {
     24 		panic(err)
     25 	}
     26 	values := make(url.Values)
     27 	var visit func(string, *yaml.Node)
     28 	visit = func(path string, node *yaml.Node) {
     29 		if path == "id" || path == "browser_token_hash" {
     30 			return
     31 		}
     32 		if node.Kind == yaml.MappingNode {
     33 			for i := 0; i < len(node.Content); i += 2 {
     34 				name := node.Content[i].Value
     35 				if path != "" {
     36 					name = path + "." + name
     37 				}
     38 				visit(name, node.Content[i+1])
     39 			}
     40 			return
     41 		}
     42 		if node.Kind == yaml.SequenceNode {
     43 			if path == "inventory.learned_nanos" {
     44 				parts := make([]string, len(node.Content))
     45 				for i, n := range node.Content {
     46 					parts[i] = n.Value
     47 				}
     48 				values.Add(path, strings.Join(parts, ","))
     49 				return
     50 			}
     51 			for i, n := range node.Content {
     52 				name := strconv.Itoa(i)
     53 				if path == "position" || path == "rotation" {
     54 					name = string("xyzw"[i])
     55 				}
     56 				visit(path+"."+name, n)
     57 			}
     58 			return
     59 		}
     60 		if path == "return_door" && node.Tag == "!!null" {
     61 			values.Set("return_door.playfield", "0")
     62 			values.Set("return_door.door", "0")
     63 			return
     64 		}
     65 		if path == "inventory.reclaim" && node.Tag == "!!null" {
     66 			return
     67 		}
     68 		switch path {
     69 		case "playfield":
     70 			path = "location.playfield"
     71 		case "head_mesh", "height", "monster_data":
     72 			path = "appearance." + path
     73 		case "resurrection_terminal", "implant_changes_until":
     74 			path = "recovery." + path
     75 		}
     76 		path = strings.Replace(path, "inventory.reclaim.", "reclaim.", 1)
     77 		value := node.Value
     78 		if node.Tag == "!!null" {
     79 			value = ""
     80 		}
     81 		values.Add(path, value)
     82 	}
     83 	visit("", node.Content[0])
     84 	return values
     85 }
     86 
     87 func playerEditorForm(t *testing.T, data characterEditor) url.Values {
     88 	t.Helper()
     89 	var page strings.Builder
     90 	renderPlayerForm(&page, data)
     91 	return playerPageValues(t, page.String())
     92 }
     93 
     94 func playerPageValues(t *testing.T, markup string) url.Values {
     95 	t.Helper()
     96 	values := make(url.Values)
     97 	for _, match := range regexp.MustCompile(`<input type='[^']+' name='([^']+)' value='([^']*)'`).FindAllStringSubmatch(markup, -1) {
     98 		values.Set(html.UnescapeString(match[1]), html.UnescapeString(match[2]))
     99 	}
    100 	for _, match := range regexp.MustCompile(`(?s)<select name='([^']+)'>(.*?)</select>`).FindAllStringSubmatch(markup, -1) {
    101 		selected := regexp.MustCompile(`<option value='([^']*)' selected>`).FindStringSubmatch(match[2])
    102 		if len(selected) != 2 {
    103 			t.Fatalf("missing selection: %s", match[0])
    104 		}
    105 		values.Set(match[1], html.UnescapeString(selected[1]))
    106 	}
    107 	return values
    108 }
    109 
    110 func TestPlayerFormRoundTripAndValidation(t *testing.T) {
    111 	world := newControlInventoryWorld(t)
    112 	page := httptest.NewRecorder()
    113 	adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil))
    114 	fields := playerPageValues(t, page.Body.String())
    115 	fields.Set("name", "Edited Explorer")
    116 	fields.Set("title", "A & B")
    117 	fields.Set("stats.ranged.rifle", "42")
    118 	fields.Set("inventory.credits", "913")
    119 	fields.Set("running", "false")
    120 
    121 	response := postControlForm(world, "/admin/players/1", fields)
    122 	restarted := newServerForTest(t)
    123 
    124 	if response.Code != http.StatusSeeOther {
    125 		t.Fatal(response.Code, response.Body.String())
    126 	}
    127 	player := restarted.characters[1]
    128 	if player.name != "Edited Explorer" || player.title != "A & B" || player.stats.Ranged.Rifle != 42 || player.inventory.Credits != 913 || player.running || len(player.inventory.Items) != 3 || len(player.inventory.Containers[3]) != 1 || player.returnDoor != nil {
    129 		t.Fatal("form did not preserve the player and item ownership", player.name, player.inventory)
    130 	}
    131 	if strings.Contains(page.Body.String(), "<textarea") || strings.Contains(page.Body.String(), "<details") || strings.Contains(page.Body.String(), "browser_token_hash") {
    132 		t.Fatal("player page exposes a document or credential field")
    133 	}
    134 }
    135 
    136 func TestPlayerFormRejectsInvalidFieldsWithoutChangingState(t *testing.T) {
    137 	for _, fields := range []url.Values{
    138 		{"level": {"65536"}}, {"stats.ranged.rifle": {"-1"}}, {"position.x": {"NaN"}},
    139 		{"running": {"maybe"}}, {"recovery.implant_changes_until": {"yesterday"}},
    140 		{"inventory.slots.inventory_slot_2": {"1"}}, {"name": {"First", "Second"}},
    141 		{"data": {"name: Changed"}}, {"id": {"2"}}, {"browser_token_hash": {"changed"}},
    142 	} {
    143 		t.Run(fmt.Sprint(fields), func(t *testing.T) {
    144 			world := newControlInventoryWorld(t)
    145 			before, err := readTestItemStore(world)
    146 			if err != nil {
    147 				t.Fatal(err)
    148 			}
    149 			fields.Set("title", "Must not save")
    150 
    151 			response := postControlForm(world, "/admin/players/1", fields)
    152 			restarted := newServerForTest(t)
    153 			after, err := readTestItemStore(restarted)
    154 
    155 			if response.Code != http.StatusBadRequest || err != nil || string(before) != string(after) || world.characters[1].title != "" || restarted.characters[1].title != "" {
    156 				t.Fatal(response.Code, response.Body.String(), err)
    157 			}
    158 		})
    159 	}
    160 }
    161 
    162 func TestPlayerFormClearsReclaimWithoutDeletingTheItem(t *testing.T) {
    163 	world := newControlInventoryWorld(t)
    164 	prepared := postControlForm(world, "/admin/players/1", url.Values{
    165 		"inventory.slots.inventory_slot_1": {""},
    166 		"reclaim.0.id":                     {"1"},
    167 		"reclaim.0.original_slot":          {"inventory_slot_1"},
    168 		"reclaim.0.available_at":           {"2026-10-23T00:00:00Z"},
    169 	})
    170 	if prepared.Code != http.StatusSeeOther {
    171 		t.Fatal(prepared.Code, prepared.Body.String())
    172 	}
    173 	page := httptest.NewRecorder()
    174 	adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil))
    175 	fields := playerPageValues(t, page.Body.String())
    176 	fields.Set("reclaim.0.id", "0")
    177 
    178 	response := postControlForm(world, "/admin/players/1", fields)
    179 	restarted := newServerForTest(t)
    180 	var placements int
    181 	err := restarted.db.QueryRow("SELECT count(*) FROM item_locations WHERE item_id=1").Scan(&placements)
    182 
    183 	if response.Code != http.StatusSeeOther || err != nil || placements != 0 || len(restarted.characters[1].inventory.Reclaim) != 0 || len(restarted.items) != 4 {
    184 		t.Fatal("clearing reclaim lost the item or retained its placement", response.Code, response.Body.String(), placements, err)
    185 	}
    186 }