don't crash when calling EnumNameXXX on sparse enum (#4982)
[platform/upstream/flatbuffers.git] / tests / test.cpp
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "flatbuffers/flatbuffers.h"
18 #include "flatbuffers/idl.h"
19 #include "flatbuffers/minireflect.h"
20 #include "flatbuffers/registry.h"
21 #include "flatbuffers/util.h"
22
23 // clang-format off
24 #ifdef FLATBUFFERS_CPP98_STL
25   #include "flatbuffers/stl_emulation.h"
26   namespace std {
27     using flatbuffers::unique_ptr;
28   }
29 #endif
30 // clang-format on
31
32 #include "monster_test_generated.h"
33 #include "namespace_test/namespace_test1_generated.h"
34 #include "namespace_test/namespace_test2_generated.h"
35 #include "union_vector/union_vector_generated.h"
36 #include "test_assert.h"
37
38 // clang-format off
39 #ifndef FLATBUFFERS_CPP98_STL
40   #include <random>
41 #endif
42
43 #include "flatbuffers/flexbuffers.h"
44
45 using namespace MyGame::Example;
46
47 void FlatBufferBuilderTest();
48
49 // Include simple random number generator to ensure results will be the
50 // same cross platform.
51 // http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
52 uint32_t lcg_seed = 48271;
53 uint32_t lcg_rand() {
54   return lcg_seed = ((uint64_t)lcg_seed * 279470273UL) % 4294967291UL;
55 }
56 void lcg_reset() { lcg_seed = 48271; }
57
58 std::string test_data_path = "tests/";
59
60 // example of how to build up a serialized buffer algorithmically:
61 flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
62   flatbuffers::FlatBufferBuilder builder;
63
64   auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20));
65
66   auto name = builder.CreateString("MyMonster");
67
68   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
69   auto inventory = builder.CreateVector(inv_data, 10);
70
71   // Alternatively, create the vector first, and fill in data later:
72   // unsigned char *inv_buf = nullptr;
73   // auto inventory = builder.CreateUninitializedVector<unsigned char>(
74   //                                                              10, &inv_buf);
75   // memcpy(inv_buf, inv_data, 10);
76
77   Test tests[] = { Test(10, 20), Test(30, 40) };
78   auto testv = builder.CreateVectorOfStructs(tests, 2);
79
80   // clang-format off
81   #ifndef FLATBUFFERS_CPP98_STL
82     // Create a vector of structures from a lambda.
83     auto testv2 = builder.CreateVectorOfStructs<Test>(
84           2, [&](size_t i, Test* s) -> void {
85             *s = tests[i];
86           });
87   #else
88     // Create a vector of structures using a plain old C++ function.
89     auto testv2 = builder.CreateVectorOfStructs<Test>(
90           2, [](size_t i, Test* s, void *state) -> void {
91             *s = (reinterpret_cast<Test*>(state))[i];
92           }, tests);
93   #endif  // FLATBUFFERS_CPP98_STL
94   // clang-format on
95
96   // create monster with very few fields set:
97   // (same functionality as CreateMonster below, but sets fields manually)
98   flatbuffers::Offset<Monster> mlocs[3];
99   auto fred = builder.CreateString("Fred");
100   auto barney = builder.CreateString("Barney");
101   auto wilma = builder.CreateString("Wilma");
102   MonsterBuilder mb1(builder);
103   mb1.add_name(fred);
104   mlocs[0] = mb1.Finish();
105   MonsterBuilder mb2(builder);
106   mb2.add_name(barney);
107   mb2.add_hp(1000);
108   mlocs[1] = mb2.Finish();
109   MonsterBuilder mb3(builder);
110   mb3.add_name(wilma);
111   mlocs[2] = mb3.Finish();
112
113   // Create an array of strings. Also test string pooling, and lambdas.
114   auto vecofstrings =
115       builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
116           4,
117           [](size_t i, flatbuffers::FlatBufferBuilder *b)
118               -> flatbuffers::Offset<flatbuffers::String> {
119             static const char *names[] = { "bob", "fred", "bob", "fred" };
120             return b->CreateSharedString(names[i]);
121           },
122           &builder);
123
124   // Creating vectors of strings in one convenient call.
125   std::vector<std::string> names2;
126   names2.push_back("jane");
127   names2.push_back("mary");
128   auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
129
130   // Create an array of sorted tables, can be used with binary search when read:
131   auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3);
132
133   // Create an array of sorted structs,
134   // can be used with binary search when read:
135   std::vector<Ability> abilities;
136   abilities.push_back(Ability(4, 40));
137   abilities.push_back(Ability(3, 30));
138   abilities.push_back(Ability(2, 20));
139   abilities.push_back(Ability(1, 10));
140   auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities);
141
142   // Create a nested FlatBuffer.
143   // Nested FlatBuffers are stored in a ubyte vector, which can be convenient
144   // since they can be memcpy'd around much easier than other FlatBuffer
145   // values. They have little overhead compared to storing the table directly.
146   // As a test, create a mostly empty Monster buffer:
147   flatbuffers::FlatBufferBuilder nested_builder;
148   auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
149                              nested_builder.CreateString("NestedMonster"));
150   FinishMonsterBuffer(nested_builder, nmloc);
151   // Now we can store the buffer in the parent. Note that by default, vectors
152   // are only aligned to their elements or size field, so in this case if the
153   // buffer contains 64-bit elements, they may not be correctly aligned. We fix
154   // that with:
155   builder.ForceVectorAlignment(nested_builder.GetSize(), sizeof(uint8_t),
156                                nested_builder.GetBufferMinAlignment());
157   // If for whatever reason you don't have the nested_builder available, you
158   // can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or
159   // the largest force_align value in your schema if you're using it.
160   auto nested_flatbuffer_vector = builder.CreateVector(
161       nested_builder.GetBufferPointer(), nested_builder.GetSize());
162
163   // Test a nested FlexBuffer:
164   flexbuffers::Builder flexbuild;
165   flexbuild.Int(1234);
166   flexbuild.Finish();
167   auto flex = builder.CreateVector(flexbuild.GetBuffer());
168
169   // shortcut for creating monster with all fields set:
170   auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue,
171                             Any_Monster, mlocs[1].Union(),  // Store a union.
172                             testv, vecofstrings, vecoftables, 0,
173                             nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0,
174                             0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
175                             vecofstructs, flex, testv2);
176
177   FinishMonsterBuffer(builder, mloc);
178
179   // clang-format off
180   #ifdef FLATBUFFERS_TEST_VERBOSE
181   // print byte data for debugging:
182   auto p = builder.GetBufferPointer();
183   for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++)
184     printf("%d ", p[i]);
185   #endif
186   // clang-format on
187
188   // return the buffer for the caller to use.
189   auto bufferpointer =
190       reinterpret_cast<const char *>(builder.GetBufferPointer());
191   buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
192
193   return builder.ReleaseBufferPointer();
194 }
195
196 //  example of accessing a buffer loaded in memory:
197 void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length,
198                           bool pooled = true) {
199   // First, verify the buffers integrity (optional)
200   flatbuffers::Verifier verifier(flatbuf, length);
201   TEST_EQ(VerifyMonsterBuffer(verifier), true);
202
203   std::vector<uint8_t> test_buff;
204   test_buff.resize(length * 2);
205   std::memcpy(&test_buff[0], flatbuf, length);
206   std::memcpy(&test_buff[length], flatbuf, length);
207
208   flatbuffers::Verifier verifier1(&test_buff[0], length);
209   TEST_EQ(VerifyMonsterBuffer(verifier1), true);
210   TEST_EQ(verifier1.GetComputedSize(), length);
211
212   flatbuffers::Verifier verifier2(&test_buff[length], length);
213   TEST_EQ(VerifyMonsterBuffer(verifier2), true);
214   TEST_EQ(verifier2.GetComputedSize(), length);
215
216   TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0);
217   TEST_EQ(MonsterBufferHasIdentifier(flatbuf), true);
218   TEST_EQ(strcmp(MonsterExtension(), "mon"), 0);
219
220   // Access the buffer from the root.
221   auto monster = GetMonster(flatbuf);
222
223   TEST_EQ(monster->hp(), 80);
224   TEST_EQ(monster->mana(), 150);  // default
225   TEST_EQ_STR(monster->name()->c_str(), "MyMonster");
226   // Can't access the following field, it is deprecated in the schema,
227   // which means accessors are not generated:
228   // monster.friendly()
229
230   auto pos = monster->pos();
231   TEST_NOTNULL(pos);
232   TEST_EQ(pos->z(), 3);
233   TEST_EQ(pos->test3().a(), 10);
234   TEST_EQ(pos->test3().b(), 20);
235
236   auto inventory = monster->inventory();
237   TEST_EQ(VectorLength(inventory), 10UL);  // Works even if inventory is null.
238   TEST_NOTNULL(inventory);
239   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
240   // Check compatibilty of iterators with STL.
241   std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
242   for (auto it = inventory->begin(); it != inventory->end(); ++it) {
243     auto indx = it - inventory->begin();
244     TEST_EQ(*it, inv_vec.at(indx));  // Use bounds-check.
245     TEST_EQ(*it, inv_data[indx]);
246   }
247
248   TEST_EQ(monster->color(), Color_Blue);
249
250   // Example of accessing a union:
251   TEST_EQ(monster->test_type(), Any_Monster);  // First make sure which it is.
252   auto monster2 = reinterpret_cast<const Monster *>(monster->test());
253   TEST_NOTNULL(monster2);
254   TEST_EQ_STR(monster2->name()->c_str(), "Fred");
255
256   // Example of accessing a vector of strings:
257   auto vecofstrings = monster->testarrayofstring();
258   TEST_EQ(vecofstrings->Length(), 4U);
259   TEST_EQ_STR(vecofstrings->Get(0)->c_str(), "bob");
260   TEST_EQ_STR(vecofstrings->Get(1)->c_str(), "fred");
261   if (pooled) {
262     // These should have pointer equality because of string pooling.
263     TEST_EQ(vecofstrings->Get(0)->c_str(), vecofstrings->Get(2)->c_str());
264     TEST_EQ(vecofstrings->Get(1)->c_str(), vecofstrings->Get(3)->c_str());
265   }
266
267   auto vecofstrings2 = monster->testarrayofstring2();
268   if (vecofstrings2) {
269     TEST_EQ(vecofstrings2->Length(), 2U);
270     TEST_EQ_STR(vecofstrings2->Get(0)->c_str(), "jane");
271     TEST_EQ_STR(vecofstrings2->Get(1)->c_str(), "mary");
272   }
273
274   // Example of accessing a vector of tables:
275   auto vecoftables = monster->testarrayoftables();
276   TEST_EQ(vecoftables->Length(), 3U);
277   for (auto it = vecoftables->begin(); it != vecoftables->end(); ++it)
278     TEST_EQ(strlen(it->name()->c_str()) >= 4, true);
279   TEST_EQ_STR(vecoftables->Get(0)->name()->c_str(), "Barney");
280   TEST_EQ(vecoftables->Get(0)->hp(), 1000);
281   TEST_EQ_STR(vecoftables->Get(1)->name()->c_str(), "Fred");
282   TEST_EQ_STR(vecoftables->Get(2)->name()->c_str(), "Wilma");
283   TEST_NOTNULL(vecoftables->LookupByKey("Barney"));
284   TEST_NOTNULL(vecoftables->LookupByKey("Fred"));
285   TEST_NOTNULL(vecoftables->LookupByKey("Wilma"));
286
287   // Test accessing a vector of sorted structs
288   auto vecofstructs = monster->testarrayofsortedstruct();
289   if (vecofstructs) {  // not filled in monster_test.bfbs
290     for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) {
291       auto left = vecofstructs->Get(i);
292       auto right = vecofstructs->Get(i + 1);
293       TEST_EQ(true, (left->KeyCompareLessThan(right)));
294     }
295     TEST_NOTNULL(vecofstructs->LookupByKey(3));
296     TEST_EQ(static_cast<const Ability *>(nullptr),
297             vecofstructs->LookupByKey(5));
298   }
299
300   // Test nested FlatBuffers if available:
301   auto nested_buffer = monster->testnestedflatbuffer();
302   if (nested_buffer) {
303     // nested_buffer is a vector of bytes you can memcpy. However, if you
304     // actually want to access the nested data, this is a convenient
305     // accessor that directly gives you the root table:
306     auto nested_monster = monster->testnestedflatbuffer_nested_root();
307     TEST_EQ_STR(nested_monster->name()->c_str(), "NestedMonster");
308   }
309
310   // Test flexbuffer if available:
311   auto flex = monster->flex();
312   // flex is a vector of bytes you can memcpy etc.
313   TEST_EQ(flex->size(), 4);  // Encoded FlexBuffer bytes.
314   // However, if you actually want to access the nested data, this is a
315   // convenient accessor that directly gives you the root value:
316   TEST_EQ(monster->flex_flexbuffer_root().AsInt16(), 1234);
317
318   // Since Flatbuffers uses explicit mechanisms to override the default
319   // compiler alignment, double check that the compiler indeed obeys them:
320   // (Test consists of a short and byte):
321   TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
322   TEST_EQ(sizeof(Test), 4UL);
323
324   const flatbuffers::Vector<const Test *> *tests_array[] = {
325     monster->test4(),
326     monster->test5(),
327   };
328   for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) {
329     auto tests = tests_array[i];
330     TEST_NOTNULL(tests);
331     auto test_0 = tests->Get(0);
332     auto test_1 = tests->Get(1);
333     TEST_EQ(test_0->a(), 10);
334     TEST_EQ(test_0->b(), 20);
335     TEST_EQ(test_1->a(), 30);
336     TEST_EQ(test_1->b(), 40);
337     for (auto it = tests->begin(); it != tests->end(); ++it) {
338       TEST_EQ(it->a() == 10 || it->a() == 30, true);  // Just testing iterators.
339     }
340   }
341
342   // Checking for presence of fields:
343   TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true);
344   TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false);
345
346   // Obtaining a buffer from a root:
347   TEST_EQ(GetBufferStartFromRootPointer(monster), flatbuf);
348 }
349
350 // Change a FlatBuffer in-place, after it has been constructed.
351 void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) {
352   // Get non-const pointer to root.
353   auto monster = GetMutableMonster(flatbuf);
354
355   // Each of these tests mutates, then tests, then set back to the original,
356   // so we can test that the buffer in the end still passes our original test.
357   auto hp_ok = monster->mutate_hp(10);
358   TEST_EQ(hp_ok, true);  // Field was present.
359   TEST_EQ(monster->hp(), 10);
360   // Mutate to default value
361   auto hp_ok_default = monster->mutate_hp(100);
362   TEST_EQ(hp_ok_default, true);  // Field was present.
363   TEST_EQ(monster->hp(), 100);
364   // Test that mutate to default above keeps field valid for further mutations
365   auto hp_ok_2 = monster->mutate_hp(20);
366   TEST_EQ(hp_ok_2, true);
367   TEST_EQ(monster->hp(), 20);
368   monster->mutate_hp(80);
369
370   // Monster originally at 150 mana (default value)
371   auto mana_default_ok = monster->mutate_mana(150);  // Mutate to default value.
372   TEST_EQ(mana_default_ok,
373           true);  // Mutation should succeed, because default value.
374   TEST_EQ(monster->mana(), 150);
375   auto mana_ok = monster->mutate_mana(10);
376   TEST_EQ(mana_ok, false);  // Field was NOT present, because default value.
377   TEST_EQ(monster->mana(), 150);
378
379   // Mutate structs.
380   auto pos = monster->mutable_pos();
381   auto test3 = pos->mutable_test3();  // Struct inside a struct.
382   test3.mutate_a(50);                 // Struct fields never fail.
383   TEST_EQ(test3.a(), 50);
384   test3.mutate_a(10);
385
386   // Mutate vectors.
387   auto inventory = monster->mutable_inventory();
388   inventory->Mutate(9, 100);
389   TEST_EQ(inventory->Get(9), 100);
390   inventory->Mutate(9, 9);
391
392   auto tables = monster->mutable_testarrayoftables();
393   auto first = tables->GetMutableObject(0);
394   TEST_EQ(first->hp(), 1000);
395   first->mutate_hp(0);
396   TEST_EQ(first->hp(), 0);
397   first->mutate_hp(1000);
398
399   // Run the verifier and the regular test to make sure we didn't trample on
400   // anything.
401   AccessFlatBufferTest(flatbuf, length);
402 }
403
404 // Unpack a FlatBuffer into objects.
405 void ObjectFlatBuffersTest(uint8_t *flatbuf) {
406   // Optional: we can specify resolver and rehasher functions to turn hashed
407   // strings into object pointers and back, to implement remote references
408   // and such.
409   auto resolver = flatbuffers::resolver_function_t(
410       [](void **pointer_adr, flatbuffers::hash_value_t hash) {
411         (void)pointer_adr;
412         (void)hash;
413         // Don't actually do anything, leave variable null.
414       });
415   auto rehasher = flatbuffers::rehasher_function_t(
416       [](void *pointer) -> flatbuffers::hash_value_t {
417         (void)pointer;
418         return 0;
419       });
420
421   // Turn a buffer into C++ objects.
422   auto monster1 = UnPackMonster(flatbuf, &resolver);
423
424   // Re-serialize the data.
425   flatbuffers::FlatBufferBuilder fbb1;
426   fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
427               MonsterIdentifier());
428
429   // Unpack again, and re-serialize again.
430   auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
431   flatbuffers::FlatBufferBuilder fbb2;
432   fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
433               MonsterIdentifier());
434
435   // Now we've gone full round-trip, the two buffers should match.
436   auto len1 = fbb1.GetSize();
437   auto len2 = fbb2.GetSize();
438   TEST_EQ(len1, len2);
439   TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
440
441   // Test it with the original buffer test to make sure all data survived.
442   AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
443
444   // Test accessing fields, similar to AccessFlatBufferTest above.
445   TEST_EQ(monster2->hp, 80);
446   TEST_EQ(monster2->mana, 150);  // default
447   TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
448
449   auto &pos = monster2->pos;
450   TEST_NOTNULL(pos);
451   TEST_EQ(pos->z(), 3);
452   TEST_EQ(pos->test3().a(), 10);
453   TEST_EQ(pos->test3().b(), 20);
454
455   auto &inventory = monster2->inventory;
456   TEST_EQ(inventory.size(), 10UL);
457   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
458   for (auto it = inventory.begin(); it != inventory.end(); ++it)
459     TEST_EQ(*it, inv_data[it - inventory.begin()]);
460
461   TEST_EQ(monster2->color, Color_Blue);
462
463   auto monster3 = monster2->test.AsMonster();
464   TEST_NOTNULL(monster3);
465   TEST_EQ_STR(monster3->name.c_str(), "Fred");
466
467   auto &vecofstrings = monster2->testarrayofstring;
468   TEST_EQ(vecofstrings.size(), 4U);
469   TEST_EQ_STR(vecofstrings[0].c_str(), "bob");
470   TEST_EQ_STR(vecofstrings[1].c_str(), "fred");
471
472   auto &vecofstrings2 = monster2->testarrayofstring2;
473   TEST_EQ(vecofstrings2.size(), 2U);
474   TEST_EQ_STR(vecofstrings2[0].c_str(), "jane");
475   TEST_EQ_STR(vecofstrings2[1].c_str(), "mary");
476
477   auto &vecoftables = monster2->testarrayoftables;
478   TEST_EQ(vecoftables.size(), 3U);
479   TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney");
480   TEST_EQ(vecoftables[0]->hp, 1000);
481   TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred");
482   TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma");
483
484   auto &tests = monster2->test4;
485   TEST_EQ(tests[0].a(), 10);
486   TEST_EQ(tests[0].b(), 20);
487   TEST_EQ(tests[1].a(), 30);
488   TEST_EQ(tests[1].b(), 40);
489 }
490
491 // Prefix a FlatBuffer with a size field.
492 void SizePrefixedTest() {
493   // Create size prefixed buffer.
494   flatbuffers::FlatBufferBuilder fbb;
495   FinishSizePrefixedMonsterBuffer(
496       fbb,
497       CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob")));
498
499   // Verify it.
500   flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
501   TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier), true);
502
503   // Access it.
504   auto m = GetSizePrefixedMonster(fbb.GetBufferPointer());
505   TEST_EQ(m->mana(), 200);
506   TEST_EQ(m->hp(), 300);
507   TEST_EQ_STR(m->name()->c_str(), "bob");
508 }
509
510 void TriviallyCopyableTest() {
511   // clang-format off
512   #if __GNUG__ && __GNUC__ < 5
513     TEST_EQ(__has_trivial_copy(Vec3), true);
514   #else
515     #if __cplusplus >= 201103L
516       TEST_EQ(std::is_trivially_copyable<Vec3>::value, true);
517     #endif
518   #endif
519   // clang-format on
520 }
521
522 // Check stringify of an default enum value to json
523 void JsonDefaultTest() {
524   // load FlatBuffer schema (.fbs) from disk
525   std::string schemafile;
526   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
527                                 false, &schemafile), true);
528   // parse schema first, so we can use it to parse the data after
529   flatbuffers::Parser parser;
530   auto include_test_path =
531       flatbuffers::ConCatPathFileName(test_data_path, "include_test");
532   const char *include_directories[] = { test_data_path.c_str(),
533                                         include_test_path.c_str(), nullptr };
534
535   TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
536   // create incomplete monster and store to json
537   parser.opts.output_default_scalars_in_json = true;
538   parser.opts.output_enum_identifiers = true;
539   flatbuffers::FlatBufferBuilder builder;
540   auto name = builder.CreateString("default_enum");
541   MonsterBuilder color_monster(builder);
542   color_monster.add_name(name);
543   FinishMonsterBuffer(builder, color_monster.Finish());
544   std::string jsongen;
545   auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
546   TEST_EQ(result, true);
547   // default value of the "color" field is Blue
548   TEST_EQ(std::string::npos != jsongen.find("color: \"Blue\""), true);
549   // default value of the "testf" field is 3.14159
550   TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true);
551 }
552
553 // example of parsing text straight into a buffer, and generating
554 // text back from it:
555 void ParseAndGenerateTextTest() {
556   // load FlatBuffer schema (.fbs) and JSON from disk
557   std::string schemafile;
558   std::string jsonfile;
559   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
560                                 false, &schemafile),
561           true);
562   TEST_EQ(flatbuffers::LoadFile(
563               (test_data_path + "monsterdata_test.golden").c_str(), false,
564               &jsonfile),
565           true);
566
567   // parse schema first, so we can use it to parse the data after
568   flatbuffers::Parser parser;
569   auto include_test_path =
570       flatbuffers::ConCatPathFileName(test_data_path, "include_test");
571   const char *include_directories[] = { test_data_path.c_str(),
572                                         include_test_path.c_str(), nullptr };
573   TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
574   TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true);
575
576   // here, parser.builder_ contains a binary buffer that is the parsed data.
577
578   // First, verify it, just in case:
579   flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(),
580                                  parser.builder_.GetSize());
581   TEST_EQ(VerifyMonsterBuffer(verifier), true);
582
583   AccessFlatBufferTest(parser.builder_.GetBufferPointer(),
584                        parser.builder_.GetSize(), false);
585
586   // to ensure it is correct, we now generate text back from the binary,
587   // and compare the two:
588   std::string jsongen;
589   auto result =
590       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
591   TEST_EQ(result, true);
592   TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
593
594   // We can also do the above using the convenient Registry that knows about
595   // a set of file_identifiers mapped to schemas.
596   flatbuffers::Registry registry;
597   // Make sure schemas can find their includes.
598   registry.AddIncludeDirectory(test_data_path.c_str());
599   registry.AddIncludeDirectory(include_test_path.c_str());
600   // Call this with many schemas if possible.
601   registry.Register(MonsterIdentifier(),
602                     (test_data_path + "monster_test.fbs").c_str());
603   // Now we got this set up, we can parse by just specifying the identifier,
604   // the correct schema will be loaded on the fly:
605   auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier());
606   // If this fails, check registry.lasterror_.
607   TEST_NOTNULL(buf.data());
608   // Test the buffer, to be sure:
609   AccessFlatBufferTest(buf.data(), buf.size(), false);
610   // We can use the registry to turn this back into text, in this case it
611   // will get the file_identifier from the binary:
612   std::string text;
613   auto ok = registry.FlatBufferToText(buf.data(), buf.size(), &text);
614   // If this fails, check registry.lasterror_.
615   TEST_EQ(ok, true);
616   TEST_EQ_STR(text.c_str(), jsonfile.c_str());
617
618   // Generate text for UTF-8 strings without escapes.
619   std::string jsonfile_utf8;
620   TEST_EQ(flatbuffers::LoadFile((test_data_path + "unicode_test.json").c_str(),
621                                 false, &jsonfile_utf8),
622           true);
623   TEST_EQ(parser.Parse(jsonfile_utf8.c_str(), include_directories), true);
624   // To ensure it is correct, generate utf-8 text back from the binary.
625   std::string jsongen_utf8;
626   // request natural printing for utf-8 strings
627   parser.opts.natural_utf8 = true;
628   parser.opts.strict_json = true;
629   TEST_EQ(
630       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen_utf8),
631       true);
632   TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str());
633 }
634
635 void ReflectionTest(uint8_t *flatbuf, size_t length) {
636   // Load a binary schema.
637   std::string bfbsfile;
638   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
639                                 true, &bfbsfile),
640           true);
641
642   // Verify it, just in case:
643   flatbuffers::Verifier verifier(
644       reinterpret_cast<const uint8_t *>(bfbsfile.c_str()), bfbsfile.length());
645   TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
646
647   // Make sure the schema is what we expect it to be.
648   auto &schema = *reflection::GetSchema(bfbsfile.c_str());
649   auto root_table = schema.root_table();
650   TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster");
651   auto fields = root_table->fields();
652   auto hp_field_ptr = fields->LookupByKey("hp");
653   TEST_NOTNULL(hp_field_ptr);
654   auto &hp_field = *hp_field_ptr;
655   TEST_EQ_STR(hp_field.name()->c_str(), "hp");
656   TEST_EQ(hp_field.id(), 2);
657   TEST_EQ(hp_field.type()->base_type(), reflection::Short);
658   auto friendly_field_ptr = fields->LookupByKey("friendly");
659   TEST_NOTNULL(friendly_field_ptr);
660   TEST_NOTNULL(friendly_field_ptr->attributes());
661   TEST_NOTNULL(friendly_field_ptr->attributes()->LookupByKey("priority"));
662
663   // Make sure the table index is what we expect it to be.
664   auto pos_field_ptr = fields->LookupByKey("pos");
665   TEST_NOTNULL(pos_field_ptr);
666   TEST_EQ(pos_field_ptr->type()->base_type(), reflection::Obj);
667   auto pos_table_ptr = schema.objects()->Get(pos_field_ptr->type()->index());
668   TEST_NOTNULL(pos_table_ptr);
669   TEST_EQ_STR(pos_table_ptr->name()->c_str(), "MyGame.Example.Vec3");
670
671   // Now use it to dynamically access a buffer.
672   auto &root = *flatbuffers::GetAnyRoot(flatbuf);
673
674   // Verify the buffer first using reflection based verification
675   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
676           true);
677
678   auto hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
679   TEST_EQ(hp, 80);
680
681   // Rather than needing to know the type, we can also get the value of
682   // any field as an int64_t/double/string, regardless of what it actually is.
683   auto hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
684   TEST_EQ(hp_int64, 80);
685   auto hp_double = flatbuffers::GetAnyFieldF(root, hp_field);
686   TEST_EQ(hp_double, 80.0);
687   auto hp_string = flatbuffers::GetAnyFieldS(root, hp_field, &schema);
688   TEST_EQ_STR(hp_string.c_str(), "80");
689
690   // Get struct field through reflection
691   auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr);
692   TEST_NOTNULL(pos_struct);
693   TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct,
694                                     *pos_table_ptr->fields()->LookupByKey("z")),
695           3.0f);
696
697   auto test3_field = pos_table_ptr->fields()->LookupByKey("test3");
698   auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field);
699   TEST_NOTNULL(test3_struct);
700   auto test3_object = schema.objects()->Get(test3_field->type()->index());
701
702   TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct,
703                                     *test3_object->fields()->LookupByKey("a")),
704           10);
705
706   // We can also modify it.
707   flatbuffers::SetField<uint16_t>(&root, hp_field, 200);
708   hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
709   TEST_EQ(hp, 200);
710
711   // We can also set fields generically:
712   flatbuffers::SetAnyFieldI(&root, hp_field, 300);
713   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
714   TEST_EQ(hp_int64, 300);
715   flatbuffers::SetAnyFieldF(&root, hp_field, 300.5);
716   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
717   TEST_EQ(hp_int64, 300);
718   flatbuffers::SetAnyFieldS(&root, hp_field, "300");
719   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
720   TEST_EQ(hp_int64, 300);
721
722   // Test buffer is valid after the modifications
723   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
724           true);
725
726   // Reset it, for further tests.
727   flatbuffers::SetField<uint16_t>(&root, hp_field, 80);
728
729   // More advanced functionality: changing the size of items in-line!
730   // First we put the FlatBuffer inside an std::vector.
731   std::vector<uint8_t> resizingbuf(flatbuf, flatbuf + length);
732   // Find the field we want to modify.
733   auto &name_field = *fields->LookupByKey("name");
734   // Get the root.
735   // This time we wrap the result from GetAnyRoot in a smartpointer that
736   // will keep rroot valid as resizingbuf resizes.
737   auto rroot = flatbuffers::piv(
738       flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
739       resizingbuf);
740   SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
741             &resizingbuf);
742   // Here resizingbuf has changed, but rroot is still valid.
743   TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string");
744   // Now lets extend a vector by 100 elements (10 -> 110).
745   auto &inventory_field = *fields->LookupByKey("inventory");
746   auto rinventory = flatbuffers::piv(
747       flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
748   flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
749                                      &resizingbuf);
750   // rinventory still valid, so lets read from it.
751   TEST_EQ(rinventory->Get(10), 50);
752
753   // For reflection uses not covered already, there is a more powerful way:
754   // we can simply generate whatever object we want to add/modify in a
755   // FlatBuffer of its own, then add that to an existing FlatBuffer:
756   // As an example, let's add a string to an array of strings.
757   // First, find our field:
758   auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
759   // Find the vector value:
760   auto rtestarrayofstring = flatbuffers::piv(
761       flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
762           **rroot, testarrayofstring_field),
763       resizingbuf);
764   // It's a vector of 2 strings, to which we add one more, initialized to
765   // offset 0.
766   flatbuffers::ResizeVector<flatbuffers::Offset<flatbuffers::String>>(
767       schema, 3, 0, *rtestarrayofstring, &resizingbuf);
768   // Here we just create a buffer that contans a single string, but this
769   // could also be any complex set of tables and other values.
770   flatbuffers::FlatBufferBuilder stringfbb;
771   stringfbb.Finish(stringfbb.CreateString("hank"));
772   // Add the contents of it to our existing FlatBuffer.
773   // We do this last, so the pointer doesn't get invalidated (since it is
774   // at the end of the buffer):
775   auto string_ptr = flatbuffers::AddFlatBuffer(
776       resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize());
777   // Finally, set the new value in the vector.
778   rtestarrayofstring->MutateOffset(2, string_ptr);
779   TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob");
780   TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
781   // Test integrity of all resize operations above.
782   flatbuffers::Verifier resize_verifier(
783       reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
784       resizingbuf.size());
785   TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
786
787   // Test buffer is valid using reflection as well
788   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
789                               flatbuffers::vector_data(resizingbuf),
790                               resizingbuf.size()),
791           true);
792
793   // As an additional test, also set it on the name field.
794   // Note: unlike the name change above, this just overwrites the offset,
795   // rather than changing the string in-place.
796   SetFieldT(*rroot, name_field, string_ptr);
797   TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "hank");
798
799   // Using reflection, rather than mutating binary FlatBuffers, we can also copy
800   // tables and other things out of other FlatBuffers into a FlatBufferBuilder,
801   // either part or whole.
802   flatbuffers::FlatBufferBuilder fbb;
803   auto root_offset = flatbuffers::CopyTable(
804       fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true);
805   fbb.Finish(root_offset, MonsterIdentifier());
806   // Test that it was copied correctly:
807   AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize());
808
809   // Test buffer is valid using reflection as well
810   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
811                               fbb.GetBufferPointer(), fbb.GetSize()),
812           true);
813 }
814
815 void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
816   auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable());
817   TEST_EQ_STR(
818       s.c_str(),
819       "{ "
820       "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
821       "{ a: 10, b: 20 } }, "
822       "hp: 80, "
823       "name: \"MyMonster\", "
824       "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
825       "test_type: Monster, "
826       "test: { name: \"Fred\" }, "
827       "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
828       "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
829       "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" "
830       "}, "
831       "{ name: \"Wilma\" } ], "
832       // TODO(wvo): should really print this nested buffer correctly.
833       "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, "
834       "0, "
835       "4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
836       "101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
837       "testarrayofstring2: [ \"jane\", \"mary\" ], "
838       "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
839       "{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
840       "{ id: 4, distance: 40 } ], "
841       "flex: [ 210, 4, 5, 2 ], "
842       "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ] "
843       "}");
844 }
845
846 // Parse a .proto schema, output as .fbs
847 void ParseProtoTest() {
848   // load the .proto and the golden file from disk
849   std::string protofile;
850   std::string goldenfile;
851   std::string goldenunionfile;
852   TEST_EQ(
853       flatbuffers::LoadFile((test_data_path + "prototest/test.proto").c_str(),
854                             false, &protofile),
855       true);
856   TEST_EQ(
857       flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(),
858                             false, &goldenfile),
859       true);
860   TEST_EQ(
861       flatbuffers::LoadFile((test_data_path +
862                             "prototest/test_union.golden").c_str(),
863                             false, &goldenunionfile),
864       true);
865
866   flatbuffers::IDLOptions opts;
867   opts.include_dependence_headers = false;
868   opts.proto_mode = true;
869
870   // Parse proto.
871   flatbuffers::Parser parser(opts);
872   auto protopath = test_data_path + "prototest/";
873   const char *include_directories[] = { protopath.c_str(), nullptr };
874   TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true);
875
876   // Generate fbs.
877   auto fbs = flatbuffers::GenerateFBS(parser, "test");
878
879   // Ensure generated file is parsable.
880   flatbuffers::Parser parser2;
881   TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true);
882   TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
883
884   // Parse proto with --oneof-union option.
885   opts.proto_oneof_union = true;
886   flatbuffers::Parser parser3(opts);
887   TEST_EQ(parser3.Parse(protofile.c_str(), include_directories), true);
888
889   // Generate fbs.
890   auto fbs_union = flatbuffers::GenerateFBS(parser3, "test");
891
892   // Ensure generated file is parsable.
893   flatbuffers::Parser parser4;
894   TEST_EQ(parser4.Parse(fbs_union.c_str(), nullptr), true);
895   TEST_EQ_STR(fbs_union.c_str(), goldenunionfile.c_str());
896 }
897
898 template<typename T>
899 void CompareTableFieldValue(flatbuffers::Table *table,
900                             flatbuffers::voffset_t voffset, T val) {
901   T read = table->GetField(voffset, static_cast<T>(0));
902   TEST_EQ(read, val);
903 }
904
905 // Low level stress/fuzz test: serialize/deserialize a variety of
906 // different kinds of data in different combinations
907 void FuzzTest1() {
908   // Values we're testing against: chosen to ensure no bits get chopped
909   // off anywhere, and also be different from eachother.
910   const uint8_t bool_val = true;
911   const int8_t char_val = -127;  // 0x81
912   const uint8_t uchar_val = 0xFF;
913   const int16_t short_val = -32222;  // 0x8222;
914   const uint16_t ushort_val = 0xFEEE;
915   const int32_t int_val = 0x83333333;
916   const uint32_t uint_val = 0xFDDDDDDD;
917   const int64_t long_val = 0x8444444444444444LL;
918   const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
919   const float float_val = 3.14159f;
920   const double double_val = 3.14159265359;
921
922   const int test_values_max = 11;
923   const flatbuffers::voffset_t fields_per_object = 4;
924   const int num_fuzz_objects = 10000;  // The higher, the more thorough :)
925
926   flatbuffers::FlatBufferBuilder builder;
927
928   lcg_reset();  // Keep it deterministic.
929
930   flatbuffers::uoffset_t objects[num_fuzz_objects];
931
932   // Generate num_fuzz_objects random objects each consisting of
933   // fields_per_object fields, each of a random type.
934   for (int i = 0; i < num_fuzz_objects; i++) {
935     auto start = builder.StartTable();
936     for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
937       int choice = lcg_rand() % test_values_max;
938       auto off = flatbuffers::FieldIndexToOffset(f);
939       switch (choice) {
940         case 0: builder.AddElement<uint8_t>(off, bool_val, 0); break;
941         case 1: builder.AddElement<int8_t>(off, char_val, 0); break;
942         case 2: builder.AddElement<uint8_t>(off, uchar_val, 0); break;
943         case 3: builder.AddElement<int16_t>(off, short_val, 0); break;
944         case 4: builder.AddElement<uint16_t>(off, ushort_val, 0); break;
945         case 5: builder.AddElement<int32_t>(off, int_val, 0); break;
946         case 6: builder.AddElement<uint32_t>(off, uint_val, 0); break;
947         case 7: builder.AddElement<int64_t>(off, long_val, 0); break;
948         case 8: builder.AddElement<uint64_t>(off, ulong_val, 0); break;
949         case 9: builder.AddElement<float>(off, float_val, 0); break;
950         case 10: builder.AddElement<double>(off, double_val, 0); break;
951       }
952     }
953     objects[i] = builder.EndTable(start);
954   }
955   builder.PreAlign<flatbuffers::largest_scalar_t>(0);  // Align whole buffer.
956
957   lcg_reset();  // Reset.
958
959   uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize();
960
961   // Test that all objects we generated are readable and return the
962   // expected values. We generate random objects in the same order
963   // so this is deterministic.
964   for (int i = 0; i < num_fuzz_objects; i++) {
965     auto table = reinterpret_cast<flatbuffers::Table *>(eob - objects[i]);
966     for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
967       int choice = lcg_rand() % test_values_max;
968       flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f);
969       switch (choice) {
970         case 0: CompareTableFieldValue(table, off, bool_val); break;
971         case 1: CompareTableFieldValue(table, off, char_val); break;
972         case 2: CompareTableFieldValue(table, off, uchar_val); break;
973         case 3: CompareTableFieldValue(table, off, short_val); break;
974         case 4: CompareTableFieldValue(table, off, ushort_val); break;
975         case 5: CompareTableFieldValue(table, off, int_val); break;
976         case 6: CompareTableFieldValue(table, off, uint_val); break;
977         case 7: CompareTableFieldValue(table, off, long_val); break;
978         case 8: CompareTableFieldValue(table, off, ulong_val); break;
979         case 9: CompareTableFieldValue(table, off, float_val); break;
980         case 10: CompareTableFieldValue(table, off, double_val); break;
981       }
982     }
983   }
984 }
985
986 // High level stress/fuzz test: generate a big schema and
987 // matching json data in random combinations, then parse both,
988 // generate json back from the binary, and compare with the original.
989 void FuzzTest2() {
990   lcg_reset();  // Keep it deterministic.
991
992   const int num_definitions = 30;
993   const int num_struct_definitions = 5;  // Subset of num_definitions.
994   const int fields_per_definition = 15;
995   const int instances_per_definition = 5;
996   const int deprecation_rate = 10;  // 1 in deprecation_rate fields will
997                                     // be deprecated.
998
999   std::string schema = "namespace test;\n\n";
1000
1001   struct RndDef {
1002     std::string instances[instances_per_definition];
1003
1004     // Since we're generating schema and corresponding data in tandem,
1005     // this convenience function adds strings to both at once.
1006     static void Add(RndDef (&definitions_l)[num_definitions],
1007                     std::string &schema_l, const int instances_per_definition_l,
1008                     const char *schema_add, const char *instance_add,
1009                     int definition) {
1010       schema_l += schema_add;
1011       for (int i = 0; i < instances_per_definition_l; i++)
1012         definitions_l[definition].instances[i] += instance_add;
1013     }
1014   };
1015
1016   // clang-format off
1017   #define AddToSchemaAndInstances(schema_add, instance_add) \
1018     RndDef::Add(definitions, schema, instances_per_definition, \
1019                 schema_add, instance_add, definition)
1020
1021   #define Dummy() \
1022     RndDef::Add(definitions, schema, instances_per_definition, \
1023                 "byte", "1", definition)
1024   // clang-format on
1025
1026   RndDef definitions[num_definitions];
1027
1028   // We are going to generate num_definitions, the first
1029   // num_struct_definitions will be structs, the rest tables. For each
1030   // generate random fields, some of which may be struct/table types
1031   // referring to previously generated structs/tables.
1032   // Simultanenously, we generate instances_per_definition JSON data
1033   // definitions, which will have identical structure to the schema
1034   // being generated. We generate multiple instances such that when creating
1035   // hierarchy, we get some variety by picking one randomly.
1036   for (int definition = 0; definition < num_definitions; definition++) {
1037     std::string definition_name = "D" + flatbuffers::NumToString(definition);
1038
1039     bool is_struct = definition < num_struct_definitions;
1040
1041     AddToSchemaAndInstances(
1042         ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
1043         "{\n");
1044
1045     for (int field = 0; field < fields_per_definition; field++) {
1046       const bool is_last_field = field == fields_per_definition - 1;
1047
1048       // Deprecate 1 in deprecation_rate fields. Only table fields can be
1049       // deprecated.
1050       // Don't deprecate the last field to avoid dangling commas in JSON.
1051       const bool deprecated =
1052           !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0);
1053
1054       std::string field_name = "f" + flatbuffers::NumToString(field);
1055       AddToSchemaAndInstances(("  " + field_name + ":").c_str(),
1056                               deprecated ? "" : (field_name + ": ").c_str());
1057       // Pick random type:
1058       auto base_type = static_cast<flatbuffers::BaseType>(
1059           lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
1060       switch (base_type) {
1061         case flatbuffers::BASE_TYPE_STRING:
1062           if (is_struct) {
1063             Dummy();  // No strings in structs.
1064           } else {
1065             AddToSchemaAndInstances("string", deprecated ? "" : "\"hi\"");
1066           }
1067           break;
1068         case flatbuffers::BASE_TYPE_VECTOR:
1069           if (is_struct) {
1070             Dummy();  // No vectors in structs.
1071           } else {
1072             AddToSchemaAndInstances("[ubyte]",
1073                                     deprecated ? "" : "[\n0,\n1,\n255\n]");
1074           }
1075           break;
1076         case flatbuffers::BASE_TYPE_NONE:
1077         case flatbuffers::BASE_TYPE_UTYPE:
1078         case flatbuffers::BASE_TYPE_STRUCT:
1079         case flatbuffers::BASE_TYPE_UNION:
1080           if (definition) {
1081             // Pick a random previous definition and random data instance of
1082             // that definition.
1083             int defref = lcg_rand() % definition;
1084             int instance = lcg_rand() % instances_per_definition;
1085             AddToSchemaAndInstances(
1086                 ("D" + flatbuffers::NumToString(defref)).c_str(),
1087                 deprecated ? ""
1088                            : definitions[defref].instances[instance].c_str());
1089           } else {
1090             // If this is the first definition, we have no definition we can
1091             // refer to.
1092             Dummy();
1093           }
1094           break;
1095         case flatbuffers::BASE_TYPE_BOOL:
1096           AddToSchemaAndInstances(
1097               "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false"));
1098           break;
1099         default:
1100           // All the scalar types.
1101           schema += flatbuffers::kTypeNames[base_type];
1102
1103           if (!deprecated) {
1104             // We want each instance to use its own random value.
1105             for (int inst = 0; inst < instances_per_definition; inst++)
1106               definitions[definition].instances[inst] +=
1107                   flatbuffers::IsFloat(base_type)
1108                       ? flatbuffers::NumToString<double>(lcg_rand() % 128)
1109                             .c_str()
1110                       : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
1111           }
1112       }
1113       AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
1114                               deprecated ? "" : is_last_field ? "\n" : ",\n");
1115     }
1116     AddToSchemaAndInstances("}\n\n", "}");
1117   }
1118
1119   schema += "root_type D" + flatbuffers::NumToString(num_definitions - 1);
1120   schema += ";\n";
1121
1122   flatbuffers::Parser parser;
1123
1124   // Will not compare against the original if we don't write defaults
1125   parser.builder_.ForceDefaults(true);
1126
1127   // Parse the schema, parse the generated data, then generate text back
1128   // from the binary and compare against the original.
1129   TEST_EQ(parser.Parse(schema.c_str()), true);
1130
1131   const std::string &json =
1132       definitions[num_definitions - 1].instances[0] + "\n";
1133
1134   TEST_EQ(parser.Parse(json.c_str()), true);
1135
1136   std::string jsongen;
1137   parser.opts.indent_step = 0;
1138   auto result =
1139       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1140   TEST_EQ(result, true);
1141
1142   if (jsongen != json) {
1143     // These strings are larger than a megabyte, so we show the bytes around
1144     // the first bytes that are different rather than the whole string.
1145     size_t len = std::min(json.length(), jsongen.length());
1146     for (size_t i = 0; i < len; i++) {
1147       if (json[i] != jsongen[i]) {
1148         i -= std::min(static_cast<size_t>(10), i);  // show some context;
1149         size_t end = std::min(len, i + 20);
1150         for (; i < end; i++)
1151           TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n",
1152                            static_cast<int>(i), jsongen[i], json[i]);
1153         break;
1154       }
1155     }
1156     TEST_NOTNULL(NULL);
1157   }
1158
1159   // clang-format off
1160   #ifdef FLATBUFFERS_TEST_VERBOSE
1161     TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
1162                      static_cast<int>(schema.length() / 1024),
1163                      static_cast<int>(json.length() / 1024));
1164   #endif
1165   // clang-format on
1166 }
1167
1168 // Test that parser errors are actually generated.
1169 void TestError(const char *src, const char *error_substr,
1170                bool strict_json = false) {
1171   flatbuffers::IDLOptions opts;
1172   opts.strict_json = strict_json;
1173   flatbuffers::Parser parser(opts);
1174   TEST_EQ(parser.Parse(src), false);  // Must signal error
1175   // Must be the error we're expecting
1176   TEST_NOTNULL(strstr(parser.error_.c_str(), error_substr));
1177 }
1178
1179 // Test that parsing errors occur as we'd expect.
1180 // Also useful for coverage, making sure these paths are run.
1181 void ErrorTest() {
1182   // In order they appear in idl_parser.cpp
1183   TestError("table X { Y:byte; } root_type X; { Y: 999 }", "does not fit");
1184   TestError(".0", "floating point");
1185   TestError("\"\0", "illegal");
1186   TestError("\"\\q", "escape code");
1187   TestError("table ///", "documentation");
1188   TestError("@", "illegal");
1189   TestError("table 1", "expecting");
1190   TestError("table X { Y:[[int]]; }", "nested vector");
1191   TestError("table X { Y:1; }", "illegal type");
1192   TestError("table X { Y:int; Y:int; }", "field already");
1193   TestError("table Y {} table X { Y:int; }", "same as table");
1194   TestError("struct X { Y:string; }", "only scalar");
1195   TestError("table X { Y:string = \"\"; }", "default values");
1196   TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum");
1197   TestError("struct X { Y:int (deprecated); }", "deprecate");
1198   TestError("union Z { X } table X { Y:Z; } root_type X; { Y: {}, A:1 }",
1199             "missing type field");
1200   TestError("union Z { X } table X { Y:Z; } root_type X; { Y_type: 99, Y: {",
1201             "type id");
1202   TestError("table X { Y:int; } root_type X; { Z:", "unknown field");
1203   TestError("table X { Y:int; } root_type X; { Y:", "string constant", true);
1204   TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant",
1205             true);
1206   TestError(
1207       "struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
1208       "{ V:{ Y:1 } }",
1209       "wrong number");
1210   TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }",
1211             "unknown enum value");
1212   TestError("table X { Y:byte; } root_type X; { Y:; }", "starting");
1213   TestError("enum X:byte { Y } enum X {", "enum already");
1214   TestError("enum X:float {}", "underlying");
1215   TestError("enum X:byte { Y, Y }", "value already");
1216   TestError("enum X:byte { Y=2, Z=1 }", "ascending");
1217   TestError("union X { Y = 256 }", "must fit");
1218   TestError("enum X:byte (bit_flags) { Y=8 }", "bit flag out");
1219   TestError("table X { Y:int; } table X {", "datatype already");
1220   TestError("struct X (force_align: 7) { Y:int; }", "force_align");
1221   TestError("{}", "no root");
1222   TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "one json");
1223   TestError("root_type X;", "unknown root");
1224   TestError("struct X { Y:int; } root_type X;", "a table");
1225   TestError("union X { Y }", "referenced");
1226   TestError("union Z { X } struct X { Y:int; }", "only tables");
1227   TestError("table X { Y:[int]; YLength:int; }", "clash");
1228   TestError("table X { Y:byte; } root_type X; { Y:1, Y:2 }", "more than once");
1229 }
1230
1231 template<typename T> T TestValue(const char *json, const char *type_name) {
1232   flatbuffers::Parser parser;
1233
1234   // Simple schema.
1235   TEST_EQ(parser.Parse(std::string("table X { Y:" + std::string(type_name) +
1236                                    "; } root_type X;")
1237                            .c_str()),
1238           true);
1239
1240   TEST_EQ(parser.Parse(json), true);
1241   auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1242       parser.builder_.GetBufferPointer());
1243   return root->GetField<T>(flatbuffers::FieldIndexToOffset(0), 0);
1244 }
1245
1246 bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; }
1247
1248 // Additional parser testing not covered elsewhere.
1249 void ValueTest() {
1250   // Test scientific notation numbers.
1251   TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"),
1252                        (float)3.14159),
1253           true);
1254
1255   // Test conversion functions.
1256   TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }", "float"), -1),
1257           true);
1258
1259   // Test negative hex constant.
1260   TEST_EQ(TestValue<int>("{ Y:-0x80 }", "int"), -128);
1261
1262   // Make sure we do unsigned 64bit correctly.
1263   TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }", "ulong"),
1264           12335089644688340133ULL);
1265 }
1266
1267 void NestedListTest() {
1268   flatbuffers::Parser parser1;
1269   TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }"
1270                         "root_type T;"
1271                         "{ F:[ [10,20], [30,40]] }"),
1272           true);
1273 }
1274
1275 void EnumStringsTest() {
1276   flatbuffers::Parser parser1;
1277   TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }"
1278                         "root_type T;"
1279                         "{ F:[ A, B, \"C\", \"A B C\" ] }"),
1280           true);
1281   flatbuffers::Parser parser2;
1282   TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }"
1283                         "root_type T;"
1284                         "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"),
1285           true);
1286 }
1287
1288 void EnumNamesTest() {
1289   TEST_EQ_STR("Red", EnumNameColor(Color_Red));
1290   TEST_EQ_STR("Green", EnumNameColor(Color_Green));
1291   TEST_EQ_STR("Blue", EnumNameColor(Color_Blue));
1292   TEST_EQ_STR("", EnumNameColor(static_cast<Color>(-1)));
1293   TEST_EQ_STR("", EnumNameColor(static_cast<Color>(1000)));
1294 }
1295
1296 void IntegerOutOfRangeTest() {
1297   TestError("table T { F:byte; } root_type T; { F:128 }",
1298             "constant does not fit");
1299   TestError("table T { F:byte; } root_type T; { F:-129 }",
1300             "constant does not fit");
1301   TestError("table T { F:ubyte; } root_type T; { F:256 }",
1302             "constant does not fit");
1303   TestError("table T { F:ubyte; } root_type T; { F:-1 }",
1304             "constant does not fit");
1305   TestError("table T { F:short; } root_type T; { F:32768 }",
1306             "constant does not fit");
1307   TestError("table T { F:short; } root_type T; { F:-32769 }",
1308             "constant does not fit");
1309   TestError("table T { F:ushort; } root_type T; { F:65536 }",
1310             "constant does not fit");
1311   TestError("table T { F:ushort; } root_type T; { F:-1 }",
1312             "constant does not fit");
1313   TestError("table T { F:int; } root_type T; { F:2147483648 }",
1314             "constant does not fit");
1315   TestError("table T { F:int; } root_type T; { F:-2147483649 }",
1316             "constant does not fit");
1317   TestError("table T { F:uint; } root_type T; { F:4294967296 }",
1318             "constant does not fit");
1319   TestError("table T { F:uint; } root_type T; { F:-1 }",
1320             "constant does not fit");
1321 }
1322
1323 void IntegerBoundaryTest() {
1324   TEST_EQ(TestValue<int8_t>("{ Y:127 }", "byte"), 127);
1325   TEST_EQ(TestValue<int8_t>("{ Y:-128 }", "byte"), -128);
1326   TEST_EQ(TestValue<uint8_t>("{ Y:255 }", "ubyte"), 255);
1327   TEST_EQ(TestValue<uint8_t>("{ Y:0 }", "ubyte"), 0);
1328   TEST_EQ(TestValue<int16_t>("{ Y:32767 }", "short"), 32767);
1329   TEST_EQ(TestValue<int16_t>("{ Y:-32768 }", "short"), -32768);
1330   TEST_EQ(TestValue<uint16_t>("{ Y:65535 }", "ushort"), 65535);
1331   TEST_EQ(TestValue<uint16_t>("{ Y:0 }", "ushort"), 0);
1332   TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }", "int"), 2147483647);
1333   TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }", "int"), (-2147483647 - 1));
1334   TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }", "uint"), 4294967295);
1335   TEST_EQ(TestValue<uint32_t>("{ Y:0 }", "uint"), 0);
1336   TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }", "long"),
1337           9223372036854775807);
1338   TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }", "long"),
1339           (-9223372036854775807 - 1));
1340   TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }", "ulong"),
1341           18446744073709551615U);
1342   TEST_EQ(TestValue<uint64_t>("{ Y:0 }", "ulong"), 0);
1343 }
1344
1345 void UnicodeTest() {
1346   flatbuffers::Parser parser;
1347   // Without setting allow_non_utf8 = true, we treat \x sequences as byte
1348   // sequences which are then validated as UTF-8.
1349   TEST_EQ(parser.Parse("table T { F:string; }"
1350                        "root_type T;"
1351                        "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1352                        "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8"
1353                        "3D\\uDE0E\" }"),
1354           true);
1355   std::string jsongen;
1356   parser.opts.indent_step = -1;
1357   auto result =
1358       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1359   TEST_EQ(result, true);
1360   TEST_EQ_STR(jsongen.c_str(),
1361               "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1362               "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
1363 }
1364
1365 void UnicodeTestAllowNonUTF8() {
1366   flatbuffers::Parser parser;
1367   parser.opts.allow_non_utf8 = true;
1368   TEST_EQ(
1369       parser.Parse(
1370           "table T { F:string; }"
1371           "root_type T;"
1372           "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1373           "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1374       true);
1375   std::string jsongen;
1376   parser.opts.indent_step = -1;
1377   auto result =
1378       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1379   TEST_EQ(result, true);
1380   TEST_EQ_STR(
1381       jsongen.c_str(),
1382       "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1383       "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
1384 }
1385
1386 void UnicodeTestGenerateTextFailsOnNonUTF8() {
1387   flatbuffers::Parser parser;
1388   // Allow non-UTF-8 initially to model what happens when we load a binary
1389   // flatbuffer from disk which contains non-UTF-8 strings.
1390   parser.opts.allow_non_utf8 = true;
1391   TEST_EQ(
1392       parser.Parse(
1393           "table T { F:string; }"
1394           "root_type T;"
1395           "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1396           "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1397       true);
1398   std::string jsongen;
1399   parser.opts.indent_step = -1;
1400   // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates
1401   // failure.
1402   parser.opts.allow_non_utf8 = false;
1403   auto result =
1404       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1405   TEST_EQ(result, false);
1406 }
1407
1408 void UnicodeSurrogatesTest() {
1409   flatbuffers::Parser parser;
1410
1411   TEST_EQ(parser.Parse("table T { F:string (id: 0); }"
1412                        "root_type T;"
1413                        "{ F:\"\\uD83D\\uDCA9\"}"),
1414           true);
1415   auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1416       parser.builder_.GetBufferPointer());
1417   auto string = root->GetPointer<flatbuffers::String *>(
1418       flatbuffers::FieldIndexToOffset(0));
1419   TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
1420 }
1421
1422 void UnicodeInvalidSurrogatesTest() {
1423   TestError(
1424       "table T { F:string; }"
1425       "root_type T;"
1426       "{ F:\"\\uD800\"}",
1427       "unpaired high surrogate");
1428   TestError(
1429       "table T { F:string; }"
1430       "root_type T;"
1431       "{ F:\"\\uD800abcd\"}",
1432       "unpaired high surrogate");
1433   TestError(
1434       "table T { F:string; }"
1435       "root_type T;"
1436       "{ F:\"\\uD800\\n\"}",
1437       "unpaired high surrogate");
1438   TestError(
1439       "table T { F:string; }"
1440       "root_type T;"
1441       "{ F:\"\\uD800\\uD800\"}",
1442       "multiple high surrogates");
1443   TestError(
1444       "table T { F:string; }"
1445       "root_type T;"
1446       "{ F:\"\\uDC00\"}",
1447       "unpaired low surrogate");
1448 }
1449
1450 void InvalidUTF8Test() {
1451   // "1 byte" pattern, under min length of 2 bytes
1452   TestError(
1453       "table T { F:string; }"
1454       "root_type T;"
1455       "{ F:\"\x80\"}",
1456       "illegal UTF-8 sequence");
1457   // 2 byte pattern, string too short
1458   TestError(
1459       "table T { F:string; }"
1460       "root_type T;"
1461       "{ F:\"\xDF\"}",
1462       "illegal UTF-8 sequence");
1463   // 3 byte pattern, string too short
1464   TestError(
1465       "table T { F:string; }"
1466       "root_type T;"
1467       "{ F:\"\xEF\xBF\"}",
1468       "illegal UTF-8 sequence");
1469   // 4 byte pattern, string too short
1470   TestError(
1471       "table T { F:string; }"
1472       "root_type T;"
1473       "{ F:\"\xF7\xBF\xBF\"}",
1474       "illegal UTF-8 sequence");
1475   // "5 byte" pattern, string too short
1476   TestError(
1477       "table T { F:string; }"
1478       "root_type T;"
1479       "{ F:\"\xFB\xBF\xBF\xBF\"}",
1480       "illegal UTF-8 sequence");
1481   // "6 byte" pattern, string too short
1482   TestError(
1483       "table T { F:string; }"
1484       "root_type T;"
1485       "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}",
1486       "illegal UTF-8 sequence");
1487   // "7 byte" pattern, string too short
1488   TestError(
1489       "table T { F:string; }"
1490       "root_type T;"
1491       "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}",
1492       "illegal UTF-8 sequence");
1493   // "5 byte" pattern, over max length of 4 bytes
1494   TestError(
1495       "table T { F:string; }"
1496       "root_type T;"
1497       "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}",
1498       "illegal UTF-8 sequence");
1499   // "6 byte" pattern, over max length of 4 bytes
1500   TestError(
1501       "table T { F:string; }"
1502       "root_type T;"
1503       "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}",
1504       "illegal UTF-8 sequence");
1505   // "7 byte" pattern, over max length of 4 bytes
1506   TestError(
1507       "table T { F:string; }"
1508       "root_type T;"
1509       "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}",
1510       "illegal UTF-8 sequence");
1511
1512   // Three invalid encodings for U+000A (\n, aka NEWLINE)
1513   TestError(
1514       "table T { F:string; }"
1515       "root_type T;"
1516       "{ F:\"\xC0\x8A\"}",
1517       "illegal UTF-8 sequence");
1518   TestError(
1519       "table T { F:string; }"
1520       "root_type T;"
1521       "{ F:\"\xE0\x80\x8A\"}",
1522       "illegal UTF-8 sequence");
1523   TestError(
1524       "table T { F:string; }"
1525       "root_type T;"
1526       "{ F:\"\xF0\x80\x80\x8A\"}",
1527       "illegal UTF-8 sequence");
1528
1529   // Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL)
1530   TestError(
1531       "table T { F:string; }"
1532       "root_type T;"
1533       "{ F:\"\xE0\x81\xA9\"}",
1534       "illegal UTF-8 sequence");
1535   TestError(
1536       "table T { F:string; }"
1537       "root_type T;"
1538       "{ F:\"\xF0\x80\x81\xA9\"}",
1539       "illegal UTF-8 sequence");
1540
1541   // Invalid encoding for U+20AC (EURO SYMBOL)
1542   TestError(
1543       "table T { F:string; }"
1544       "root_type T;"
1545       "{ F:\"\xF0\x82\x82\xAC\"}",
1546       "illegal UTF-8 sequence");
1547
1548   // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in
1549   // UTF-8
1550   TestError(
1551       "table T { F:string; }"
1552       "root_type T;"
1553       // U+10400 "encoded" as U+D801 U+DC00
1554       "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}",
1555       "illegal UTF-8 sequence");
1556 }
1557
1558 void UnknownFieldsTest() {
1559   flatbuffers::IDLOptions opts;
1560   opts.skip_unexpected_fields_in_json = true;
1561   flatbuffers::Parser parser(opts);
1562
1563   TEST_EQ(parser.Parse("table T { str:string; i:int;}"
1564                        "root_type T;"
1565                        "{ str:\"test\","
1566                        "unknown_string:\"test\","
1567                        "\"unknown_string\":\"test\","
1568                        "unknown_int:10,"
1569                        "unknown_float:1.0,"
1570                        "unknown_array: [ 1, 2, 3, 4],"
1571                        "unknown_object: { i: 10 },"
1572                        "\"unknown_object\": { \"i\": 10 },"
1573                        "i:10}"),
1574           true);
1575
1576   std::string jsongen;
1577   parser.opts.indent_step = -1;
1578   auto result =
1579       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1580   TEST_EQ(result, true);
1581   TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}");
1582 }
1583
1584 void ParseUnionTest() {
1585   // Unions must be parseable with the type field following the object.
1586   flatbuffers::Parser parser;
1587   TEST_EQ(parser.Parse("table T { A:int; }"
1588                        "union U { T }"
1589                        "table V { X:U; }"
1590                        "root_type V;"
1591                        "{ X:{ A:1 }, X_type: T }"),
1592           true);
1593   // Unions must be parsable with prefixed namespace.
1594   flatbuffers::Parser parser2;
1595   TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }"
1596                         "table B { e:U; } root_type B;"
1597                         "{ e_type: N_A, e: {} }"),
1598           true);
1599 }
1600
1601 void UnionVectorTest() {
1602   // load FlatBuffer fbs schema.
1603   // TODO: load a JSON file with such a vector when JSON support is ready.
1604   std::string schemafile;
1605   TEST_EQ(flatbuffers::LoadFile(
1606               (test_data_path + "union_vector/union_vector.fbs").c_str(), false,
1607               &schemafile),
1608           true);
1609
1610   // parse schema.
1611   flatbuffers::IDLOptions idl_opts;
1612   idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kCpp;
1613   flatbuffers::Parser parser(idl_opts);
1614   TEST_EQ(parser.Parse(schemafile.c_str()), true);
1615
1616   flatbuffers::FlatBufferBuilder fbb;
1617
1618   // union types.
1619   std::vector<uint8_t> types;
1620   types.push_back(static_cast<uint8_t>(Character_Belle));
1621   types.push_back(static_cast<uint8_t>(Character_MuLan));
1622   types.push_back(static_cast<uint8_t>(Character_BookFan));
1623   types.push_back(static_cast<uint8_t>(Character_Other));
1624   types.push_back(static_cast<uint8_t>(Character_Unused));
1625
1626   // union values.
1627   std::vector<flatbuffers::Offset<void>> characters;
1628   characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/7)).Union());
1629   characters.push_back(CreateAttacker(fbb, /*sword_attack_damage=*/5).Union());
1630   characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/2)).Union());
1631   characters.push_back(fbb.CreateString("Other").Union());
1632   characters.push_back(fbb.CreateString("Unused").Union());
1633
1634   // create Movie.
1635   const auto movie_offset =
1636       CreateMovie(fbb, Character_Rapunzel,
1637                   fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(),
1638                   fbb.CreateVector(types), fbb.CreateVector(characters));
1639   FinishMovieBuffer(fbb, movie_offset);
1640   auto buf = fbb.GetBufferPointer();
1641
1642   flatbuffers::Verifier verifier(buf, fbb.GetSize());
1643   TEST_EQ(VerifyMovieBuffer(verifier), true);
1644
1645   auto flat_movie = GetMovie(buf);
1646
1647   auto TestMovie = [](const Movie *movie) {
1648     TEST_EQ(movie->main_character_type() == Character_Rapunzel, true);
1649
1650     auto cts = movie->characters_type();
1651     TEST_EQ(movie->characters_type()->size(), 5);
1652     TEST_EQ(cts->GetEnum<Character>(0) == Character_Belle, true);
1653     TEST_EQ(cts->GetEnum<Character>(1) == Character_MuLan, true);
1654     TEST_EQ(cts->GetEnum<Character>(2) == Character_BookFan, true);
1655     TEST_EQ(cts->GetEnum<Character>(3) == Character_Other, true);
1656     TEST_EQ(cts->GetEnum<Character>(4) == Character_Unused, true);
1657
1658     auto rapunzel = movie->main_character_as_Rapunzel();
1659     TEST_EQ(rapunzel->hair_length(), 6);
1660
1661     auto cs = movie->characters();
1662     TEST_EQ(cs->size(), 5);
1663     auto belle = cs->GetAs<BookReader>(0);
1664     TEST_EQ(belle->books_read(), 7);
1665     auto mu_lan = cs->GetAs<Attacker>(1);
1666     TEST_EQ(mu_lan->sword_attack_damage(), 5);
1667     auto book_fan = cs->GetAs<BookReader>(2);
1668     TEST_EQ(book_fan->books_read(), 2);
1669     auto other = cs->GetAsString(3);
1670     TEST_EQ_STR(other->c_str(), "Other");
1671     auto unused = cs->GetAsString(4);
1672     TEST_EQ_STR(unused->c_str(), "Unused");
1673   };
1674
1675   TestMovie(flat_movie);
1676
1677   auto movie_object = flat_movie->UnPack();
1678   TEST_EQ(movie_object->main_character.AsRapunzel()->hair_length(), 6);
1679   TEST_EQ(movie_object->characters[0].AsBelle()->books_read(), 7);
1680   TEST_EQ(movie_object->characters[1].AsMuLan()->sword_attack_damage, 5);
1681   TEST_EQ(movie_object->characters[2].AsBookFan()->books_read(), 2);
1682   TEST_EQ_STR(movie_object->characters[3].AsOther()->c_str(), "Other");
1683   TEST_EQ_STR(movie_object->characters[4].AsUnused()->c_str(), "Unused");
1684
1685   fbb.Clear();
1686   fbb.Finish(Movie::Pack(fbb, movie_object));
1687
1688   delete movie_object;
1689
1690   auto repacked_movie = GetMovie(fbb.GetBufferPointer());
1691
1692   TestMovie(repacked_movie);
1693
1694   auto s =
1695       flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable());
1696   TEST_EQ_STR(
1697       s.c_str(),
1698       "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
1699       "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
1700       "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
1701       "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
1702
1703
1704   flatbuffers::ToStringVisitor visitor("\n", true, "  ");
1705   IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor);
1706   TEST_EQ_STR(
1707       visitor.s.c_str(),
1708       "{\n"
1709       "  \"main_character_type\": \"Rapunzel\",\n"
1710       "  \"main_character\": {\n"
1711       "    \"hair_length\": 6\n"
1712       "  },\n"
1713       "  \"characters_type\": [\n"
1714       "    \"Belle\",\n"
1715       "    \"MuLan\",\n"
1716       "    \"BookFan\",\n"
1717       "    \"Other\",\n"
1718       "    \"Unused\"\n"
1719       "  ],\n"
1720       "  \"characters\": [\n"
1721       "    {\n"
1722       "      \"books_read\": 7\n"
1723       "    },\n"
1724       "    {\n"
1725       "      \"sword_attack_damage\": 5\n"
1726       "    },\n"
1727       "    {\n"
1728       "      \"books_read\": 2\n"
1729       "    },\n"
1730       "    \"Other\",\n"
1731       "    \"Unused\"\n"
1732       "  ]\n"
1733       "}");
1734 }
1735
1736 void ConformTest() {
1737   flatbuffers::Parser parser;
1738   TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
1739
1740   auto test_conform = [](flatbuffers::Parser &parser1, const char *test,
1741                          const char *expected_err) {
1742     flatbuffers::Parser parser2;
1743     TEST_EQ(parser2.Parse(test), true);
1744     auto err = parser2.ConformTo(parser1);
1745     TEST_NOTNULL(strstr(err.c_str(), expected_err));
1746   };
1747
1748   test_conform(parser, "table T { A:byte; }", "types differ for field");
1749   test_conform(parser, "table T { B:int; A:int; }", "offsets differ for field");
1750   test_conform(parser, "table T { A:int = 1; }", "defaults differ for field");
1751   test_conform(parser, "table T { B:float; }",
1752                "field renamed to different type");
1753   test_conform(parser, "enum E:byte { B, A }", "values differ for enum");
1754 }
1755
1756 void ParseProtoBufAsciiTest() {
1757   // We can put the parser in a mode where it will accept JSON that looks more
1758   // like Protobuf ASCII, for users that have data in that format.
1759   // This uses no "" for field names (which we already support by default,
1760   // omits `,`, `:` before `{` and a couple of other features.
1761   flatbuffers::Parser parser;
1762   parser.opts.protobuf_ascii_alike = true;
1763   TEST_EQ(
1764       parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"),
1765       true);
1766   TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true);
1767   // Similarly, in text output, it should omit these.
1768   std::string text;
1769   auto ok = flatbuffers::GenerateText(
1770       parser, parser.builder_.GetBufferPointer(), &text);
1771   TEST_EQ(ok, true);
1772   TEST_EQ_STR(text.c_str(),
1773               "{\n  A [\n    1\n    2\n  ]\n  C {\n    B: 2\n  }\n}\n");
1774 }
1775
1776 void FlexBuffersTest() {
1777   flexbuffers::Builder slb(512,
1778                            flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
1779
1780   // Write the equivalent of:
1781   // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
1782   // foo: 100, bool: true, mymap: { foo: "Fred" } }
1783   // clang-format off
1784   #ifndef FLATBUFFERS_CPP98_STL
1785     // It's possible to do this without std::function support as well.
1786     slb.Map([&]() {
1787        slb.Vector("vec", [&]() {
1788         slb += -100;  // Equivalent to slb.Add(-100) or slb.Int(-100);
1789         slb += "Fred";
1790         slb.IndirectFloat(4.0f);
1791         uint8_t blob[] = { 77 };
1792         slb.Blob(blob, 1);
1793         slb += false;
1794       });
1795       int ints[] = { 1, 2, 3 };
1796       slb.Vector("bar", ints, 3);
1797       slb.FixedTypedVector("bar3", ints, 3);
1798       bool bools[] = {true, false, true, false};
1799       slb.Vector("bools", bools, 4);
1800       slb.Bool("bool", true);
1801       slb.Double("foo", 100);
1802       slb.Map("mymap", [&]() {
1803         slb.String("foo", "Fred");  // Testing key and string reuse.
1804       });
1805     });
1806     slb.Finish();
1807   #else
1808     // It's possible to do this without std::function support as well.
1809     slb.Map([](flexbuffers::Builder& slb2) {
1810        slb2.Vector("vec", [](flexbuffers::Builder& slb3) {
1811         slb3 += -100;  // Equivalent to slb.Add(-100) or slb.Int(-100);
1812         slb3 += "Fred";
1813         slb3.IndirectFloat(4.0f);
1814         uint8_t blob[] = { 77 };
1815         slb3.Blob(blob, 1);
1816         slb3 += false;
1817       }, slb2);
1818       int ints[] = { 1, 2, 3 };
1819       slb2.Vector("bar", ints, 3);
1820       slb2.FixedTypedVector("bar3", ints, 3);
1821       slb2.Bool("bool", true);
1822       slb2.Double("foo", 100);
1823       slb2.Map("mymap", [](flexbuffers::Builder& slb3) {
1824         slb3.String("foo", "Fred");  // Testing key and string reuse.
1825       }, slb2);
1826     }, slb);
1827     slb.Finish();
1828   #endif  // FLATBUFFERS_CPP98_STL
1829
1830   #ifdef FLATBUFFERS_TEST_VERBOSE
1831     for (size_t i = 0; i < slb.GetBuffer().size(); i++)
1832       printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
1833     printf("\n");
1834   #endif
1835   // clang-format on
1836
1837   auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
1838   TEST_EQ(map.size(), 7);
1839   auto vec = map["vec"].AsVector();
1840   TEST_EQ(vec.size(), 5);
1841   TEST_EQ(vec[0].AsInt64(), -100);
1842   TEST_EQ_STR(vec[1].AsString().c_str(), "Fred");
1843   TEST_EQ(vec[1].AsInt64(), 0);  // Number parsing failed.
1844   TEST_EQ(vec[2].AsDouble(), 4.0);
1845   TEST_EQ(vec[2].AsString().IsTheEmptyString(), true);  // Wrong Type.
1846   TEST_EQ_STR(vec[2].AsString().c_str(), "");     // This still works though.
1847   TEST_EQ_STR(vec[2].ToString().c_str(), "4.0");  // Or have it converted.
1848
1849   // Few tests for templated version of As.
1850   TEST_EQ(vec[0].As<int64_t>(), -100);
1851   TEST_EQ_STR(vec[1].As<std::string>().c_str(), "Fred");
1852   TEST_EQ(vec[1].As<int64_t>(), 0);  // Number parsing failed.
1853   TEST_EQ(vec[2].As<double>(), 4.0);
1854
1855   // Test that the blob can be accessed.
1856   TEST_EQ(vec[3].IsBlob(), true);
1857   auto blob = vec[3].AsBlob();
1858   TEST_EQ(blob.size(), 1);
1859   TEST_EQ(blob.data()[0], 77);
1860   TEST_EQ(vec[4].IsBool(), true);   // Check if type is a bool
1861   TEST_EQ(vec[4].AsBool(), false);  // Check if value is false
1862   auto tvec = map["bar"].AsTypedVector();
1863   TEST_EQ(tvec.size(), 3);
1864   TEST_EQ(tvec[2].AsInt8(), 3);
1865   auto tvec3 = map["bar3"].AsFixedTypedVector();
1866   TEST_EQ(tvec3.size(), 3);
1867   TEST_EQ(tvec3[2].AsInt8(), 3);
1868   TEST_EQ(map["bool"].AsBool(), true);
1869   auto tvecb = map["bools"].AsTypedVector();
1870   TEST_EQ(tvecb.ElementType(), flexbuffers::FBT_BOOL);
1871   TEST_EQ(map["foo"].AsUInt8(), 100);
1872   TEST_EQ(map["unknown"].IsNull(), true);
1873   auto mymap = map["mymap"].AsMap();
1874   // These should be equal by pointer equality, since key and value are shared.
1875   TEST_EQ(mymap.Keys()[0].AsKey(), map.Keys()[4].AsKey());
1876   TEST_EQ(mymap.Values()[0].AsString().c_str(), vec[1].AsString().c_str());
1877   // We can mutate values in the buffer.
1878   TEST_EQ(vec[0].MutateInt(-99), true);
1879   TEST_EQ(vec[0].AsInt64(), -99);
1880   TEST_EQ(vec[1].MutateString("John"), true);  // Size must match.
1881   TEST_EQ_STR(vec[1].AsString().c_str(), "John");
1882   TEST_EQ(vec[1].MutateString("Alfred"), false);  // Too long.
1883   TEST_EQ(vec[2].MutateFloat(2.0f), true);
1884   TEST_EQ(vec[2].AsFloat(), 2.0f);
1885   TEST_EQ(vec[2].MutateFloat(3.14159), false);  // Double does not fit in float.
1886   TEST_EQ(vec[4].AsBool(), false);              // Is false before change
1887   TEST_EQ(vec[4].MutateBool(true), true);       // Can change a bool
1888   TEST_EQ(vec[4].AsBool(), true);               // Changed bool is now true
1889
1890   // Parse from JSON:
1891   flatbuffers::Parser parser;
1892   slb.Clear();
1893   auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
1894   TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
1895   auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
1896   auto jmap = jroot.AsMap();
1897   auto jvec = jmap["a"].AsVector();
1898   TEST_EQ(jvec[0].AsInt64(), 123);
1899   TEST_EQ(jvec[1].AsDouble(), 456.0);
1900   TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello");
1901   TEST_EQ(jmap["c"].IsBool(), true);   // Parsed correctly to a bool
1902   TEST_EQ(jmap["c"].AsBool(), true);   // Parsed correctly to true
1903   TEST_EQ(jmap["d"].IsBool(), true);   // Parsed correctly to a bool
1904   TEST_EQ(jmap["d"].AsBool(), false);  // Parsed correctly to false
1905   // And from FlexBuffer back to JSON:
1906   auto jsonback = jroot.ToString();
1907   TEST_EQ_STR(jsontest, jsonback.c_str());
1908 }
1909
1910 void TypeAliasesTest() {
1911   flatbuffers::FlatBufferBuilder builder;
1912
1913   builder.Finish(CreateTypeAliases(
1914       builder, flatbuffers::numeric_limits<int8_t>::min(),
1915       flatbuffers::numeric_limits<uint8_t>::max(),
1916       flatbuffers::numeric_limits<int16_t>::min(),
1917       flatbuffers::numeric_limits<uint16_t>::max(),
1918       flatbuffers::numeric_limits<int32_t>::min(),
1919       flatbuffers::numeric_limits<uint32_t>::max(),
1920       flatbuffers::numeric_limits<int64_t>::min(),
1921       flatbuffers::numeric_limits<uint64_t>::max(), 2.3f, 2.3));
1922
1923   auto p = builder.GetBufferPointer();
1924   auto ta = flatbuffers::GetRoot<TypeAliases>(p);
1925
1926   TEST_EQ(ta->i8(), flatbuffers::numeric_limits<int8_t>::min());
1927   TEST_EQ(ta->u8(), flatbuffers::numeric_limits<uint8_t>::max());
1928   TEST_EQ(ta->i16(), flatbuffers::numeric_limits<int16_t>::min());
1929   TEST_EQ(ta->u16(), flatbuffers::numeric_limits<uint16_t>::max());
1930   TEST_EQ(ta->i32(), flatbuffers::numeric_limits<int32_t>::min());
1931   TEST_EQ(ta->u32(), flatbuffers::numeric_limits<uint32_t>::max());
1932   TEST_EQ(ta->i64(), flatbuffers::numeric_limits<int64_t>::min());
1933   TEST_EQ(ta->u64(), flatbuffers::numeric_limits<uint64_t>::max());
1934   TEST_EQ(ta->f32(), 2.3f);
1935   TEST_EQ(ta->f64(), 2.3);
1936   TEST_EQ(sizeof(ta->i8()), 1);
1937   TEST_EQ(sizeof(ta->i16()), 2);
1938   TEST_EQ(sizeof(ta->i32()), 4);
1939   TEST_EQ(sizeof(ta->i64()), 8);
1940   TEST_EQ(sizeof(ta->u8()), 1);
1941   TEST_EQ(sizeof(ta->u16()), 2);
1942   TEST_EQ(sizeof(ta->u32()), 4);
1943   TEST_EQ(sizeof(ta->u64()), 8);
1944   TEST_EQ(sizeof(ta->f32()), 4);
1945   TEST_EQ(sizeof(ta->f64()), 8);
1946 }
1947
1948 void EndianSwapTest() {
1949   TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)), 0x3412);
1950   TEST_EQ(flatbuffers::EndianSwap(static_cast<int32_t>(0x12345678)),
1951           0x78563412);
1952   TEST_EQ(flatbuffers::EndianSwap(static_cast<int64_t>(0x1234567890ABCDEF)),
1953           0xEFCDAB9078563412);
1954   TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f);
1955 }
1956
1957 void UninitializedVectorTest() {
1958   flatbuffers::FlatBufferBuilder builder;
1959
1960   Test *buf = nullptr;
1961   auto vector_offset = builder.CreateUninitializedVectorOfStructs<Test>(2, &buf);
1962   TEST_NOTNULL(buf);
1963   buf[0] = Test(10, 20);
1964   buf[1] = Test(30, 40);
1965
1966   auto required_name = builder.CreateString("myMonster");
1967   auto monster_builder = MonsterBuilder(builder);
1968   monster_builder.add_name(required_name); // required field mandated for monster.
1969   monster_builder.add_test4(vector_offset);
1970   builder.Finish(monster_builder.Finish());
1971
1972   auto p = builder.GetBufferPointer();
1973   auto uvt = flatbuffers::GetRoot<Monster>(p);
1974   TEST_NOTNULL(uvt);
1975   auto vec = uvt->test4();
1976   TEST_NOTNULL(vec);
1977   auto test_0 = vec->Get(0);
1978   auto test_1 = vec->Get(1);
1979   TEST_EQ(test_0->a(), 10);
1980   TEST_EQ(test_0->b(), 20);
1981   TEST_EQ(test_1->a(), 30);
1982   TEST_EQ(test_1->b(), 40);
1983 }
1984
1985 void EqualOperatorTest() {
1986   MonsterT a;
1987   MonsterT b;
1988   TEST_EQ(b == a, true);
1989
1990   b.mana = 33;
1991   TEST_EQ(b == a, false);
1992   b.mana = 150;
1993   TEST_EQ(b == a, true);
1994
1995   b.inventory.push_back(3);
1996   TEST_EQ(b == a, false);
1997   b.inventory.clear();
1998   TEST_EQ(b == a, true);
1999
2000   b.test.type = Any_Monster;
2001   TEST_EQ(b == a, false);
2002 }
2003
2004 // For testing any binaries, e.g. from fuzzing.
2005 void LoadVerifyBinaryTest() {
2006   std::string binary;
2007   if (flatbuffers::LoadFile((test_data_path +
2008                              "fuzzer/your-filename-here").c_str(),
2009                             true, &binary)) {
2010     flatbuffers::Verifier verifier(
2011           reinterpret_cast<const uint8_t *>(binary.data()), binary.size());
2012     TEST_EQ(VerifyMonsterBuffer(verifier), true);
2013   }
2014 }
2015
2016 int FlatBufferTests() {
2017   // clang-format off
2018   #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \
2019       defined(_MSC_VER) && defined(_DEBUG)
2020     _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF
2021       // For more thorough checking:
2022       //| _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_DELAY_FREE_MEM_DF
2023     );
2024   #endif
2025
2026   // Run our various test suites:
2027
2028   std::string rawbuf;
2029   auto flatbuf1 = CreateFlatBufferTest(rawbuf);
2030   #if !defined(FLATBUFFERS_CPP98_STL)
2031     auto flatbuf = std::move(flatbuf1);  // Test move assignment.
2032   #else
2033     auto &flatbuf = flatbuf1;
2034   #endif // !defined(FLATBUFFERS_CPP98_STL)
2035
2036   TriviallyCopyableTest();
2037
2038   AccessFlatBufferTest(reinterpret_cast<const uint8_t *>(rawbuf.c_str()),
2039                        rawbuf.length());
2040   AccessFlatBufferTest(flatbuf.data(), flatbuf.size());
2041
2042   MutateFlatBuffersTest(flatbuf.data(), flatbuf.size());
2043
2044   ObjectFlatBuffersTest(flatbuf.data());
2045
2046   MiniReflectFlatBuffersTest(flatbuf.data());
2047
2048   SizePrefixedTest();
2049
2050   #ifndef FLATBUFFERS_NO_FILE_TESTS
2051     #ifdef FLATBUFFERS_TEST_PATH_PREFIX
2052       test_data_path = FLATBUFFERS_STRING(FLATBUFFERS_TEST_PATH_PREFIX) +
2053                        test_data_path;
2054     #endif
2055     ParseAndGenerateTextTest();
2056     ReflectionTest(flatbuf.data(), flatbuf.size());
2057     ParseProtoTest();
2058     UnionVectorTest();
2059     LoadVerifyBinaryTest();
2060   #endif
2061   // clang-format on
2062
2063   FuzzTest1();
2064   FuzzTest2();
2065
2066   ErrorTest();
2067   ValueTest();
2068   EnumStringsTest();
2069   EnumNamesTest();
2070   IntegerOutOfRangeTest();
2071   IntegerBoundaryTest();
2072   UnicodeTest();
2073   UnicodeTestAllowNonUTF8();
2074   UnicodeTestGenerateTextFailsOnNonUTF8();
2075   UnicodeSurrogatesTest();
2076   UnicodeInvalidSurrogatesTest();
2077   InvalidUTF8Test();
2078   UnknownFieldsTest();
2079   ParseUnionTest();
2080   ConformTest();
2081   ParseProtoBufAsciiTest();
2082   TypeAliasesTest();
2083   EndianSwapTest();
2084
2085   JsonDefaultTest();
2086
2087   FlexBuffersTest();
2088   UninitializedVectorTest();
2089   EqualOperatorTest();
2090
2091   return 0;
2092 }
2093
2094 int main(int /*argc*/, const char * /*argv*/ []) {
2095   InitTestEngine();
2096
2097   FlatBufferTests();
2098   FlatBufferBuilderTest();
2099
2100   if (!testing_fails) {
2101     TEST_OUTPUT_LINE("ALL TESTS PASSED");
2102     return 0;
2103   } else {
2104     TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails);
2105     return 1;
2106   }
2107 }