forked from Argus-Labs/world-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cardinal_test.go
871 lines (767 loc) · 24.2 KB
/
cardinal_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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
package cardinal_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"strconv"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/crypto"
"github.com/fasthttp/websocket"
"github.com/golang/mock/gomock"
"pkg.world.dev/world-engine/assert"
"pkg.world.dev/world-engine/cardinal"
"pkg.world.dev/world-engine/cardinal/router/mocks"
"pkg.world.dev/world-engine/cardinal/search/filter"
"pkg.world.dev/world-engine/cardinal/testutils"
"pkg.world.dev/world-engine/cardinal/types"
"pkg.world.dev/world-engine/sign"
)
type AddHealthToEntityTx struct {
TargetID types.EntityID
Amount int
}
type AddHealthToEntityResult struct{}
type Rawbodytx struct {
PersonaTag string `json:"personaTag"`
SignerAddress string `json:"signerAddress"`
}
type Foo struct{}
func (Foo) Name() string { return "foo" }
type Bar struct{}
func (Bar) Name() string { return "bar" }
type Health struct {
Value int
}
func (Health) Name() string { return "health" }
func TestForEachTransaction(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
type SomeMsgRequest struct {
GenerateError bool
}
type SomeMsgResponse struct {
Successful bool
}
someMsgName := "some_msg"
assert.NilError(t, cardinal.RegisterMessage[SomeMsgRequest, SomeMsgResponse](world, someMsgName))
err := cardinal.RegisterSystems(world, func(wCtx cardinal.WorldContext) error {
return cardinal.EachMessage[SomeMsgRequest, SomeMsgResponse](wCtx,
func(t cardinal.TxData[SomeMsgRequest]) (result SomeMsgResponse, err error) {
if t.Msg.GenerateError {
return result, errors.New("some error")
}
return SomeMsgResponse{
Successful: true,
}, nil
})
})
assert.NilError(t, err)
tf.StartWorld()
// Add 10 transactions to the tx pool and keep track of the hashes that we just cardinal.Created
knownTxHashes := map[types.TxHash]SomeMsgRequest{}
for i := 0; i < 10; i++ {
someMsg, ok := world.GetMessageByFullName("game." + someMsgName)
assert.True(t, ok)
req := SomeMsgRequest{GenerateError: i%2 == 0}
txHash := tf.AddTransaction(someMsg.ID(), req, testutils.UniqueSignature())
knownTxHashes[txHash] = req
}
// Perform a engine tick
tf.DoTick()
// Verify the receipts for the previous tick are what we expect
receipts, err := world.GetTransactionReceiptsForTick(world.CurrentTick() - 1)
assert.NilError(t, err)
assert.Equal(t, len(knownTxHashes), len(receipts))
for _, receipt := range receipts {
request, ok := knownTxHashes[receipt.TxHash]
assert.Check(t, ok)
if request.GenerateError {
assert.Check(t, len(receipt.Errs) > 0)
} else {
assert.Equal(t, 0, len(receipt.Errs))
assert.Equal(t, receipt.Result.(SomeMsgResponse), SomeMsgResponse{Successful: true})
}
}
}
type CounterComponent struct {
Count int
}
func (CounterComponent) Name() string {
return "count"
}
type ScoreComponent struct {
Score int
}
func (ScoreComponent) Name() string {
return "score"
}
type ModifyScoreMsg struct {
PlayerID types.EntityID
Amount int
}
type EmptyMsgResult struct{}
func TestSystemsAreExecutedDuringGameTick(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.NilError(t, cardinal.RegisterComponent[CounterComponent](world))
wCtx := cardinal.NewWorldContext(world)
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
search := cardinal.NewSearch().Entity(filter.Exact(filter.Component[CounterComponent]()))
id := search.MustFirst(wCtx)
return cardinal.UpdateComponent[CounterComponent](
wCtx, id, func(c *CounterComponent) *CounterComponent {
c.Count++
return c
},
)
},
)
assert.NilError(t, err)
tf.StartWorld()
id, err := cardinal.Create(wCtx, CounterComponent{})
assert.NilError(t, err)
for i := 0; i < 10; i++ {
tf.DoTick()
}
c, err := cardinal.GetComponent[CounterComponent](wCtx, id)
assert.NilError(t, err)
assert.Equal(t, 10, c.Count)
}
func TestTransactionAreAppliedToSomeEntities(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.NilError(t, cardinal.RegisterComponent[ScoreComponent](world))
assert.NilError(t, cardinal.RegisterMessage[*ModifyScoreMsg, *EmptyMsgResult](world, "modify_score"))
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
return cardinal.EachMessage[*ModifyScoreMsg, *EmptyMsgResult](wCtx,
func(msData cardinal.TxData[*ModifyScoreMsg]) (*EmptyMsgResult, error) {
ms := msData.Msg
err := cardinal.UpdateComponent[ScoreComponent](
wCtx, ms.PlayerID, func(s *ScoreComponent) *ScoreComponent {
s.Score += ms.Amount
return s
},
)
assert.Check(t, err == nil)
return &EmptyMsgResult{}, nil
})
},
)
assert.NilError(t, err)
tf.StartWorld()
wCtx := cardinal.NewWorldContext(world)
ids, err := cardinal.CreateMany(wCtx, 100, ScoreComponent{})
assert.NilError(t, err)
// Entities at index 5, 10 and 50 will be updated with some values
modifyScoreMsg, err := testutils.GetMessage[*ModifyScoreMsg, *EmptyMsgResult](tf.World)
assert.NilError(t, err)
tf.AddTransaction(
modifyScoreMsg.ID(), &ModifyScoreMsg{
PlayerID: ids[5],
Amount: 105,
},
)
tf.AddTransaction(
modifyScoreMsg.ID(), &ModifyScoreMsg{
PlayerID: ids[10],
Amount: 110,
},
)
tf.AddTransaction(
modifyScoreMsg.ID(), &ModifyScoreMsg{
PlayerID: ids[50],
Amount: 150,
},
)
tf.DoTick()
for i, id := range ids {
wantScore := 0
switch i {
case 5:
wantScore = 105
case 10:
wantScore = 110
case 50:
wantScore = 150
}
s, err := cardinal.GetComponent[ScoreComponent](wCtx, id)
assert.NilError(t, err)
assert.Equal(t, wantScore, s.Score)
}
}
// TestAddToPoolDuringTickDoesNotTimeout verifies that we can add a transaction to the transaction
// pool during a game tick, and the call does not block.
func TestAddToPoolDuringTickDoesNotTimeout(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "modify_Score"
assert.NilError(t, cardinal.RegisterMessage[*ModifyScoreMsg, *EmptyMsgResult](world, msgName))
inSystemCh := make(chan struct{})
defer func() { close(inSystemCh) }()
// This system will block forever. This will give us a never-ending game tick that we can use
// to verify that the addition of more transactions doesn't block.
err := cardinal.RegisterSystems(
world,
func(cardinal.WorldContext) error {
<-inSystemCh
<-inSystemCh
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
modScore, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
tf.AddTransaction(modScore.ID(), &ModifyScoreMsg{})
// Start a tick in the background.
go func() {
tf.DoTick()
}()
// Make sure we're actually in the system.
inSystemCh <- struct{}{}
// Make sure we can call addTransaction again in a reasonable amount of time
timeout := time.After(500 * time.Millisecond)
doneWithAddTx := make(chan struct{})
go func() {
tf.AddTransaction(modScore.ID(), &ModifyScoreMsg{})
doneWithAddTx <- struct{}{}
}()
select {
case <-doneWithAddTx:
// happy path
case <-timeout:
t.Fatal("timeout while trying to addTransaction")
}
// release the system
inSystemCh <- struct{}{}
// Second tick to make sure all transaction processed before shutdown
tickDone := make(chan struct{})
go func() {
tf.DoTick()
tickDone <- struct{}{}
}()
inSystemCh <- struct{}{}
inSystemCh <- struct{}{}
// wait for tick done to prevent panic on shutdown
<-tickDone
}
// TestTransactionsAreExecutedAtNextTick verifies that while a game tick is taking place, new transactions
// are added to some pool that is not processed until the NEXT tick.
func TestTransactionsAreExecutedAtNextTick(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "modify_score"
assert.NilError(t, cardinal.RegisterMessage[*ModifyScoreMsg, *EmptyMsgResult](world, msgName))
tickStart := tf.StartTickCh
tickDone := tf.DoneTickCh
modScoreCountCh := make(chan int)
// Create two system that report how many instances of the ModifyScoreMsg exist in the
// transaction pool. These counts should be the same for each tick. modScoreCountCh is an unbuffered channel
// so these systems will block while writing to modScoreCountCh. This allows the test to ensure that we can run
// commands mid-tick.
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
modScoreMsg, err := testutils.GetMessage[*ModifyScoreMsg, *EmptyMsgResult](world)
if err != nil {
return err
}
modScores := modScoreMsg.In(wCtx)
modScoreCountCh <- len(modScores)
return nil
},
)
assert.NilError(t, err)
err = cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
modScoreMsg, err := testutils.GetMessage[*ModifyScoreMsg, *EmptyMsgResult](world)
if err != nil {
return err
}
modScores := modScoreMsg.In(wCtx)
modScoreCountCh <- len(modScores)
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
modScoreMsg, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
tf.AddTransaction(modScoreMsg.ID(), &ModifyScoreMsg{})
// Start the game tick. The tick will block while waiting to write to modScoreCountCh
tickStart <- time.Now()
// In the first system, we should see 1 modify score transaction
count := <-modScoreCountCh
assert.Equal(t, 1, count)
// Add two transactions mid-tick.
tf.AddTransaction(modScoreMsg.ID(), &ModifyScoreMsg{})
tf.AddTransaction(modScoreMsg.ID(), &ModifyScoreMsg{})
// The tick is still not over, so we should still only see 1 modify score transaction
count = <-modScoreCountCh
assert.Equal(t, 1, count)
// Block until the tick has completed.
<-tickDone
// Start the next tick.
tickStart <- time.Now()
// This second tick should find 2 ModifyScore transactions. They were added in the middle of the previous tick.
count = <-modScoreCountCh
assert.Equal(t, 2, count)
count = <-modScoreCountCh
assert.Equal(t, 2, count)
// Block until the tick has completed.
<-tickDone
// In this final tick, we should see no modify score transactions
tickStart <- time.Now()
count = <-modScoreCountCh
assert.Equal(t, 0, count)
count = <-modScoreCountCh
assert.Equal(t, 0, count)
<-tickDone
}
func TestCannotRegisterDuplicateTransaction(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.NilError(t, cardinal.RegisterMessage[ModifyScoreMsg, EmptyMsgResult](world, "modify_score"))
assert.IsError(t, cardinal.RegisterMessage[ModifyScoreMsg, EmptyMsgResult](world, "modify_score"))
}
func TestCannotCallRegisterTransactionsMultipleTimes(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.NilError(t, cardinal.RegisterMessage[ModifyScoreMsg, EmptyMsgResult](world, "modify_score"))
assert.Check(t, nil != cardinal.RegisterMessage[ModifyScoreMsg, EmptyMsgResult](world, "modify_score"))
}
func TestCannotHaveDuplicateTransactionNames(t *testing.T) {
type SomeMsg struct {
X, Y, Z int
}
type OtherMsg struct {
Alpha, Beta string
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
err := cardinal.RegisterMessage[SomeMsg, EmptyMsgResult](world, "name_match")
assert.NilError(t, err)
err = cardinal.RegisterMessage[OtherMsg, EmptyMsgResult](world, "name_match")
assert.IsError(t, err)
}
func TestCanGetTransactionErrorsAndResults(t *testing.T) {
type MoveMsg struct {
DeltaX, DeltaY int
}
type MoveMsgResult struct {
EndX, EndY int
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
// Each transaction now needs an input and an output
msgName := "move"
assert.NilError(t, cardinal.RegisterMessage[MoveMsg, MoveMsgResult](world, msgName))
wantFirstError := errors.New("this is a transaction error")
wantSecondError := errors.New("another transaction error")
wantDeltaX, wantDeltaY := 99, 100
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
// This new In function returns a triplet of information:
// 1) The transaction input
// 2) An EntityID that uniquely identifies this specific transaction
// 3) The signature
// This function would replace both "In" and "TxsAndSigsIn"
moveMsg, err := testutils.GetMessage[MoveMsg, MoveMsgResult](world)
assert.NilError(t, err)
txData := moveMsg.In(wCtx)
assert.Equal(t, 1, len(txData), "expected 1 move transaction")
tx := txData[0]
// The input for the transaction is found at tx.Val
assert.Equal(t, wantDeltaX, tx.Msg.DeltaX)
assert.Equal(t, wantDeltaY, tx.Msg.DeltaY)
// AddError will associate an error with the tx.TxHash. Multiple errors can be
// associated with a transaction.
moveMsg.AddError(wCtx, tx.Hash, wantFirstError)
moveMsg.AddError(wCtx, tx.Hash, wantSecondError)
// SetResult sets the output for the transaction. Only one output can be set
// for a tx.TxHash (the last assigned result will clobber other results)
moveMsg.SetResult(wCtx, tx.Hash, MoveMsgResult{42, 42})
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
moveMsg, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
_ = tf.AddTransaction(moveMsg.ID(), MoveMsg{99, 100})
// Tick the game so the transaction is processed
tf.DoTick()
tick := world.CurrentTick() - 1
receipts, err := world.GetTransactionReceiptsForTick(tick)
assert.NilError(t, err)
assert.Equal(t, 1, len(receipts))
r := receipts[0]
assert.Equal(t, 2, len(r.Errs))
assert.ErrorIs(t, wantFirstError, r.Errs[0])
assert.ErrorIs(t, wantSecondError, r.Errs[1])
got, ok := r.Result.(MoveMsgResult)
assert.Check(t, ok)
assert.Equal(t, MoveMsgResult{42, 42}, got)
}
func TestSystemCanFindErrorsFromEarlierSystem(t *testing.T) {
type MsgIn struct {
Number int
}
type MsgOut struct {
Number int
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "number"
assert.NilError(t, cardinal.RegisterMessage[MsgIn, MsgOut](world, msgName))
wantErr := errors.New("some transaction error")
systemCalls := 0
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
systemCalls++
numTx, err := testutils.GetMessage[MsgIn, MsgOut](world)
if err != nil {
return err
}
txs := numTx.In(wCtx)
assert.Equal(t, 1, len(txs))
hash := txs[0].Hash
_, _, ok := numTx.GetReceipt(wCtx, hash)
assert.Check(t, !ok)
numTx.AddError(wCtx, hash, wantErr)
return nil
},
)
assert.NilError(t, err)
err = cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
systemCalls++
numTx, err := testutils.GetMessage[MsgIn, MsgOut](world)
if err != nil {
return err
}
txs := numTx.In(wCtx)
assert.Equal(t, 1, len(txs))
hash := txs[0].Hash
_, errs, ok := numTx.GetReceipt(wCtx, hash)
assert.Check(t, ok)
assert.Equal(t, 1, len(errs))
assert.ErrorIs(t, wantErr, errs[0])
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
numTx, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
_ = tf.AddTransaction(numTx.ID(), MsgIn{100})
tf.DoTick()
assert.Equal(t, 2, systemCalls)
}
func TestSystemCanClobberTransactionResult(t *testing.T) {
type MsgIn struct {
Number int
}
type MsgOut struct {
Number int
}
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
msgName := "number"
assert.NilError(t, cardinal.RegisterMessage[MsgIn, MsgOut](world, msgName))
systemCalls := 0
firstResult := MsgOut{1234}
secondResult := MsgOut{5678}
err := cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
systemCalls++
numTx, err := testutils.GetMessage[MsgIn, MsgOut](world)
assert.NilError(t, err)
txs := numTx.In(wCtx)
assert.Equal(t, 1, len(txs))
hash := txs[0].Hash
_, _, ok := numTx.GetReceipt(wCtx, hash)
assert.Check(t, !ok)
numTx.SetResult(wCtx, hash, firstResult)
return nil
},
)
assert.NilError(t, err)
err = cardinal.RegisterSystems(
world,
func(wCtx cardinal.WorldContext) error {
systemCalls++
numTx, err := testutils.GetMessage[MsgIn, MsgOut](world)
if err != nil {
return err
}
txs := numTx.In(wCtx)
assert.Equal(t, 1, len(txs))
hash := txs[0].Hash
out, errs, ok := numTx.GetReceipt(wCtx, hash)
assert.Check(t, ok)
assert.Equal(t, 0, len(errs))
assert.Equal(t, MsgOut{1234}, out)
numTx.SetResult(wCtx, hash, secondResult)
return nil
},
)
assert.NilError(t, err)
tf.StartWorld()
numTx, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
_ = tf.AddTransaction(numTx.ID(), MsgIn{100})
tf.DoTick()
prevTick := world.CurrentTick() - 1
receipts, err := world.GetTransactionReceiptsForTick(prevTick)
assert.NilError(t, err)
assert.Equal(t, 1, len(receipts))
r := receipts[0]
assert.Equal(t, 0, len(r.Errs))
gotResult, ok := r.Result.(MsgOut)
assert.Check(t, ok)
assert.Equal(t, secondResult, gotResult)
}
func TestTransactionExample(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world, doTick := tf.World, tf.DoTick
assert.NilError(t, cardinal.RegisterComponent[Health](world))
msgName := "add_health"
assert.NilError(t, cardinal.RegisterMessage[AddHealthToEntityTx, AddHealthToEntityResult](world, msgName))
err := cardinal.RegisterSystems(world, func(wCtx cardinal.WorldContext) error {
// test "In" method
addHealthToEntity, err := testutils.GetMessage[AddHealthToEntityTx, AddHealthToEntityResult](world)
if err != nil {
return err
}
for _, tx := range addHealthToEntity.In(wCtx) {
targetID := tx.Msg.TargetID
err := cardinal.UpdateComponent[Health](wCtx, targetID, func(h *Health) *Health {
h.Value = tx.Msg.Amount
return h
})
assert.Check(t, err == nil)
}
// test same as above but with .Each
addHealthToEntity.Each(wCtx,
func(tx cardinal.TxData[AddHealthToEntityTx]) (AddHealthToEntityResult, error) {
targetID := tx.Msg.TargetID
err := cardinal.UpdateComponent[Health](wCtx, targetID,
func(h *Health) *Health {
h.Value = tx.Msg.Amount
return h
})
assert.Check(t, err == nil)
return AddHealthToEntityResult{}, errors.New("fake tx error")
})
return nil
})
assert.NilError(t, err)
testWorldCtx := cardinal.NewWorldContext(world)
doTick()
ids, err := cardinal.CreateMany(testWorldCtx, 10, Health{})
assert.NilError(t, err)
// Queue up the transaction.
idToModify := ids[3]
amountToModify := 20
payload := testutils.UniqueSignature()
addHealthToEntity, ok := world.GetMessageByFullName("game." + msgName)
assert.True(t, ok)
tf.AddTransaction(addHealthToEntity.ID(), AddHealthToEntityTx{idToModify, amountToModify}, payload)
// The health change should be applied during this tick
doTick()
// Make sure the target entity had its health updated.
for _, id := range ids {
var health *Health
health, err = cardinal.GetComponent[Health](testWorldCtx, id)
assert.NilError(t, err)
if id == idToModify {
assert.Equal(t, amountToModify, health.Value)
} else {
assert.Equal(t, 0, health.Value)
}
}
// Make sure transaction errors are recorded in the receipt
receipts, err := tf.World.GetTransactionReceiptsForTick(testWorldCtx.CurrentTick() - 1)
assert.NilError(t, err)
assert.Equal(t, 1, len(receipts))
assert.Equal(t, 1, len(receipts[0].Errs))
}
func TestCreatePersona(t *testing.T) {
namespace := "custom-namespace"
t.Setenv("CARDINAL_NAMESPACE", namespace)
tf := cardinal.NewTestFixture(t, nil)
addr := tf.BaseURL
tf.DoTick()
goodKey, err := crypto.GenerateKey()
assert.NilError(t, err)
body := Rawbodytx{
PersonaTag: "a",
SignerAddress: crypto.PubkeyToAddress(goodKey.PublicKey).Hex(),
}
wantBody, err := json.Marshal(body)
assert.NilError(t, err)
wantNonce := uint64(100)
sp, err := sign.NewSystemTransaction(goodKey, namespace, wantNonce, wantBody)
assert.NilError(t, err)
bodyBytes, err := json.Marshal(sp)
assert.NilError(t, err)
client := &http.Client{}
req, err := http.NewRequest(
http.MethodPost, "http://"+addr+"/tx/persona/create-persona", bytes.NewBuffer(bodyBytes))
assert.NilError(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
assert.NilError(t, err)
assert.Equal(t, resp.StatusCode, http.StatusOK)
// tick before shutdown
tf.DoTick()
}
func TestNewWorld(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
assert.Equal(t, tf.World.Namespace(), cardinal.DefaultCardinalNamespace)
}
func TestNewWorldWithCustomNamespace(t *testing.T) {
t.Setenv("CARDINAL_NAMESPACE", "custom-namespace")
tf := cardinal.NewTestFixture(t, nil)
assert.Equal(t, tf.World.Namespace(), "custom-namespace")
}
func TestCanQueryInsideSystem(t *testing.T) {
testutils.SetTestTimeout(t, 10*time.Second)
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
assert.NilError(t, cardinal.RegisterComponent[Foo](world))
gotNumOfEntities := 0
err := cardinal.RegisterSystems(world, func(wCtx cardinal.WorldContext) error {
err := cardinal.NewSearch().Entity(filter.Exact(filter.Component[Foo]())).Each(wCtx, func(types.EntityID) bool {
gotNumOfEntities++
return true
})
assert.NilError(t, err)
return nil
})
assert.NilError(t, err)
tf.DoTick()
wantNumOfEntities := 10
wCtx := cardinal.NewWorldContext(world)
_, err = cardinal.CreateMany(wCtx, wantNumOfEntities, Foo{})
assert.NilError(t, err)
tf.DoTick()
assert.Equal(t, world.CurrentTick(), uint64(2))
assert.Equal(t, gotNumOfEntities, wantNumOfEntities)
}
func TestRandomNumberGenerator(t *testing.T) {
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
testAmount := 50
numbers1 := make([]int64, 0, testAmount)
err := cardinal.RegisterSystems(world, func(context cardinal.WorldContext) error {
time.Sleep(5 * time.Millisecond)
numbers1 = append(numbers1, context.Rand().Int63())
return nil
})
assert.NilError(t, err)
tf.StartWorld()
for i := 0; i < testAmount; i++ {
tf.DoTick()
}
mapOfNums := make(map[int64]bool)
for _, num := range numbers1 {
_, ok := mapOfNums[num]
assert.Assert(t, ok == false)
mapOfNums[num] = true
}
}
func TestCanGetTimestampFromWorldContext(t *testing.T) {
var ts uint64
tf := cardinal.NewTestFixture(t, nil)
world := tf.World
err := cardinal.RegisterSystems(world, func(context cardinal.WorldContext) error {
ts = context.Timestamp()
return nil
})
assert.NilError(t, err)
tf.StartWorld()
tf.DoTick()
lastTS := ts
time.Sleep(time.Second)
tf.DoTick()
assert.Check(t, ts > lastTS)
}
func TestShutdownViaSignal(t *testing.T) {
// If this test is frozen then it failed to shut down, create a failure with panic.
testutils.SetTestTimeout(t, 10*time.Second)
tf := cardinal.NewTestFixture(t, nil)
world, addr := tf.World, tf.BaseURL
httpBaseURL := "http://" + addr
assert.NilError(t, cardinal.RegisterComponent[Foo](world))
wantNumOfEntities := 10
err := cardinal.RegisterInitSystems(world, func(wCtx cardinal.WorldContext) error {
_, err := cardinal.CreateMany(wCtx, wantNumOfEntities/2, Foo{})
if err != nil {
return err
}
return nil
})
assert.NilError(t, err)
tf.StartWorld()
wCtx := cardinal.NewWorldContext(world)
_, err = cardinal.CreateMany(wCtx, wantNumOfEntities/2, Foo{})
assert.NilError(t, err)
// test CORS with cardinal
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, httpBaseURL+"/world", nil)
assert.NilError(t, err)
req.Header.Set("Origin", "http://www.bullshit.com") // test CORS
resp, err := client.Do(req)
assert.NilError(t, err)
v := resp.Header.Get("Access-Control-Allow-Origin")
assert.Equal(t, v, "*")
assert.Equal(t, resp.StatusCode, 200)
conn, _, err := websocket.DefaultDialer.Dial(wsURL(addr, "events"), nil)
assert.NilError(t, err)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, _, err := conn.ReadMessage()
assert.Assert(t, websocket.IsCloseError(err, websocket.CloseNoStatusReceived))
}()
// Send a SIGINT signal.
cmd := exec.Command("kill", "-SIGINT", strconv.Itoa(os.Getpid()))
err = cmd.Run()
assert.NilError(t, err)
for world.IsGameRunning() {
// wait until game loop is not running
time.Sleep(50 * time.Millisecond)
}
// Wait for goroutine to finish otherwise it will panic
wg.Wait()
}
func TestCallsRegisterGameShardOnStartup(t *testing.T) {
ctrl := gomock.NewController(t)
rtr := mocks.NewMockRouter(ctrl)
tf := cardinal.NewTestFixture(t, nil, cardinal.WithCustomRouter(rtr))
rtr.EXPECT().Start().Times(1)
rtr.EXPECT().RegisterGameShard(gomock.Any()).Times(1)
rtr.EXPECT().SubmitTxBlob(gomock.Any(), gomock.Any(), gomock.Any()).Times(1)
tf.DoTick()
}
func wsURL(addr, path string) string {
return fmt.Sprintf("ws://%s/%s", addr, path)
}