-
Notifications
You must be signed in to change notification settings - Fork 42
/
world_fixture.go
271 lines (232 loc) · 7.62 KB
/
world_fixture.go
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
package cardinal
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/rotisserie/eris"
"github.com/spf13/viper"
"gotest.tools/v3/assert"
"pkg.world.dev/world-engine/cardinal/persona/msg"
"pkg.world.dev/world-engine/cardinal/types"
"pkg.world.dev/world-engine/sign"
)
// TestFixture is a helper struct that manages a cardinal.World instance. It will automatically clean up its resources
// at the end of the test.
type TestFixture struct {
testing.TB
// Base url is something like "localhost:5050". You must attach http:// or ws:// as well as a resource path
BaseURL string
World *World
Redis *miniredis.Miniredis
StartTickCh chan time.Time
DoneTickCh chan uint64
doCleanup func()
startOnce *sync.Once
}
// NewTestFixture creates a test fixture with user defined port for Cardinal integration tests.
func NewTestFixture(t testing.TB, redis *miniredis.Miniredis, opts ...WorldOption) *TestFixture {
if redis == nil {
redis = miniredis.RunT(t)
}
ports, err := findOpenPorts(2) //nolint:gomnd
assert.NilError(t, err)
cardinalPort := ports[0]
evmPort := ports[1]
t.Setenv("BASE_SHARD_SEQUENCER_ADDRESS", "localhost:"+evmPort)
t.Setenv("CARDINAL_LOG_PRETTY", "true")
t.Setenv("REDIS_ADDRESS", redis.Addr())
startTickCh, doneTickCh := make(chan time.Time), make(chan uint64)
defaultOpts := []WorldOption{
WithTickChannel(startTickCh),
WithTickDoneChannel(doneTickCh),
WithPort(cardinalPort),
WithMockJobQueue(),
}
// Default options go first so that any user supplied options overwrite the defaults.
world, err := NewWorld(append(defaultOpts, opts...)...)
assert.NilError(t, err)
return &TestFixture{
TB: t,
BaseURL: "localhost:" + cardinalPort,
World: world,
Redis: redis,
StartTickCh: startTickCh,
DoneTickCh: doneTickCh,
startOnce: &sync.Once{},
// Only register this method with t.Cleanup if the game server is actually started
doCleanup: func() {
viper.Reset()
// Optionally, you can also clear environment variables if needed
for _, key := range viper.AllKeys() {
err := os.Unsetenv(key)
if err != nil {
t.Errorf("failed to unset env var %s: %v", key, err)
}
}
// First, make sure completed ticks will never be blocked
go func() {
for range doneTickCh { //nolint:revive // This pattern drains the channel until closed
}
}()
// Next, shut down the world
world.Shutdown()
// The world is shut down; No more ticks will be started
close(startTickCh)
},
}
}
// StartWorld starts the game world and registers a cleanup function that will shut down
// the cardinal World at the end of the test. Components/Systems/Queries, etc should
// be registered before calling this function.
func (t *TestFixture) StartWorld() {
t.startOnce.Do(func() {
timeout := time.After(5 * time.Second) //nolint:gomnd // fine for now.
startupError := make(chan error)
go func() {
// StartGame is meant to block forever, so any return value will be non-nil and cause for concern.
// Also, calling t.Fatal from a non-main thread only reports a failure once the test on the main thread has
// completed. By sending this error out on a channel we can fail the test right away (assuming doTick
// has been called from the main thread).
startupError <- t.World.StartGame()
}()
for !t.World.IsGameRunning() {
select {
case err := <-startupError:
t.Fatalf("startup error: %v", err)
case <-timeout:
t.Fatal("timeout while waiting for game to start")
default:
time.Sleep(10 * time.Millisecond) //nolint:gomnd // its for testing its ok.
}
}
t.Cleanup(t.doCleanup)
})
}
// DoTick executes one game tick and blocks until the tick is complete. StartWorld is automatically called if it was
// not called before the first tick.
func (t *TestFixture) DoTick() {
t.StartWorld()
t.StartTickCh <- time.Now()
<-t.DoneTickCh
}
func (t *TestFixture) httpURL(path string) string {
return fmt.Sprintf("http://%s/%s", t.BaseURL, path)
}
// Post executes a http POST request to this TextFixture's cardinal server.
func (t *TestFixture) Post(path string, payload any) *http.Response {
bz, err := json.Marshal(payload)
assert.NilError(t, err)
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodPost,
t.httpURL(strings.Trim(path, "/")),
bytes.NewReader(bz),
)
assert.NilError(t, err)
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
assert.NilError(t, err)
return resp
}
// Get executes a http GET request to this TestFixture's cardinal server.
func (t *TestFixture) Get(path string) *http.Response {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, t.httpURL(strings.Trim(path, "/")),
nil)
assert.NilError(t, err)
resp, err := http.DefaultClient.Do(req)
assert.NilError(t, err)
return resp
}
func (t *TestFixture) AddTransaction(txID types.MessageID, tx any, sigs ...*sign.Transaction) types.TxHash {
sig := &sign.Transaction{}
if len(sigs) > 0 {
sig = sigs[0]
}
_, id := t.World.AddTransaction(txID, tx, sig)
return id
}
func (t *TestFixture) CreatePersona(personaTag, signerAddr string) {
personaMsg := msg.CreatePersona{
PersonaTag: personaTag,
SignerAddress: signerAddr,
}
createPersonaMsg, exists := t.World.GetMessageByFullName("persona." + msg.CreatePersonaMessageName)
assert.Check(
t,
exists,
"message with name %q not registered in World", msg.CreatePersonaMessageName,
)
t.AddTransaction(createPersonaMsg.ID(), personaMsg, &sign.Transaction{})
t.DoTick()
}
// findOpenPorts finds a set of open ports and returns them as a slice of strings.
// It is guaranteed that the returned slice will have the amount of ports requested and that there is no duplicate
// ports in the slice.
func findOpenPorts(amount int) ([]string, error) {
ports := make([]string, 0, amount)
// Try to find open ports until we find the target amount or we run out of retries
for i := 0; i < amount; i++ {
var found bool
// Try to find a random port, retying if it turns out to be a duplicate in list of ports up to 10 times
for retries := 10; retries > 0; retries-- {
port, err := findOpenPort()
if err != nil {
continue
}
// Check for duplicate ports
for _, existingPort := range ports {
if port == existingPort {
continue
}
}
// Add the port to the list and break out of the inner loop
ports = append(ports, port)
found = true
break
}
if !found {
return nil, eris.New("failed to find open ports after retries")
}
}
return ports, nil
}
// findOpenPort finds an open port and returns it as a string.
// If you need to find multiple ports, use findOpenPorts to make sure that the ports are unique.
func findOpenPort() (string, error) {
findFn := func() (string, error) {
// Try to get a random port using the wildcard 0 port
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return "", eris.Wrap(err, "failed to initialize listener")
}
// Get the autoamtically assigned port number from the listener
tcpAddr, err := net.ResolveTCPAddr(l.Addr().Network(), l.Addr().String())
if err != nil {
return "", eris.Wrap(err, "failed to resolve address")
}
// Close the listener when the function returns
err = l.Close()
if err != nil {
return "", eris.Wrap(err, "failed to close listener")
}
return strconv.Itoa(tcpAddr.Port), nil
}
for retries := 10; retries > 0; retries-- {
port, err := findFn()
if err == nil {
return port, nil
}
time.Sleep(10 * time.Millisecond) //nolint:gomnd // it's fine.
}
return "", eris.New("failed to find an open port")
}