-
Notifications
You must be signed in to change notification settings - Fork 42
/
engine_test.go
500 lines (442 loc) · 12.7 KB
/
engine_test.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
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
package cardinal_test
import (
"errors"
"strconv"
"testing"
"time"
"github.com/golang/mock/gomock"
"pkg.world.dev/world-engine/assert"
"pkg.world.dev/world-engine/cardinal"
"pkg.world.dev/world-engine/cardinal/router/iterator"
"pkg.world.dev/world-engine/cardinal/router/mocks"
"pkg.world.dev/world-engine/cardinal/txpool"
"pkg.world.dev/world-engine/sign"
)
var _ iterator.Iterator = (*FakeIterator)(nil)
// FakeIterator mimics the behavior of a real transaction iterator for testing purposes.
type FakeIterator struct {
objects []Iterable
}
type Iterable struct {
Batches []*iterator.TxBatch
Tick uint64
Timestamp uint64
}
func NewFakeIterator(collection []Iterable) *FakeIterator {
return &FakeIterator{
objects: collection,
}
}
// Each simulates iterating over transactions based on the provided ranges.
// It directly invokes the provided function with mock data for testing.
func (f *FakeIterator) Each(fn func(batch []*iterator.TxBatch, tick, timestamp uint64) error, _ ...uint64) error {
for _, val := range f.objects {
// Invoke the callback function with the current batch, tick, and timestamp.
if err := fn(val.Batches, val.Tick, val.Timestamp); err != nil {
return err
}
}
return nil
}
func TestCanWaitForNextTick(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
startTickCh := tf.StartTickCh
doneTickCh := tf.DoneTickCh
// Make sure the game can tick
tf.StartWorld()
tf.DoTick()
waitForNextTickDone := make(chan struct{})
go func() {
for i := 0; i < 10; i++ {
success := world.WaitForNextTick()
assert.Check(t, success)
}
close(waitForNextTickDone)
}()
for {
select {
case startTickCh <- time.Now():
<-doneTickCh
case <-waitForNextTickDone:
// The above goroutine successfully waited multiple times
return
}
}
}
func TestWaitForNextTickReturnsFalseWhenEngineIsShutDown(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
startTickCh := tf.StartTickCh
doneTickCh := tf.DoneTickCh
// Make sure the game can tick
tf.StartWorld()
tf.DoTick()
waitForNextTickDone := make(chan struct{})
go func() {
// continually spin here waiting for next tick. One of these must fail before
// the test times out for this test to pass
for world.WaitForNextTick() {
}
close(waitForNextTickDone)
}()
// Shutdown the engine at some point in the near future
time.AfterFunc(
100*time.Millisecond, func() {
world.Shutdown()
},
)
// testTimeout will cause the test to fail if we have to wait too long for a WaitForNextTick failure
testTimeout := time.After(5 * time.Second)
for {
select {
case startTickCh <- time.Now():
time.Sleep(10 * time.Millisecond)
<-doneTickCh
case <-testTimeout:
assert.Check(t, false, "test timeout")
return
case <-waitForNextTickDone:
// WaitForNextTick failed, meaning this test was successful
return
}
}
}
func TestCannotWaitForNextTickAfterEngineIsShutDown(t *testing.T) {
type FooIn struct {
X uint32
}
type FooOut struct {
Y string
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "foo"
assert.NilError(t,
cardinal.RegisterMessage[FooIn, FooOut](world, msgName, cardinal.WithMsgEVMSupport[FooIn, FooOut]()))
fooTx, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
var returnVal FooOut
var returnErr error
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
return cardinal.EachMessage[FooIn, FooOut](
wCtx, func(cardinal.TxData[FooIn]) (FooOut, error) {
return returnVal, returnErr
},
)
},
)
assert.NilError(t, err)
tf.StartWorld()
// add tx to queue
evmTxHash := "0xFooBar"
world.AddEVMTransaction(fooTx.ID(), FooIn{X: 32}, &sign.Transaction{PersonaTag: "foo"}, evmTxHash)
tf.StartWorld()
// let's check against a system that returns a result and no error
returnVal = FooOut{Y: "hi"}
returnErr = nil
tf.DoTick()
evmTxReceipt, ok := world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, true)
assert.Check(t, len(evmTxReceipt.ABIResult) > 0)
assert.Equal(t, evmTxReceipt.EVMTxHash, evmTxHash)
assert.Equal(t, len(evmTxReceipt.Errs), 0)
// shouldn't be able to consume it again.
_, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, false)
// lets check against a system that returns an error
returnVal = FooOut{}
returnErr = errors.New("omg error")
world.AddEVMTransaction(fooTx.ID(), FooIn{X: 32}, &sign.Transaction{PersonaTag: "foo"}, evmTxHash)
tf.DoTick()
evmTxReceipt, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, true)
assert.Equal(t, len(evmTxReceipt.ABIResult), 0)
assert.Equal(t, evmTxReceipt.EVMTxHash, evmTxHash)
assert.Equal(t, len(evmTxReceipt.Errs), 1)
// shouldn't be able to consume it again.
_, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, false)
}
func TestEVMTxConsume(t *testing.T) {
type FooIn struct {
X uint32
}
type FooOut struct {
Y string
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "foo"
err := cardinal.RegisterMessage[FooIn, FooOut](world, msgName, cardinal.WithMsgEVMSupport[FooIn, FooOut]())
assert.NilError(t, err)
var returnVal FooOut
var returnErr error
err = cardinal.RegisterSystems(world,
func(wCtx cardinal.WorldContext) error {
return cardinal.EachMessage[FooIn, FooOut](
wCtx, func(cardinal.TxData[FooIn]) (FooOut, error) {
return returnVal, returnErr
},
)
},
)
assert.NilError(t, err)
tf.StartWorld()
fooTx, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
// add tx to queue
evmTxHash := "0xFooBar"
world.AddEVMTransaction(fooTx.ID(), FooIn{X: 32}, &sign.Transaction{PersonaTag: "foo"}, evmTxHash)
// let's check against a system that returns a result and no error
returnVal = FooOut{Y: "hi"}
returnErr = nil
tf.DoTick()
evmTxReceipt, ok := world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, true)
assert.Check(t, len(evmTxReceipt.ABIResult) > 0)
assert.Equal(t, evmTxReceipt.EVMTxHash, evmTxHash)
assert.Equal(t, len(evmTxReceipt.Errs), 0)
// shouldn't be able to consume it again.
_, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, false)
// lets check against a system that returns an error
returnVal = FooOut{}
returnErr = errors.New("omg error")
world.AddEVMTransaction(fooTx.ID(), FooIn{X: 32}, &sign.Transaction{PersonaTag: "foo"}, evmTxHash)
tf.DoTick()
evmTxReceipt, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, true)
assert.Equal(t, len(evmTxReceipt.ABIResult), 0)
assert.Equal(t, evmTxReceipt.EVMTxHash, evmTxHash)
assert.Equal(t, len(evmTxReceipt.Errs), 1)
// shouldn't be able to consume it again.
_, ok = world.GetEVMMsgReceipt(evmTxHash)
assert.Equal(t, ok, false)
}
func TestAddSystems(t *testing.T) {
count := 0
sys1 := func(cardinal.WorldContext) error {
count++
return nil
}
sys2 := func(cardinal.WorldContext) error {
count++
return nil
}
sys3 := func(cardinal.WorldContext) error {
count++
return nil
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
err := cardinal.RegisterSystems(world, sys1, sys2, sys3)
assert.NilError(t, err)
tf.StartWorld()
assert.NilError(t, err)
tf.DoTick()
assert.Equal(t, count, 3)
}
func TestSystemExecutionOrder(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
order := make([]int, 0, 3)
err := cardinal.RegisterSystems(
world,
func(cardinal.WorldContext) error {
order = append(order, 1)
return nil
}, func(cardinal.WorldContext) error {
order = append(order, 2)
return nil
}, func(cardinal.WorldContext) error {
order = append(order, 3)
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
assert.NilError(t, err)
tf.DoTick()
expectedOrder := []int{1, 2, 3}
for i, elem := range order {
assert.Equal(t, elem, expectedOrder[i])
}
}
func TestSetNamespace(t *testing.T) {
namespace := "test"
t.Setenv("CARDINAL_NAMESPACE", namespace)
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.Equal(t, world.Namespace(), namespace)
}
func TestWithoutRegistration(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
wCtx := cardinal.NewWorldContext(world)
assert.Panics(t, func() { _, _ = cardinal.Create(wCtx, EnergyComponent{}, OwnableComponent{}) })
assert.Panics(t, func() {
_ = cardinal.UpdateComponent[EnergyComponent](
wCtx, 0, func(component *EnergyComponent) *EnergyComponent {
component.Amt += 50
return component
},
)
})
assert.Panics(t, func() {
_ = cardinal.SetComponent[EnergyComponent](
wCtx, 0, &EnergyComponent{
Amt: 0,
Cap: 0,
},
)
})
assert.NilError(t, cardinal.RegisterComponent[EnergyComponent](world))
assert.NilError(t, cardinal.RegisterComponent[OwnableComponent](world))
tf.StartWorld()
id, err := cardinal.Create(wCtx, EnergyComponent{}, OwnableComponent{})
assert.NilError(t, err)
err = cardinal.UpdateComponent[EnergyComponent](
wCtx, id, func(component *EnergyComponent) *EnergyComponent {
component.Amt += 50
return component
},
)
assert.NilError(t, err)
err = cardinal.SetComponent[EnergyComponent](
wCtx, id, &EnergyComponent{
Amt: 0,
Cap: 0,
},
)
assert.NilError(t, err)
}
func TestTransactionsSentToRouterAfterTick(t *testing.T) {
ctrl := gomock.NewController(t)
rtr := mocks.NewMockRouter(ctrl)
tf := cardinal.NewTestFixture(t, nil, cardinal.WithCustomRouter(rtr))
world := tf.World
type fooMsg struct {
Bar string
}
type fooMsgRes struct{}
msgName := "foo"
err := cardinal.RegisterMessage[fooMsg, fooMsgRes](world, msgName, cardinal.WithMsgEVMSupport[fooMsg, fooMsgRes]())
assert.NilError(t, err)
evmTxHash := "0x12345"
msg := fooMsg{Bar: "hello"}
tx := &sign.Transaction{PersonaTag: "ty"}
fooMessage, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
_, txHash := world.AddEVMTransaction(fooMessage.ID(), msg, tx, evmTxHash)
rtr.
EXPECT().
SubmitTxBlob(
gomock.Any(),
txpool.TxMap{
fooMessage.ID(): {
{
MsgID: fooMessage.ID(),
Msg: msg,
TxHash: txHash,
Tx: tx,
EVMSourceTxHash: evmTxHash,
},
},
},
world.CurrentTick(),
gomock.Any(),
).
Return(nil).
Times(1)
rtr.EXPECT().Start().Times(1)
rtr.EXPECT().RegisterGameShard(gomock.Any()).Times(1)
tf.StartWorld()
tf.DoTick()
// Expect that ticks with no transactions are also submitted
rtr.
EXPECT().
SubmitTxBlob(
gomock.Any(),
txpool.TxMap{},
world.CurrentTick(),
gomock.Any(),
).
Return(nil).
Times(1)
rtr.EXPECT().Start().AnyTimes()
tf.DoTick()
}
// setEnvToCardinalRollupMode sets a bunch of environment variables that are required
// for Cardinal to be able to run in rollup node.
func setEnvToCardinalRollupMode(t *testing.T) {
t.Setenv("CARDINAL_ROLLUP_ENABLED", strconv.FormatBool(true))
t.Setenv("BASE_SHARD_ROUTER_KEY", "77cf59146831dbd94bd19dd4b259b268ee07a7c1fdba67e92b0f7c1cfdfb7a9b")
}
func TestRecoverFromChain(t *testing.T) {
ctrl := gomock.NewController(t)
rtr := mocks.NewMockRouter(ctrl)
// Set CARDINAL_ROLLUP_ENABLED=true so that recoverFromChain() is called
setEnvToCardinalRollupMode(t)
rtr.EXPECT().Start().Times(1)
rtr.EXPECT().RegisterGameShard(gomock.Any()).Times(1)
tf := cardinal.NewTestFixture(t, nil, cardinal.WithCustomRouter(rtr))
world := tf.World
type fooMsg struct{ I int }
type fooMsgRes struct{}
fooMsgName := "foo"
assert.NilError(t, cardinal.RegisterMessage[fooMsg, fooMsgRes](world, fooMsgName))
fooMessages := 0
err := cardinal.RegisterSystems(world, func(engineContext cardinal.WorldContext) error {
return cardinal.EachMessage[fooMsg, fooMsgRes](engineContext, func(cardinal.TxData[fooMsg]) (fooMsgRes, error) {
fooMessages++
return fooMsgRes{}, nil
})
})
assert.NilError(t, err)
fooMessage, ok := world.GetMessageByFullName("game." + fooMsgName)
assert.True(t, ok)
fakeBatches := []Iterable{
{
Batches: []*iterator.TxBatch{
{
MsgID: fooMessage.ID(),
MsgValue: fooMsg{I: 1},
Tx: &sign.Transaction{},
},
{
MsgID: fooMessage.ID(),
MsgValue: fooMsg{I: 2},
Tx: &sign.Transaction{},
},
},
Tick: 1,
Timestamp: uint64(sign.TimestampNow()),
},
{
Batches: []*iterator.TxBatch{
{
MsgID: fooMessage.ID(),
MsgValue: fooMsg{I: 3},
Tx: &sign.Transaction{},
},
{
MsgID: fooMessage.ID(),
MsgValue: fooMsg{I: 4},
Tx: &sign.Transaction{},
},
},
Tick: 15,
Timestamp: uint64(sign.TimestampNow()),
},
}
fakeIterator := NewFakeIterator(fakeBatches)
rtr.EXPECT().TransactionIterator().Return(fakeIterator).Times(1)
tf.StartWorld()
// fooMessages should have been incremented 4 times for each of the 4 txs
assert.Equal(t, fooMessages, 4)
// World should be ready for tick 16
assert.Equal(t, world.CurrentTick(), uint64(16))
}