-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather_admin_test.go
More file actions
501 lines (469 loc) · 18 KB
/
Copy pathweather_admin_test.go
File metadata and controls
501 lines (469 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package weather
import (
"fmt"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/GoMudEngine/GoMud/modules/weather/seasons"
"github.com/GoMudEngine/GoMud/modules/weather/sim"
)
func adminTestModule() *weatherModule {
g := &sim.Graph{Nodes: map[string]sim.ZoneNode{
"Frost": {Zone: "Frost", Biome: "tundra"},
"Dune": {Zone: "Dune", Biome: "desert"},
}}
m := &weatherModule{
cfg: buildConfig(func(string) any { return nil }),
graph: g,
simReady: true,
seasonsOn: true,
simCfg: sim.DefaultConfig(),
state: sim.State{
Round: 42,
Fronts: []sim.Front{{Id: 7, Type: "storm", Zone: "Frost", Intensity: 0.8, Age: 3, MaxAge: 24}},
Weather: map[sim.ZoneId]sim.WeatherType{
"Frost": "storm", "Dune": sim.Clear,
},
},
zoneSeasons: map[sim.ZoneId]seasons.ZoneSeason{
"Frost": {Track: "temperate", Season: "winter", Blend: 1.0},
},
nextTick: 1000,
}
return m
}
func TestBuildSnapshot(t *testing.T) {
m := adminTestModule()
s := m.buildSnapshot()
if !s.SimReady || !s.SeasonsOn {
t.Errorf("flags: %+v", s)
}
if s.Round != 42 || s.NextTickRound != 1000 {
t.Errorf("rounds: %+v", s)
}
if len(s.Fronts) != 1 || s.Fronts[0].Type != "storm" || s.Fronts[0].Zone != "Frost" {
t.Errorf("fronts: %+v", s.Fronts)
}
if len(s.Zones) != 2 {
t.Fatalf("zones: %+v", s.Zones)
}
// Zones sorted by name; Dune first.
if s.Zones[0].Zone != "Dune" || s.Zones[0].Weather != "clear" || s.Zones[0].Season != "" {
t.Errorf("Dune row: %+v", s.Zones[0])
}
if s.Zones[1].Zone != "Frost" || s.Zones[1].Weather != "storm" || s.Zones[1].Season != "winter" || s.Zones[1].Track != "temperate" {
t.Errorf("Frost row: %+v", s.Zones[1])
}
// Config rows cover every public key with a badge.
if len(s.Config) == 0 {
t.Fatal("config rows missing")
}
seen := map[string]bool{}
for _, c := range s.Config {
seen[c.Key] = true
if c.Badge == "" {
t.Errorf("key %s missing badge", c.Key)
}
}
for _, want := range []string{"TickEveryGameHours", "SeasonsEnabled", "BuffsEnabled", "Enabled", "Seed", "PerRoomRefinement", "ExcludeZonePatterns", "BuffOverrides.*"} {
if !seen[want] {
t.Errorf("config row for %s missing", want)
}
}
}
func TestBuildSnapshotRefinementFields(t *testing.T) {
m := adminTestModule()
// Default mode is "occupied"; no players in the test world -> 0 rooms.
s := m.buildSnapshot()
if s.RefinementMode != RefineOccupied {
t.Errorf("RefinementMode: %q", s.RefinementMode)
}
if s.RefinedRooms != 0 {
t.Errorf("RefinedRooms should be 0 with no players: %d", s.RefinedRooms)
}
m.cfg.PerRoomRefinement = RefineOff
if s = m.buildSnapshot(); s.RefinementMode != RefineOff || s.RefinedRooms != 0 {
t.Errorf("off mode: %q %d", s.RefinementMode, s.RefinedRooms)
}
}
func TestApplyConfigChangeRefinementMode(t *testing.T) {
// Mode switches run their LiveApply on the game loop; in this unit test the
// graph zones aren't in the live room registry, so the engine calls are
// no-op loops — we validate adoption and snapshot refresh.
m := adminTestModule()
for _, mode := range []string{RefineAll, RefineOff, RefineOccupied} {
newCfg := m.cfg
newCfg.PerRoomRefinement = mode
m.applyConfigChange(newCfg, "PerRoomRefinement")
if m.cfg.PerRoomRefinement != mode {
t.Fatalf("mode %q not adopted: %q", mode, m.cfg.PerRoomRefinement)
}
if snap := loadSnapshot(); snap.RefinementMode != mode {
t.Errorf("snapshot not refreshed for %q: %q", mode, snap.RefinementMode)
}
}
}
func TestSnapshotIsolation(t *testing.T) {
m := adminTestModule()
s := m.buildSnapshot()
// Mutating the snapshot must not touch module state (deep copy).
s.Fronts[0].Type = "tampered"
s.Zones[0].Weather = "tampered"
if m.state.Fronts[0].Type != "storm" || m.state.Weather["Dune"] != sim.Clear {
t.Error("snapshot shares memory with module state")
}
}
func TestPublishAndLoadSnapshot(t *testing.T) {
m := adminTestModule()
m.publishSnapshot()
s := loadSnapshot()
if s == nil || !s.SimReady {
t.Fatalf("published snapshot not readable: %+v", s)
}
if !strings.Contains(strings.Join(configKeysOf(s), ","), "SpawnRateScale") {
t.Error("config keys incomplete")
}
}
func configKeysOf(s *AdminSnapshot) []string {
out := make([]string, 0, len(s.Config))
for _, c := range s.Config {
out = append(out, c.Key)
}
return out
}
func TestConfigKeyMetaCoversAllKeys(t *testing.T) {
m := adminTestModule()
for _, row := range m.configRows() {
meta, ok := configKeyMeta[row.Key]
if !ok {
t.Errorf("no meta for %s", row.Key)
continue
}
if meta.Badge != row.Badge {
t.Errorf("%s: row badge %q != meta badge %q", row.Key, row.Badge, meta.Badge)
}
}
// Single source for the expected key count.
const wantConfigKeys = 15
if len(configKeyMeta) != wantConfigKeys {
t.Errorf("expected %d config keys, got %d", wantConfigKeys, len(configKeyMeta))
}
}
func TestApplyConfigChangeLiveKeys(t *testing.T) {
m := adminTestModule()
// Simulate a persisted change: cfg re-read happens via loadConfig in the
// real path; here we hand applyConfigChange the new config directly.
newCfg := m.cfg
newCfg.SpawnRateScale = 0 // stops new fronts
newCfg.TickEveryGameHours = 6
m.applyConfigChange(newCfg, "SpawnRateScale")
if m.cfg.SpawnRateScale != 0 {
t.Error("cfg not adopted")
}
if m.simCfg.SpawnChance != 0 {
t.Error("simCfg not re-derived for live key")
}
}
func TestApplyConfigChangeSeasonsToggle(t *testing.T) {
// applyConfigChange's season-disable path calls engine.ReconcileSeasons
// which iterates g.Zones() and calls rooms.GetZoneConfig for each — in this
// unit test the graph zones ("Frost", "Dune") don't exist in the live room
// registry, so GetZoneConfig returns nil and the call is a no-op loop.
// The test therefore validates field mutations without a booted world.
m := adminTestModule()
newCfg := m.cfg
newCfg.SeasonsEnabled = false
m.applyConfigChange(newCfg, "SeasonsEnabled")
if m.seasonsOn {
t.Error("seasons should turn off live")
}
if len(m.zoneSeasons) != 0 {
t.Error("zone seasons should clear on live disable")
}
}
func TestStatusHandler(t *testing.T) {
m := adminTestModule()
m.publishSnapshot()
status, success, data := m.handleAdminStatus(httptest.NewRequest("GET", "/admin/api/v1/weather/status", nil))
if status != 200 || !success {
t.Fatalf("status=%d success=%v", status, success)
}
snap, ok := data.(*AdminSnapshot)
if !ok || !snap.SimReady {
t.Fatalf("payload: %T %+v", data, data)
}
}
func TestConfigHandlerValidation(t *testing.T) {
m := adminTestModule()
bad := httptest.NewRequest("POST", "/x", strings.NewReader(`{"key":"NotAKey","value":"1"}`))
if status, success, _ := m.handleAdminConfig(bad); status != 400 || success {
t.Errorf("unknown key must 400: %d %v", status, success)
}
malformed := httptest.NewRequest("POST", "/x", strings.NewReader(`{nope`))
if status, _, _ := m.handleAdminConfig(malformed); status != 400 {
t.Errorf("malformed body must 400: %d", status)
}
// The synthetic BuffOverrides.* row is display-only: writes must be
// refused here even before the page renders it read-only (Task 6).
readOnly := httptest.NewRequest("POST", "/x", strings.NewReader(`{"key":"BuffOverrides.*","value":"59002"}`))
if status, success, _ := m.handleAdminConfig(readOnly); status != 400 || success {
t.Errorf("read-only key must 400: %d %v", status, success)
}
}
// TestConfigHandlerValueValidation: bad values 400 with a useful message;
// good values pass validation (the fabricated test module has no plugin, so
// they then hit the 503 plug-nil guard — which proves validation PASSED,
// since validation runs before that guard).
func TestConfigHandlerValueValidation(t *testing.T) {
m := adminTestModule()
cases := []struct {
name, key, value string
wantStatus int
wantMsgPart string // for 400s: the message must mention this
}{
// ints (floors are the shared min* constants from weather_config.go,
// so these cases track the loader's clamp block by construction)
{"bad int", "TickEveryGameHours", "abc", 400, "whole number"},
{"int below clamp floor", "TickEveryGameHours", strconv.Itoa(minTickEveryGameHours - 1), 400, fmt.Sprintf("%d or higher", minTickEveryGameHours)},
{"int at exact clamp floor", "TickEveryGameHours", strconv.Itoa(minTickEveryGameHours), 503, ""},
{"good int", "TickEveryGameHours", "6", 503, ""},
{"negative front budget", "MaxActiveFronts", "-1", 400, fmt.Sprintf("%d or higher", minMaxActiveFronts)},
{"good front budget", "MaxActiveFronts", "12", 503, ""},
{"emote cadence below floor", "EmoteEveryRounds", strconv.Itoa(minEmoteEveryRounds - 1), 400, fmt.Sprintf("%d or higher", minEmoteEveryRounds)},
{"emote cadence at exact floor", "EmoteEveryRounds", strconv.Itoa(minEmoteEveryRounds), 503, ""},
{"good emote cadence", "EmoteEveryRounds", "30", 503, ""},
{"negative seed", "Seed", "-3", 400, "0 or higher"},
{"good seed", "Seed", "0", 503, ""},
// floats
{"bad float", "SpawnRateScale", "fast", 400, "not a number"},
{"negative float", "SpawnRateScale", "-0.1", 400, "0 or higher"},
{"good float", "SpawnRateScale", "1.5", 503, ""},
// bools (engine bool parsing = strconv.ParseBool)
{"bad bool", "BuffsEnabled", "maybe", 400, "boolean"},
{"good bool numeric", "BuffsEnabled", "1", 503, ""},
{"good bool uppercase", "Enabled", "TRUE", 503, ""},
{"bad bool yes", "Persist", "yes", 400, "boolean"},
// enums (case-insensitive)
{"bad emote mode", "EmoteMode", "loud", 400, "module, tag-only"},
{"good emote mode mixed case", "EmoteMode", "Tag-Only", 503, ""},
{"bad refinement", "PerRoomRefinement", "sometimes", 400, "occupied, all, off"},
{"good refinement uppercase", "PerRoomRefinement", "ALL", 503, ""},
// free text stays permissive
{"free text", "ExcludeZonePatterns", "instance_*, arena_*", 503, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
body := fmt.Sprintf(`{"key":%q,"value":%q}`, tc.key, tc.value)
req := httptest.NewRequest("POST", "/x", strings.NewReader(body))
status, success, data := m.handleAdminConfig(req)
if status != tc.wantStatus {
t.Fatalf("%s=%q: status %d, want %d (data: %v)", tc.key, tc.value, status, tc.wantStatus, data)
}
if tc.wantStatus == 400 {
if success {
t.Error("400 must not report success")
}
msg, _ := data.(string)
if !strings.Contains(msg, tc.wantMsgPart) {
t.Errorf("message %q should mention %q", msg, tc.wantMsgPart)
}
}
})
}
}
// TestConfigHandlerReadBackGuard: the engine's PluginConfig.Set discards
// configs.SetVal's error, so handleAdminConfig verifies the write by reading
// the value back (via the persistConfigFn seam). Accepted writes 200 with the
// engine-typed read-back; rejected or silently-ignored writes 500 and must
// not report saved.
func TestConfigHandlerReadBackGuard(t *testing.T) {
m := adminTestModule()
orig := persistConfigFn
defer func() { persistConfigFn = orig }()
post := func(key, value string) (int, bool, any) {
body := fmt.Sprintf(`{"key":%q,"value":%q}`, key, value)
return m.handleAdminConfig(httptest.NewRequest("POST", "/x", strings.NewReader(body)))
}
// Engine accepts: read-back returns the ENGINE-typed value (the yaml
// round-trip re-types the normalized string), which must compare equal.
accepted := map[string]any{
"TickEveryGameHours": 3, // "3" -> int
"BuffsEnabled": false, // "false" -> bool
"SpawnRateScale": 1.5, // "1.5" -> float64
"EmoteMode": "tag-only",
}
persistConfigFn = func(_ *weatherModule, key, _ string) (any, bool) {
return accepted[key], true
}
for key, value := range map[string]string{
"TickEveryGameHours": "3", "BuffsEnabled": "false",
"SpawnRateScale": "1.50", "EmoteMode": "TAG-ONLY",
} {
status, success, data := post(key, value)
if status != 200 || !success {
t.Errorf("%s=%q: accepted write must 200: %d %v (%v)", key, value, status, success, data)
}
}
// Engine rejects (unregistered key -> SetVal error swallowed): read-back
// returns nil -> 500, no success.
persistConfigFn = func(*weatherModule, string, string) (any, bool) { return nil, true }
status, success, data := post("TickEveryGameHours", "3")
if status != 500 || success {
t.Errorf("rejected write must 500 without success: %d %v", status, success)
}
if msg, _ := data.(string); !strings.Contains(msg, "engine rejected") {
t.Errorf("500 message should say the engine rejected the write: %q", msg)
}
// Engine silently keeps the OLD value: equally a 500 (value unchanged).
persistConfigFn = func(*weatherModule, string, string) (any, bool) { return 1, true }
if status, success, _ := post("TickEveryGameHours", "3"); status != 500 || success {
t.Errorf("unchanged value must 500: %d %v", status, success)
}
// No plugin (fabricated module, default seam): 503, as before.
persistConfigFn = orig
if status, _, _ := post("TickEveryGameHours", "3"); status != 503 {
t.Errorf("nil plugin must 503: %d", status)
}
}
// TestConfigValidatorsNormalize: the value Validate returns is what gets
// persisted — canonical bools, lowercased enums, trimmed numbers/text.
func TestConfigValidatorsNormalize(t *testing.T) {
cases := []struct{ key, in, want string }{
{"BuffsEnabled", "1", "true"},
{"Persist", "F", "false"},
{"Enabled", "True", "true"},
{"EmoteMode", "TAG-ONLY", "tag-only"},
{"PerRoomRefinement", " Occupied ", "occupied"},
{"TickEveryGameHours", " 6 ", "6"},
{"SpawnRateScale", "1.50", "1.5"},
{"ExcludeZonePatterns", " instance_* ", "instance_*"},
}
for _, tc := range cases {
got, err := configKeyMeta[tc.key].Validate(tc.in)
if err != nil {
t.Errorf("%s=%q: unexpected error %v", tc.key, tc.in, err)
continue
}
if got != tc.want {
t.Errorf("%s=%q: normalized to %q, want %q", tc.key, tc.in, got, tc.want)
}
}
}
// TestConfigKindsAndOptions: every key carries the input kind the page needs;
// enums carry their choices; every writable key validates.
func TestConfigKindsAndOptions(t *testing.T) {
wantKinds := map[string]string{
"Enabled": "bool", "IncludeSecretExits": "bool", "RebuildGraphOnBoot": "bool",
"BuffsEnabled": "bool", "Persist": "bool", "SeasonsEnabled": "bool",
"Seed": "int", "TickEveryGameHours": "int", "MaxActiveFronts": "int",
"EmoteEveryRounds": "int", "SpawnRateScale": "float",
"EmoteMode": "enum", "PerRoomRefinement": "enum",
"ExcludeZonePatterns": "text", "BuffOverrides.*": "text",
}
m := adminTestModule()
for _, row := range m.configRows() {
if row.Kind != wantKinds[row.Key] {
t.Errorf("%s: kind %q, want %q", row.Key, row.Kind, wantKinds[row.Key])
}
if row.Kind == "enum" && len(row.Options) == 0 {
t.Errorf("%s: enum row without options", row.Key)
}
if row.Kind != "enum" && len(row.Options) != 0 {
t.Errorf("%s: non-enum row carries options %v", row.Key, row.Options)
}
}
if got := strings.Join(configKeyMeta["PerRoomRefinement"].Options, ","); got != "occupied,all,off" {
t.Errorf("refinement options: %q", got)
}
if got := strings.Join(configKeyMeta["EmoteMode"].Options, ","); got != "module,tag-only" {
t.Errorf("emote mode options: %q", got)
}
for key, meta := range configKeyMeta {
if !meta.ReadOnly && meta.Validate == nil {
t.Errorf("writable key %s has no validator", key)
}
}
}
// TestAdminRebuildPublishesOnce guards the single-publish rule for the admin
// rebuild arm: nothing publishes before/inside rebuildGraph (snapshot pointer
// generation as proxy), and the arm's single tail publish carries the
// outcome-derived lastAdminAction.
func TestAdminRebuildPublishesOnce(t *testing.T) {
m := adminTestModule()
m.publishSnapshot()
before := adminSnapshot.Load()
var during *AdminSnapshot
orig := rebuildGraphFn
rebuildGraphFn = func(m *weatherModule) { during = adminSnapshot.Load() } // crawl stub: keep the graph
defer func() { rebuildGraphFn = orig }()
m.applyAdminAction(WeatherAdminAction{Action: "rebuild"})
if during != before {
t.Error("snapshot published before/inside rebuildGraph — attribution would be wrong")
}
after := adminSnapshot.Load()
if after == before {
t.Fatal("rebuild action did not publish a snapshot")
}
if after.LastAction != "graph rebuilt" {
t.Errorf("lastAction = %q", after.LastAction)
}
// Failure path publishes too (rebuildGraph kept/lost the graph; arm reports).
rebuildGraphFn = func(m *weatherModule) { m.graph = nil }
m.applyAdminAction(WeatherAdminAction{Action: "rebuild"})
failed := adminSnapshot.Load()
if failed == after {
t.Fatal("failed rebuild did not publish a snapshot")
}
if failed.LastAction != "graph rebuild failed (see server log)" {
t.Errorf("failure lastAction = %q", failed.LastAction)
}
}
func TestConfigRowsNewKeys(t *testing.T) {
m := adminTestModule()
rowOf := func(key string) AdminConfigRow {
for _, r := range m.configRows() {
if r.Key == key {
return r
}
}
t.Fatalf("row %s missing", key)
return AdminConfigRow{}
}
bo := rowOf("BuffOverrides.*")
if !bo.ReadOnly {
t.Error("BuffOverrides.* row must be read-only")
}
if bo.Badge != "takes effect on reboot" {
t.Errorf("BuffOverrides.* badge: %q", bo.Badge)
}
if bo.Value != "(none)" {
t.Errorf("no overrides configured: value %v, want (none)", bo.Value)
}
m.cfg.BuffOverrides = map[string][]int{"storm": {59002}, "blizzard": {}}
if v := rowOf("BuffOverrides.*").Value; v != "blizzard→[]; storm→[59002]" {
t.Errorf("summary = %v", v)
}
ez := rowOf("ExcludeZonePatterns")
if ez.ReadOnly {
t.Error("ExcludeZonePatterns must stay editable")
}
if ez.Badge != "applies on next graph rebuild" {
t.Errorf("ExcludeZonePatterns badge: %q", ez.Badge)
}
// Slice rendered as a fresh string — snapshot isolation (see configRows).
if ez.Value != "instance_*,ephemeral_*" {
t.Errorf("ExcludeZonePatterns value = %v", ez.Value)
}
}
func TestActionHandlerValidation(t *testing.T) {
m := adminTestModule()
bad := httptest.NewRequest("POST", "/x", strings.NewReader(`{"action":"explode"}`))
if status, success, _ := m.handleAdminAction(bad); status != 400 || success {
t.Errorf("unknown action must 400: %d %v", status, success)
}
missing := httptest.NewRequest("POST", "/x", strings.NewReader(`{"action":"spawn","zone":""}`))
if status, _, _ := m.handleAdminAction(missing); status != 400 {
t.Errorf("spawn without zone must 400: %d", status)
}
}