aboutsummaryrefslogtreecommitdiff
path: root/internal/world/hardening_room_id_mismatch_test.go
blob: 1ac171149255794e1da84cfd388ada3f9487ba90 (plain)
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
package world

import (
	"bytes"
	"log"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// Regression: a room file whose declared id: disagrees with its numeric
// filename was silently loaded under the filename with no diagnostic.
// World.LoadRoom must warn, because room identity comes from the filename.

func writeRoomFile(t *testing.T, dir, name, body string) {
	t.Helper()
	path := filepath.Join(dir, "rooms", name)
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
		t.Fatal(err)
	}
}

func captureRoomLog(t *testing.T, fn func()) string {
	t.Helper()
	var buf bytes.Buffer
	old := log.Writer()
	log.SetOutput(&buf)
	defer log.SetOutput(old)
	fn()
	return buf.String()
}

func TestWorldWarnsOnDeclaredRoomIDMismatch(t *testing.T) {
	dir := t.TempDir()
	writeRoomFile(t, dir, "1.yaml", "id: 2\nname: Wrong Id\n")
	w := New(dir)

	out := captureRoomLog(t, func() {
		room, err := w.LoadRoom(1)
		if err != nil {
			t.Fatalf("load room: %v", err)
		}
		if room.ID != 1 {
			t.Fatalf("filename must win: room.ID = %d, want 1", room.ID)
		}
	})
	if !strings.Contains(out, "declares id") {
		t.Fatalf("expected a room id-mismatch warning, got log %q", out)
	}
}

func TestWorldDoesNotWarnWhenRoomIDMatchesOrAbsent(t *testing.T) {
	dir := t.TempDir()
	writeRoomFile(t, dir, "1.yaml", "id: 1\nname: Match\n")
	writeRoomFile(t, dir, "2.yaml", "name: Absent\n")
	w := New(dir)

	out := captureRoomLog(t, func() {
		if _, err := w.LoadRoom(1); err != nil {
			t.Fatal(err)
		}
		if _, err := w.LoadRoom(2); err != nil {
			t.Fatal(err)
		}
	})
	if strings.Contains(out, "declares id") {
		t.Fatalf("unexpected room id-mismatch warning: %q", out)
	}
}