-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
go_test.go
2607 lines (2269 loc) · 76.9 KB
/
go_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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
mygame "MyGame" // refers to generated code
example "MyGame/Example" // refers to generated code
pizza "Pizza"
"encoding/json"
optional_scalars "optional_scalars" // refers to generated code
order "order"
"bytes"
"flag"
"fmt"
"os"
"reflect"
"sort"
"testing"
"testing/quick"
flatbuffers "github.com/google/flatbuffers/go"
)
var (
cppData, javaData, outData string
fuzz bool
fuzzFields, fuzzObjects int
)
func init() {
flag.StringVar(&cppData, "cpp_data", "",
"location of monsterdata_test.mon to verify against (required)")
flag.StringVar(&javaData, "java_data", "",
"location of monsterdata_java_wire.mon to verify against (optional)")
flag.StringVar(&outData, "out_data", "",
"location to write generated Go data")
flag.BoolVar(&fuzz, "fuzz", false, "perform fuzzing")
flag.IntVar(&fuzzFields, "fuzz_fields", 4, "fields per fuzzer object")
flag.IntVar(&fuzzObjects, "fuzz_objects", 10000,
"number of fuzzer objects (higher is slower and more thorough")
}
// Store specific byte patterns in these variables for the fuzzer. These
// values are taken verbatim from the C++ function FuzzTest1.
var (
overflowingInt32Val = flatbuffers.GetInt32([]byte{0x83, 0x33, 0x33, 0x33})
overflowingInt64Val = flatbuffers.GetInt64([]byte{0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44})
)
func TestMain(m *testing.M) {
flag.Parse()
if cppData == "" {
fmt.Fprintf(os.Stderr, "cpp_data argument is required\n")
os.Exit(1)
}
os.Exit(m.Run())
}
// TestTextParsing test if text parsing works with object API.
func TestTextParsing(t *testing.T) {
expectedMonster := example.MonsterT{
Mana: 42,
Name: "foo",
LongEnumNormalDefault: example.LongEnumLongTwo,
}
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(expectedMonster); err != nil {
t.Fatal(err)
}
var monster example.MonsterT
if err := json.NewDecoder(buf).Decode(&monster); err != nil {
t.Fatal(err)
}
if monster.Mana != expectedMonster.Mana {
t.Fatal("wrong mana:", monster.Mana)
}
if monster.Name != expectedMonster.Name {
t.Fatal("wrong name:", monster.Name)
}
if monster.LongEnumNormalDefault != expectedMonster.LongEnumNormalDefault {
t.Fatal("wrong enum:", monster.LongEnumNormalDefault)
}
}
func CheckNoNamespaceImport(fail func(string, ...interface{})) {
const size = 13
// Order a pizza with specific size
builder := flatbuffers.NewBuilder(0)
ordered_pizza := pizza.PizzaT{Size: size}
food := order.FoodT{Pizza: &ordered_pizza}
builder.Finish(food.Pack(builder))
// Receive order
received_food := order.GetRootAsFood(builder.FinishedBytes(), 0)
received_pizza := received_food.Pizza(nil).UnPack()
// Check if received pizza is equal to ordered pizza
if !reflect.DeepEqual(ordered_pizza, *received_pizza) {
fail(FailString("no namespace import", ordered_pizza, received_pizza))
}
}
// TestAll runs all checks, failing if any errors occur.
func TestAll(t *testing.T) {
// Verify that the Go FlatBuffers runtime library generates the
// expected bytes (does not use any schema):
CheckByteLayout(t.Fatalf)
CheckMutateMethods(t.Fatalf)
// Verify that panics are raised during exceptional conditions:
CheckNotInObjectError(t.Fatalf)
CheckStringIsNestedError(t.Fatalf)
CheckByteStringIsNestedError(t.Fatalf)
CheckStructIsNotInlineError(t.Fatalf)
CheckFinishedBytesError(t.Fatalf)
CheckReset(t.Fatalf)
CheckSharedStrings(t.Fatalf)
CheckEmptiedBuilder(t.Fatalf)
// Verify that GetRootAs works for non-root tables
CheckGetRootAsForNonRootTable(t.Fatalf)
CheckTableAccessors(t.Fatalf)
// Verify that using the generated Go code builds a buffer without
// returning errors:
generated, off := CheckGeneratedBuild(false, false, t.Fatalf)
// Verify that the buffer generated by Go code is readable by the
// generated Go code:
CheckReadBuffer(generated, off, false, t.Fatalf)
CheckMutateBuffer(generated, off, false, t.Fatalf)
CheckObjectAPI(generated, off, false, t.Fatalf)
// Generate the buffer again, with file identifier.
generated, off = CheckGeneratedBuild(false, true, t.Fatalf)
// Check that this buffer with file identifier is usable
// and that the file identifier is correct.
CheckReadBuffer(generated, off, false, t.Fatalf)
CheckMutateBuffer(generated, off, false, t.Fatalf)
CheckObjectAPI(generated, off, false, t.Fatalf)
CheckFileIdentifier(generated, off, false, t.Fatalf)
// Verify that the buffer generated by C++ code is readable by the
// generated Go code:
monsterDataCpp, err := os.ReadFile(cppData)
if err != nil {
t.Fatal(err)
}
CheckReadBuffer(monsterDataCpp, 0, false, t.Fatalf)
CheckMutateBuffer(monsterDataCpp, 0, false, t.Fatalf)
CheckObjectAPI(monsterDataCpp, 0, false, t.Fatalf)
CheckFileIdentifier(monsterDataCpp, 0, false, t.Fatalf)
// Verify that vtables are deduplicated when written:
CheckVtableDeduplication(t.Fatalf)
// Verify the enum names
CheckEnumNames(t.Fatalf)
// Verify enum String methods
CheckEnumString(t.Fatalf)
// Verify the enum values maps
CheckEnumValues(t.Fatalf)
// Verify that the Go code used in FlatBuffers documentation passes
// some sanity checks:
CheckDocExample(generated, off, t.Fatalf)
// Check Builder.CreateByteVector
CheckCreateByteVector(t.Fatalf)
// Check a parent namespace import
CheckParentNamespace(t.Fatalf)
// Check a no namespace import
CheckNoNamespaceImport(t.Fatalf)
// Check size-prefixed flatbuffers
CheckSizePrefixedBuffer(t.Fatalf)
// Check that optional scalars works
CheckOptionalScalars(t.Fatalf)
// Check that getting vector element by key works
CheckByKey(t.Fatalf)
// If the filename of the FlatBuffers file generated by the Java test
// is given, check that Go code can read it, and that Go code
// generates an identical buffer when used to create the example data:
if javaData != "" {
monsterDataJava, err := os.ReadFile(javaData)
if err != nil {
t.Fatal(err)
}
CheckReadBuffer(monsterDataJava, 0, false, t.Fatalf)
CheckByteEquality(generated[off:], monsterDataJava, t.Fatalf)
}
// Verify that various fuzzing scenarios produce a valid FlatBuffer.
if fuzz {
checkFuzz(fuzzFields, fuzzObjects, t.Fatalf)
}
// Write the generated buffer out to a file:
err = os.WriteFile(outData, generated[off:], os.FileMode(0644))
if err != nil {
t.Fatal(err)
}
}
// CheckReadBuffer checks that the given buffer is evaluated correctly
// as the example Monster.
func CheckReadBuffer(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) {
// try the two ways of generating a monster
var monster1 *example.Monster
monster2 := &example.Monster{}
if sizePrefix {
monster1 = example.GetSizePrefixedRootAsMonster(buf, offset)
flatbuffers.GetSizePrefixedRootAs(buf, offset, monster2)
} else {
monster1 = example.GetRootAsMonster(buf, offset)
flatbuffers.GetRootAs(buf, offset, monster2)
}
for _, monster := range []*example.Monster{monster1, monster2} {
if got := monster.Hp(); 80 != got {
fail(FailString("hp", 80, got))
}
// default
if got := monster.Mana(); 150 != got {
fail(FailString("mana", 150, got))
}
if got := monster.Name(); !bytes.Equal([]byte("MyMonster"), got) {
fail(FailString("name", "MyMonster", got))
}
if got := monster.Color(); example.ColorBlue != got {
fail(FailString("color", example.ColorBlue, got))
}
if got := monster.Testbool(); true != got {
fail(FailString("testbool", true, got))
}
// initialize a Vec3 from Pos()
vec := new(example.Vec3)
vec = monster.Pos(vec)
if vec == nil {
fail("vec3 initialization failed")
}
// check that new allocs equal given ones:
vec2 := monster.Pos(nil)
if !reflect.DeepEqual(vec, vec2) {
fail("fresh allocation failed")
}
// verify the properties of the Vec3
if got := vec.X(); float32(1.0) != got {
fail(FailString("Pos.X", float32(1.0), got))
}
if got := vec.Y(); float32(2.0) != got {
fail(FailString("Pos.Y", float32(2.0), got))
}
if got := vec.Z(); float32(3.0) != got {
fail(FailString("Pos.Z", float32(3.0), got))
}
if got := vec.Test1(); float64(3.0) != got {
fail(FailString("Pos.Test1", float64(3.0), got))
}
if got := vec.Test2(); example.ColorGreen != got {
fail(FailString("Pos.Test2", example.ColorGreen, got))
}
// initialize a Test from Test3(...)
t := new(example.Test)
t = vec.Test3(t)
if t == nil {
fail("vec.Test3(&t) failed")
}
// check that new allocs equal given ones:
t2 := vec.Test3(nil)
if !reflect.DeepEqual(t, t2) {
fail("fresh allocation failed")
}
// verify the properties of the Test
if got := t.A(); int16(5) != got {
fail(FailString("t.A()", int16(5), got))
}
if got := t.B(); int8(6) != got {
fail(FailString("t.B()", int8(6), got))
}
if got := monster.TestType(); example.AnyMonster != got {
fail(FailString("monster.TestType()", example.AnyMonster, got))
}
// initialize a Table from a union field Test(...)
var table2 flatbuffers.Table
if ok := monster.Test(&table2); !ok {
fail("monster.Test(&monster2) failed")
}
// initialize a Monster from the Table from the union
var monster2 example.Monster
monster2.Init(table2.Bytes, table2.Pos)
if got := monster2.Name(); !bytes.Equal([]byte("Fred"), got) {
fail(FailString("monster2.Name()", "Fred", got))
}
inventorySlice := monster.InventoryBytes()
if len(inventorySlice) != monster.InventoryLength() {
fail(FailString("len(monster.InventoryBytes) != monster.InventoryLength", len(inventorySlice), monster.InventoryLength()))
}
if got := monster.InventoryLength(); 5 != got {
fail(FailString("monster.InventoryLength", 5, got))
}
invsum := 0
l := monster.InventoryLength()
for i := 0; i < l; i++ {
v := monster.Inventory(i)
if v != inventorySlice[i] {
fail(FailString("monster inventory slice[i] != Inventory(i)", v, inventorySlice[i]))
}
invsum += int(v)
}
if invsum != 10 {
fail(FailString("monster inventory sum", 10, invsum))
}
if got := monster.Test4Length(); 2 != got {
fail(FailString("monster.Test4Length()", 2, got))
}
var test0 example.Test
ok := monster.Test4(&test0, 0)
if !ok {
fail(FailString("monster.Test4(&test0, 0)", true, ok))
}
var test1 example.Test
ok = monster.Test4(&test1, 1)
if !ok {
fail(FailString("monster.Test4(&test1, 1)", true, ok))
}
// the position of test0 and test1 are swapped in monsterdata_java_wire
// and monsterdata_test_wire, so ignore ordering
v0 := test0.A()
v1 := test0.B()
v2 := test1.A()
v3 := test1.B()
sum := int(v0) + int(v1) + int(v2) + int(v3)
if 100 != sum {
fail(FailString("test0 and test1 sum", 100, sum))
}
if got := monster.TestarrayofstringLength(); 2 != got {
fail(FailString("Testarrayofstring length", 2, got))
}
if got := monster.Testarrayofstring(0); !bytes.Equal([]byte("test1"), got) {
fail(FailString("Testarrayofstring(0)", "test1", got))
}
if got := monster.Testarrayofstring(1); !bytes.Equal([]byte("test2"), got) {
fail(FailString("Testarrayofstring(1)", "test2", got))
}
}
}
// CheckFileIdentifier checks the "MONS" file identifier
func CheckFileIdentifier(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) {
// Strip offset
buf = buf[offset:]
var fileIdentifier string
var hasFileIdentifier bool
if sizePrefix {
fileIdentifier = flatbuffers.GetSizePrefixedBufferIdentifier(buf)
hasFileIdentifier = example.SizePrefixedMonsterBufferHasIdentifier(buf)
} else {
fileIdentifier = flatbuffers.GetBufferIdentifier(buf)
hasFileIdentifier = example.MonsterBufferHasIdentifier(buf)
}
expectedFileIdentifier := "MONS"
if fileIdentifier != expectedFileIdentifier {
fail("expected file identifier %q, got %q", expectedFileIdentifier, fileIdentifier)
}
if !hasFileIdentifier {
fail("did not find file identifier")
}
}
// CheckMutateBuffer checks that the given buffer can be mutated correctly
// as the example Monster. Only available scalar values are mutated.
func CheckMutateBuffer(org []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) {
// make a copy to mutate
buf := make([]byte, len(org))
copy(buf, org)
// load monster data from the buffer
var monster *example.Monster
if sizePrefix {
monster = example.GetSizePrefixedRootAsMonster(buf, offset)
} else {
monster = example.GetRootAsMonster(buf, offset)
}
// test case struct
type testcase struct {
field string
testfn func() bool
}
testForOriginalValues := []testcase{
testcase{"Hp", func() bool { return monster.Hp() == 80 }},
testcase{"Mana", func() bool { return monster.Mana() == 150 }},
testcase{"Testbool", func() bool { return monster.Testbool() == true }},
testcase{"Pos.X'", func() bool { return monster.Pos(nil).X() == float32(1.0) }},
testcase{"Pos.Y'", func() bool { return monster.Pos(nil).Y() == float32(2.0) }},
testcase{"Pos.Z'", func() bool { return monster.Pos(nil).Z() == float32(3.0) }},
testcase{"Pos.Test1'", func() bool { return monster.Pos(nil).Test1() == float64(3.0) }},
testcase{"Pos.Test2'", func() bool { return monster.Pos(nil).Test2() == example.ColorGreen }},
testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).A() == int16(5) }},
testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).B() == int8(6) }},
testcase{"Inventory[2]", func() bool { return monster.Inventory(2) == byte(2) }},
}
testMutability := []testcase{
testcase{"Hp", func() bool { return monster.MutateHp(70) }},
testcase{"Mana", func() bool { return !monster.MutateMana(140) }},
testcase{"Testbool", func() bool { return monster.MutateTestbool(false) }},
testcase{"Pos.X", func() bool { return monster.Pos(nil).MutateX(10.0) }},
testcase{"Pos.Y", func() bool { return monster.Pos(nil).MutateY(20.0) }},
testcase{"Pos.Z", func() bool { return monster.Pos(nil).MutateZ(30.0) }},
testcase{"Pos.Test1", func() bool { return monster.Pos(nil).MutateTest1(30.0) }},
testcase{"Pos.Test2", func() bool { return monster.Pos(nil).MutateTest2(example.ColorBlue) }},
testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).MutateA(50) }},
testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).MutateB(60) }},
testcase{"Inventory[2]", func() bool { return monster.MutateInventory(2, 200) }},
}
testForMutatedValues := []testcase{
testcase{"Hp", func() bool { return monster.Hp() == 70 }},
testcase{"Mana", func() bool { return monster.Mana() == 150 }},
testcase{"Testbool", func() bool { return monster.Testbool() == false }},
testcase{"Pos.X'", func() bool { return monster.Pos(nil).X() == float32(10.0) }},
testcase{"Pos.Y'", func() bool { return monster.Pos(nil).Y() == float32(20.0) }},
testcase{"Pos.Z'", func() bool { return monster.Pos(nil).Z() == float32(30.0) }},
testcase{"Pos.Test1'", func() bool { return monster.Pos(nil).Test1() == float64(30.0) }},
testcase{"Pos.Test2'", func() bool { return monster.Pos(nil).Test2() == example.ColorBlue }},
testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).A() == int16(50) }},
testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).B() == int8(60) }},
testcase{"Inventory[2]", func() bool { return monster.Inventory(2) == byte(200) }},
}
testInvalidEnumValues := []testcase{
testcase{"Pos.Test2", func() bool { return monster.Pos(nil).MutateTest2(example.Color(20)) }},
testcase{"Pos.Test2", func() bool { return monster.Pos(nil).Test2() == example.Color(20) }},
}
// make sure original values are okay
for _, t := range testForOriginalValues {
if !t.testfn() {
fail("field '" + t.field + "' doesn't have the expected original value")
}
}
// try to mutate fields and check mutability
for _, t := range testMutability {
if !t.testfn() {
fail(FailString("field '"+t.field+"' failed mutability test", true, false))
}
}
// test whether values have changed
for _, t := range testForMutatedValues {
if !t.testfn() {
fail("field '" + t.field + "' doesn't have the expected mutated value")
}
}
// make sure the buffer has changed
if reflect.DeepEqual(buf, org) {
fail("mutate buffer failed")
}
// To make sure the buffer has changed accordingly
// Read data from the buffer and verify all fields
if sizePrefix {
monster = example.GetSizePrefixedRootAsMonster(buf, offset)
} else {
monster = example.GetRootAsMonster(buf, offset)
}
for _, t := range testForMutatedValues {
if !t.testfn() {
fail("field '" + t.field + "' doesn't have the expected mutated value")
}
}
// a couple extra tests for "invalid" enum values, which don't correspond to
// anything in the schema, but are allowed
for _, t := range testInvalidEnumValues {
if !t.testfn() {
fail("field '" + t.field + "' doesn't work with an invalid enum value")
}
}
// reverting all fields to original values should
// re-create the original buffer. Mutate all fields
// back to their original values and compare buffers.
// This test is done to make sure mutations do not do
// any unnecessary changes to the buffer.
if sizePrefix {
monster = example.GetSizePrefixedRootAsMonster(buf, offset)
} else {
monster = example.GetRootAsMonster(buf, offset)
}
monster.MutateHp(80)
monster.MutateTestbool(true)
monster.Pos(nil).MutateX(1.0)
monster.Pos(nil).MutateY(2.0)
monster.Pos(nil).MutateZ(3.0)
monster.Pos(nil).MutateTest1(3.0)
monster.Pos(nil).MutateTest2(example.ColorGreen)
monster.Pos(nil).Test3(nil).MutateA(5)
monster.Pos(nil).Test3(nil).MutateB(6)
monster.MutateInventory(2, 2)
for _, t := range testForOriginalValues {
if !t.testfn() {
fail("field '" + t.field + "' doesn't have the expected original value")
}
}
// buffer should have original values
if !reflect.DeepEqual(buf, org) {
fail("revert changes failed")
}
}
func CheckObjectAPI(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) {
var monster *example.MonsterT
if sizePrefix {
monster = example.GetSizePrefixedRootAsMonster(buf, offset).UnPack()
} else {
monster = example.GetRootAsMonster(buf, offset).UnPack()
}
if got := monster.Hp; 80 != got {
fail(FailString("hp", 80, got))
}
// default
if got := monster.Mana; 150 != got {
fail(FailString("mana", 150, got))
}
if monster.Test != nil && monster.Test.Type == example.AnyMonster {
monster.Test.Value.(*example.MonsterT).NanDefault = 0.0
}
if monster.Enemy != nil {
monster.Enemy.NanDefault = 0.0
}
monster.NanDefault = 0.0
builder := flatbuffers.NewBuilder(0)
builder.Finish(monster.Pack(builder))
monster2 := example.GetRootAsMonster(builder.FinishedBytes(), 0).UnPack()
if !reflect.DeepEqual(monster, monster2) {
fail(FailString("Pack/Unpack()", monster, monster2))
}
}
// Low level stress/fuzz test: serialize/deserialize a variety of
// different kinds of data in different combinations
func checkFuzz(fuzzFields, fuzzObjects int, fail func(string, ...interface{})) {
// Values we're testing against: chosen to ensure no bits get chopped
// off anywhere, and also be different from eachother.
boolVal := true
int8Val := int8(-127) // 0x81
uint8Val := uint8(0xFF)
int16Val := int16(-32222) // 0x8222
uint16Val := uint16(0xFEEE)
int32Val := int32(overflowingInt32Val)
uint32Val := uint32(0xFDDDDDDD)
int64Val := int64(overflowingInt64Val)
uint64Val := uint64(0xFCCCCCCCCCCCCCCC)
float32Val := float32(3.14159)
float64Val := float64(3.14159265359)
testValuesMax := 11 // hardcoded to the number of scalar types
builder := flatbuffers.NewBuilder(0)
l := NewLCG()
objects := make([]flatbuffers.UOffsetT, fuzzObjects)
// Generate fuzzObjects random objects each consisting of
// fuzzFields fields, each of a random type.
for i := 0; i < fuzzObjects; i++ {
builder.StartObject(fuzzFields)
for f := 0; f < fuzzFields; f++ {
choice := l.Next() % uint32(testValuesMax)
switch choice {
case 0:
builder.PrependBoolSlot(int(f), boolVal, false)
case 1:
builder.PrependInt8Slot(int(f), int8Val, 0)
case 2:
builder.PrependUint8Slot(int(f), uint8Val, 0)
case 3:
builder.PrependInt16Slot(int(f), int16Val, 0)
case 4:
builder.PrependUint16Slot(int(f), uint16Val, 0)
case 5:
builder.PrependInt32Slot(int(f), int32Val, 0)
case 6:
builder.PrependUint32Slot(int(f), uint32Val, 0)
case 7:
builder.PrependInt64Slot(int(f), int64Val, 0)
case 8:
builder.PrependUint64Slot(int(f), uint64Val, 0)
case 9:
builder.PrependFloat32Slot(int(f), float32Val, 0)
case 10:
builder.PrependFloat64Slot(int(f), float64Val, 0)
}
}
off := builder.EndObject()
// store the offset from the end of the builder buffer,
// since it will keep growing:
objects[i] = off
}
// Do some bookkeeping to generate stats on fuzzes:
stats := map[string]int{}
check := func(desc string, want, got interface{}) {
stats[desc]++
if want != got {
fail("%s want %v got %v", desc, want, got)
}
}
l = NewLCG() // Reset.
// Test that all objects we generated are readable and return the
// expected values. We generate random objects in the same order
// so this is deterministic.
for i := 0; i < fuzzObjects; i++ {
table := &flatbuffers.Table{
Bytes: builder.Bytes,
Pos: flatbuffers.UOffsetT(len(builder.Bytes)) - objects[i],
}
for j := 0; j < fuzzFields; j++ {
f := flatbuffers.VOffsetT((flatbuffers.VtableMetadataFields + j) * flatbuffers.SizeVOffsetT)
choice := l.Next() % uint32(testValuesMax)
switch choice {
case 0:
check("bool", boolVal, table.GetBoolSlot(f, false))
case 1:
check("int8", int8Val, table.GetInt8Slot(f, 0))
case 2:
check("uint8", uint8Val, table.GetUint8Slot(f, 0))
case 3:
check("int16", int16Val, table.GetInt16Slot(f, 0))
case 4:
check("uint16", uint16Val, table.GetUint16Slot(f, 0))
case 5:
check("int32", int32Val, table.GetInt32Slot(f, 0))
case 6:
check("uint32", uint32Val, table.GetUint32Slot(f, 0))
case 7:
check("int64", int64Val, table.GetInt64Slot(f, 0))
case 8:
check("uint64", uint64Val, table.GetUint64Slot(f, 0))
case 9:
check("float32", float32Val, table.GetFloat32Slot(f, 0))
case 10:
check("float64", float64Val, table.GetFloat64Slot(f, 0))
}
}
}
// If enough checks were made, verify that all scalar types were used:
if fuzzFields*fuzzObjects >= testValuesMax {
if len(stats) != testValuesMax {
fail("fuzzing failed to test all scalar types")
}
}
// Print some counts, if needed:
if testing.Verbose() {
if fuzzFields == 0 || fuzzObjects == 0 {
fmt.Printf("fuzz\tfields: %d\tobjects: %d\t[none]\t%d\n",
fuzzFields, fuzzObjects, 0)
} else {
keys := make([]string, 0, len(stats))
for k := range stats {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("fuzz\tfields: %d\tobjects: %d\t%s\t%d\n",
fuzzFields, fuzzObjects, k, stats[k])
}
}
}
return
}
// FailString makes a message for when expectations differ from reality.
func FailString(name string, want, got interface{}) string {
return fmt.Sprintf("bad %s: want %#v got %#v", name, want, got)
}
// CheckByteLayout verifies the bytes of a Builder in various scenarios.
func CheckByteLayout(fail func(string, ...interface{})) {
var b *flatbuffers.Builder
var i int
check := func(want []byte) {
i++
got := b.Bytes[b.Head():]
if !bytes.Equal(want, got) {
fail("case %d: want\n%v\nbut got\n%v\n", i, want, got)
}
}
// test 1: numbers
b = flatbuffers.NewBuilder(0)
check([]byte{})
b.PrependBool(true)
check([]byte{1})
b.PrependInt8(-127)
check([]byte{129, 1})
b.PrependUint8(255)
check([]byte{255, 129, 1})
b.PrependInt16(-32222)
check([]byte{0x22, 0x82, 0, 255, 129, 1}) // first pad
b.PrependUint16(0xFEEE)
check([]byte{0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) // no pad this time
b.PrependInt32(-53687092)
check([]byte{204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})
b.PrependUint32(0x98765432)
check([]byte{0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})
// test 1b: numbers 2
b = flatbuffers.NewBuilder(0)
b.PrependUint64(0x1122334455667788)
check([]byte{0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11})
// test 2: 1xbyte vector
b = flatbuffers.NewBuilder(0)
check([]byte{})
b.StartVector(flatbuffers.SizeByte, 1, 1)
check([]byte{0, 0, 0}) // align to 4bytes
b.PrependByte(1)
check([]byte{1, 0, 0, 0})
b.EndVector(1)
check([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding
// test 3: 2xbyte vector
b = flatbuffers.NewBuilder(0)
b.StartVector(flatbuffers.SizeByte, 2, 1)
check([]byte{0, 0}) // align to 4bytes
b.PrependByte(1)
check([]byte{1, 0, 0})
b.PrependByte(2)
check([]byte{2, 1, 0, 0})
b.EndVector(2)
check([]byte{2, 0, 0, 0, 2, 1, 0, 0}) // padding
// test 3b: 11xbyte vector matches builder size
b = flatbuffers.NewBuilder(12)
b.StartVector(flatbuffers.SizeByte, 8, 1)
start := []byte{}
check(start)
for i := 1; i < 12; i++ {
b.PrependByte(byte(i))
start = append([]byte{byte(i)}, start...)
check(start)
}
b.EndVector(8)
check(append([]byte{8, 0, 0, 0}, start...))
// test 4: 1xuint16 vector
b = flatbuffers.NewBuilder(0)
b.StartVector(flatbuffers.SizeUint16, 1, 1)
check([]byte{0, 0}) // align to 4bytes
b.PrependUint16(1)
check([]byte{1, 0, 0, 0})
b.EndVector(1)
check([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding
// test 5: 2xuint16 vector
b = flatbuffers.NewBuilder(0)
b.StartVector(flatbuffers.SizeUint16, 2, 1)
check([]byte{}) // align to 4bytes
b.PrependUint16(0xABCD)
check([]byte{0xCD, 0xAB})
b.PrependUint16(0xDCBA)
check([]byte{0xBA, 0xDC, 0xCD, 0xAB})
b.EndVector(2)
check([]byte{2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB})
// test 6: CreateString
b = flatbuffers.NewBuilder(0)
b.CreateString("foo")
check([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad
b.CreateString("moop")
check([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad
3, 0, 0, 0, 'f', 'o', 'o', 0})
// test 6b: CreateString unicode
b = flatbuffers.NewBuilder(0)
// These characters are chinese from blog.golang.org/strings
// We use escape codes here so that editors without unicode support
// aren't bothered:
uni_str := "\u65e5\u672c\u8a9e"
b.CreateString(uni_str)
check([]byte{9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad
0, 0})
// test 6c: CreateByteString
b = flatbuffers.NewBuilder(0)
b.CreateByteString([]byte("foo"))
check([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad
b.CreateByteString([]byte("moop"))
check([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad
3, 0, 0, 0, 'f', 'o', 'o', 0})
// test 7: empty vtable
b = flatbuffers.NewBuilder(0)
b.StartObject(0)
check([]byte{})
b.EndObject()
check([]byte{4, 0, 4, 0, 4, 0, 0, 0})
// test 8: vtable with one true bool
b = flatbuffers.NewBuilder(0)
check([]byte{})
b.StartObject(1)
check([]byte{})
b.PrependBoolSlot(0, true, false)
b.EndObject()
check([]byte{
6, 0, // vtable bytes
8, 0, // length of object including vtable offset
7, 0, // start of bool value
6, 0, 0, 0, // offset for start of vtable (int32)
0, 0, 0, // padded to 4 bytes
1, // bool value
})
// test 9: vtable with one default bool
b = flatbuffers.NewBuilder(0)
check([]byte{})
b.StartObject(1)
check([]byte{})
b.PrependBoolSlot(0, false, false)
b.EndObject()
check([]byte{
4, 0, // vtable bytes
4, 0, // end of object from here
// entry 1 is zero and not stored.
4, 0, 0, 0, // offset for start of vtable (int32)
})
// test 10: vtable with one int16
b = flatbuffers.NewBuilder(0)
b.StartObject(1)
b.PrependInt16Slot(0, 0x789A, 0)
b.EndObject()
check([]byte{
6, 0, // vtable bytes
8, 0, // end of object from here
6, 0, // offset to value
6, 0, 0, 0, // offset for start of vtable (int32)
0, 0, // padding to 4 bytes
0x9A, 0x78,
})
// test 11: vtable with two int16
b = flatbuffers.NewBuilder(0)
b.StartObject(2)
b.PrependInt16Slot(0, 0x3456, 0)
b.PrependInt16Slot(1, 0x789A, 0)
b.EndObject()
check([]byte{
8, 0, // vtable bytes
8, 0, // end of object from here
6, 0, // offset to value 0
4, 0, // offset to value 1
8, 0, 0, 0, // offset for start of vtable (int32)
0x9A, 0x78, // value 1
0x56, 0x34, // value 0
})
// test 12: vtable with int16 and bool
b = flatbuffers.NewBuilder(0)
b.StartObject(2)
b.PrependInt16Slot(0, 0x3456, 0)
b.PrependBoolSlot(1, true, false)
b.EndObject()
check([]byte{
8, 0, // vtable bytes
8, 0, // end of object from here
6, 0, // offset to value 0
5, 0, // offset to value 1
8, 0, 0, 0, // offset for start of vtable (int32)
0, // padding
1, // value 1
0x56, 0x34, // value 0
})
// test 12: vtable with empty vector
b = flatbuffers.NewBuilder(0)
b.StartVector(flatbuffers.SizeByte, 0, 1)
vecend := b.EndVector(0)
b.StartObject(1)
b.PrependUOffsetTSlot(0, vecend, 0)
b.EndObject()
check([]byte{
6, 0, // vtable bytes
8, 0,
4, 0, // offset to vector offset
6, 0, 0, 0, // offset for start of vtable (int32)
4, 0, 0, 0,
0, 0, 0, 0, // length of vector (not in struct)
})
// test 12b: vtable with empty vector of byte and some scalars
b = flatbuffers.NewBuilder(0)
b.StartVector(flatbuffers.SizeByte, 0, 1)
vecend = b.EndVector(0)
b.StartObject(2)
b.PrependInt16Slot(0, 55, 0)
b.PrependUOffsetTSlot(1, vecend, 0)
b.EndObject()
check([]byte{