# coding=utf-8 # 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. import os.path import sys PY_VERSION = sys.version_info[:2] import ctypes from collections import defaultdict import math import random import timeit import unittest from flatbuffers import compat from flatbuffers import util from flatbuffers.compat import range_func as compat_range from flatbuffers.compat import NumpyRequiredForThisFeature import flatbuffers from flatbuffers import number_types as N import MyGame # refers to generated code import MyGame.Example # refers to generated code import MyGame.Example.Any # refers to generated code import MyGame.Example.Color # refers to generated code import MyGame.Example.Monster # refers to generated code import MyGame.Example.Test # refers to generated code import MyGame.Example.Stat # refers to generated code import MyGame.Example.Vec3 # refers to generated code import MyGame.MonsterExtra # refers to generated code import MyGame.InParentNamespace # refers to generated code import MyGame.Example.ArrayTable # refers to generated code import MyGame.Example.ArrayStruct # refers to generated code import MyGame.Example.NestedStruct # refers to generated code import MyGame.Example.TestEnum # refers to generated code import MyGame.Example.NestedUnion.NestedUnionTest # refers to generated code import MyGame.Example.NestedUnion.Vec3 # refers to generated code import MyGame.Example.NestedUnion.Any # refers to generated code import MyGame.Example.NestedUnion.Test # refers to generated code import MyGame.Example.NestedUnion.Color # refers to generated code import monster_test_generated # the one-file version import optional_scalars import optional_scalars.ScalarStuff def create_namespace_shortcut(is_onefile): # Create shortcut from either the one-file format or the multi-file format global _ANY global _COLOR global _MONSTER global _TEST global _STAT global _VEC3 global _IN_PARENT_NAMESPACE if is_onefile: print('Testing with the one-file generated code') _ANY = monster_test_generated _COLOR = monster_test_generated _MONSTER = monster_test_generated _TEST = monster_test_generated _STAT = monster_test_generated _VEC3 = monster_test_generated _IN_PARENT_NAMESPACE = monster_test_generated else: print('Testing with multi-file generated code') _ANY = MyGame.Example.Any _COLOR = MyGame.Example.Color _MONSTER = MyGame.Example.Monster _TEST = MyGame.Example.Test _STAT = MyGame.Example.Stat _VEC3 = MyGame.Example.Vec3 _IN_PARENT_NAMESPACE = MyGame.InParentNamespace def assertRaises(test_case, fn, exception_class): """ Backwards-compatible assertion for exceptions raised. """ exc = None try: fn() except Exception as e: exc = e test_case.assertTrue(exc is not None) test_case.assertTrue(isinstance(exc, exception_class)) class TestWireFormat(unittest.TestCase): def test_wire_format(self): # Verify that using the generated Python code builds a buffer without # returning errors, and is interpreted correctly, for size prefixed # representation and regular: for sizePrefix in [True, False]: for file_identifier in [None, b'MONS']: gen_buf, gen_off = make_monster_from_generated_code( sizePrefix=sizePrefix, file_identifier=file_identifier) CheckReadBuffer( gen_buf, gen_off, sizePrefix=sizePrefix, file_identifier=file_identifier) # Verify that the canonical flatbuffer file is readable by the # generated Python code. Note that context managers are not part of # Python 2.5, so we use the simpler open/close methods here: f = open('monsterdata_test.mon', 'rb') canonicalWireData = f.read() f.close() CheckReadBuffer(bytearray(canonicalWireData), 0, file_identifier=b'MONS') # Write the generated buffer out to a file: f = open('monsterdata_python_wire.mon', 'wb') f.write(gen_buf[gen_off:]) f.close() class TestObjectBasedAPI(unittest.TestCase): """ Tests the generated object based API.""" def test_consistency_with_repeated_pack_and_unpack(self): """ Checks the serialization and deserialization between a buffer and its python object. It tests in the same way as the C++ object API test, ObjectFlatBuffersTest in test.cpp. """ buf, off = make_monster_from_generated_code() # Turns a buffer into Python object (T class). monster1 = _MONSTER.Monster.GetRootAs(buf, off) monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1) for sizePrefix in [True, False]: # Re-serialize the data into a buffer. b1 = flatbuffers.Builder(0) if sizePrefix: b1.FinishSizePrefixed(monsterT1.Pack(b1)) else: b1.Finish(monsterT1.Pack(b1)) CheckReadBuffer(b1.Bytes, b1.Head(), sizePrefix) # Deserializes the buffer into Python object again. monster2 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head()) # Re-serializes the data into a buffer for one more time. monsterT2 = _MONSTER.MonsterT.InitFromObj(monster2) for sizePrefix in [True, False]: # Re-serializes the data into a buffer b2 = flatbuffers.Builder(0) if sizePrefix: b2.FinishSizePrefixed(monsterT2.Pack(b2)) else: b2.Finish(monsterT2.Pack(b2)) CheckReadBuffer(b2.Bytes, b2.Head(), sizePrefix) def test_default_values_with_pack_and_unpack(self): """ Serializes and deserializes between a buffer with default values (no specific values are filled when the buffer is created) and its python object. """ # Creates a flatbuffer with default values. b1 = flatbuffers.Builder(0) _MONSTER.MonsterStart(b1) gen_mon = _MONSTER.MonsterEnd(b1) b1.Finish(gen_mon) # Converts the flatbuffer into the object class. monster1 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head()) monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1) # Packs the object class into another flatbuffer. b2 = flatbuffers.Builder(0) b2.Finish(monsterT1.Pack(b2)) monster2 = _MONSTER.Monster.GetRootAs(b2.Bytes, b2.Head()) # Checks the default values. self.assertTrue(monster2.Pos() is None) self.assertEqual(monster2.Mana(), 150) self.assertEqual(monster2.Hp(), 100) self.assertTrue(monster2.Name() is None) self.assertEqual(monster2.Inventory(0), 0) self.assertEqual(monster2.InventoryAsNumpy(), 0) self.assertEqual(monster2.InventoryLength(), 0) self.assertTrue(monster2.InventoryIsNone()) self.assertEqual(monster2.Color(), 8) self.assertEqual(monster2.TestType(), 0) self.assertTrue(monster2.Test() is None) self.assertTrue(monster2.Test4(0) is None) self.assertEqual(monster2.Test4Length(), 0) self.assertTrue(monster2.Test4IsNone()) self.assertEqual(monster2.Testarrayofstring(0), '') self.assertEqual(monster2.TestarrayofstringLength(), 0) self.assertTrue(monster2.TestarrayofstringIsNone()) self.assertTrue(monster2.Testarrayoftables(0) is None) self.assertEqual(monster2.TestarrayoftablesLength(), 0) self.assertTrue(monster2.TestarrayoftablesIsNone()) self.assertTrue(monster2.Enemy() is None) self.assertEqual(monster2.Testnestedflatbuffer(0), 0) self.assertEqual(monster2.TestnestedflatbufferAsNumpy(), 0) self.assertEqual(monster2.TestnestedflatbufferLength(), 0) self.assertTrue(monster2.TestnestedflatbufferIsNone()) self.assertTrue(monster2.Testempty() is None) self.assertFalse(monster2.Testbool()) self.assertEqual(monster2.Testhashs32Fnv1(), 0) self.assertEqual(monster2.Testhashu32Fnv1(), 0) self.assertEqual(monster2.Testhashs64Fnv1(), 0) self.assertEqual(monster2.Testhashu64Fnv1(), 0) self.assertEqual(monster2.Testhashs32Fnv1a(), 0) self.assertEqual(monster2.Testhashu32Fnv1a(), 0) self.assertEqual(monster2.Testhashs64Fnv1a(), 0) self.assertEqual(monster2.Testhashu64Fnv1a(), 0) self.assertEqual(monster2.Testarrayofbools(0), 0) self.assertEqual(monster2.TestarrayofboolsAsNumpy(), 0) self.assertEqual(monster2.TestarrayofboolsLength(), 0) self.assertTrue(monster2.TestarrayofboolsIsNone()) self.assertEqual(monster2.Testf(), 3.14159) self.assertEqual(monster2.Testf2(), 3.0) self.assertEqual(monster2.Testf3(), 0.0) self.assertEqual(monster2.Testarrayofstring2(0), '') self.assertEqual(monster2.Testarrayofstring2Length(), 0) self.assertTrue(monster2.Testarrayofstring2IsNone()) self.assertTrue(monster2.Testarrayofsortedstruct(0) is None) self.assertEqual(monster2.TestarrayofsortedstructLength(), 0) self.assertTrue(monster2.TestarrayofsortedstructIsNone()) self.assertEqual(monster2.Flex(0), 0) self.assertEqual(monster2.FlexAsNumpy(), 0) self.assertEqual(monster2.FlexLength(), 0) self.assertTrue(monster2.FlexIsNone()) self.assertTrue(monster2.Test5(0) is None) self.assertEqual(monster2.Test5Length(), 0) self.assertTrue(monster2.Test5IsNone()) self.assertEqual(monster2.VectorOfLongs(0), 0) self.assertEqual(monster2.VectorOfLongsAsNumpy(), 0) self.assertEqual(monster2.VectorOfLongsLength(), 0) self.assertTrue(monster2.VectorOfLongsIsNone()) self.assertEqual(monster2.VectorOfDoubles(0), 0) self.assertEqual(monster2.VectorOfDoublesAsNumpy(), 0) self.assertEqual(monster2.VectorOfDoublesLength(), 0) self.assertTrue(monster2.VectorOfDoublesIsNone()) self.assertTrue(monster2.ParentNamespaceTest() is None) self.assertTrue(monster2.VectorOfReferrables(0) is None) self.assertEqual(monster2.VectorOfReferrablesLength(), 0) self.assertTrue(monster2.VectorOfReferrablesIsNone()) self.assertEqual(monster2.SingleWeakReference(), 0) self.assertEqual(monster2.VectorOfWeakReferences(0), 0) self.assertEqual(monster2.VectorOfWeakReferencesAsNumpy(), 0) self.assertEqual(monster2.VectorOfWeakReferencesLength(), 0) self.assertTrue(monster2.VectorOfWeakReferencesIsNone()) self.assertTrue(monster2.VectorOfStrongReferrables(0) is None) self.assertEqual(monster2.VectorOfStrongReferrablesLength(), 0) self.assertTrue(monster2.VectorOfStrongReferrablesIsNone()) self.assertEqual(monster2.CoOwningReference(), 0) self.assertEqual(monster2.VectorOfCoOwningReferences(0), 0) self.assertEqual(monster2.VectorOfCoOwningReferencesAsNumpy(), 0) self.assertEqual(monster2.VectorOfCoOwningReferencesLength(), 0) self.assertTrue(monster2.VectorOfCoOwningReferencesIsNone()) self.assertEqual(monster2.NonOwningReference(), 0) self.assertEqual(monster2.VectorOfNonOwningReferences(0), 0) self.assertEqual(monster2.VectorOfNonOwningReferencesAsNumpy(), 0) self.assertEqual(monster2.VectorOfNonOwningReferencesLength(), 0) self.assertTrue(monster2.VectorOfNonOwningReferencesIsNone()) self.assertEqual(monster2.AnyUniqueType(), 0) self.assertTrue(monster2.AnyUnique() is None) self.assertEqual(monster2.AnyAmbiguousType(), 0) self.assertTrue(monster2.AnyAmbiguous() is None) self.assertEqual(monster2.VectorOfEnums(0), 0) self.assertEqual(monster2.VectorOfEnumsAsNumpy(), 0) self.assertEqual(monster2.VectorOfEnumsLength(), 0) self.assertTrue(monster2.VectorOfEnumsIsNone()) def test_optional_scalars_with_pack_and_unpack(self): """ Serializes and deserializes between a buffer with optional values (no specific values are filled when the buffer is created) and its python object. """ # Creates a flatbuffer with optional values. b1 = flatbuffers.Builder(0) optional_scalars.ScalarStuff.ScalarStuffStart(b1) gen_opt = optional_scalars.ScalarStuff.ScalarStuffEnd(b1) b1.Finish(gen_opt) # Converts the flatbuffer into the object class. opts1 = optional_scalars.ScalarStuff.ScalarStuff.GetRootAs(b1.Bytes, b1.Head()) optsT1 = optional_scalars.ScalarStuff.ScalarStuffT.InitFromObj(opts1) # Packs the object class into another flatbuffer. b2 = flatbuffers.Builder(0) b2.Finish(optsT1.Pack(b2)) opts2 = optional_scalars.ScalarStuff.ScalarStuff.GetRootAs(b2.Bytes, b2.Head()) optsT2 = optional_scalars.ScalarStuff.ScalarStuffT.InitFromObj(opts2) # Checks the default values. self.assertTrue(opts2.JustI8() == 0) self.assertTrue(opts2.MaybeF32() is None) self.assertTrue(opts2.DefaultBool() is True) self.assertTrue(optsT2.justU16 == 0) self.assertTrue(optsT2.maybeEnum is None) self.assertTrue(optsT2.defaultU64 == 42) class TestAllMutableCodePathsOfExampleSchema(unittest.TestCase): """ Tests the object API generated for monster_test.fbs for mutation purposes. In each test, the default values will be changed through the object API. We'll then pack the object class into the buf class and read the updated values out from it to validate if the values are mutated as expected. """ def setUp(self, *args, **kwargs): super(TestAllMutableCodePathsOfExampleSchema, self).setUp(*args, **kwargs) # Creates an empty monster flatbuffer, and loads it into the object # class for future tests. b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) self.monsterT = self._create_and_load_object_class(b) def _pack_and_load_buf_class(self, monsterT): """ Packs the object class into a flatbuffer and loads it into a buf class. """ b = flatbuffers.Builder(0) b.Finish(monsterT.Pack(b)) monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) return monster def _create_and_load_object_class(self, b): """ Finishs the creation of a monster flatbuffer and loads it into an object class. """ gen_mon = _MONSTER.MonsterEnd(b) b.Finish(gen_mon) monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) monsterT = _MONSTER.MonsterT() monsterT.InitFromObj(monster) return monsterT def test_mutate_pos(self): posT = _VEC3.Vec3T() posT.x = 4.0 posT.y = 5.0 posT.z = 6.0 posT.test1 = 6.0 posT.test2 = 7 test3T = _TEST.TestT() test3T.a = 8 test3T.b = 9 posT.test3 = test3T self.monsterT.pos = posT # Packs the updated values. monster = self._pack_and_load_buf_class(self.monsterT) # Checks if values are loaded correctly into the object class. pos = monster.Pos() # Verifies the properties of the Vec3. self.assertEqual(pos.X(), 4.0) self.assertEqual(pos.Y(), 5.0) self.assertEqual(pos.Z(), 6.0) self.assertEqual(pos.Test1(), 6.0) self.assertEqual(pos.Test2(), 7) t3 = _TEST.Test() t3 = pos.Test3(t3) self.assertEqual(t3.A(), 8) self.assertEqual(t3.B(), 9) def test_mutate_mana(self): self.monsterT.mana = 200 monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Mana(), 200) def test_mutate_hp(self): self.monsterT.hp = 200 monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Hp(), 200) def test_mutate_name(self): self.monsterT.name = 'MyMonster' monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Name(), b'MyMonster') def test_mutate_inventory(self): self.monsterT.inventory = [1, 7, 8] monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Inventory(0), 1) self.assertEqual(monster.Inventory(1), 7) self.assertEqual(monster.Inventory(2), 8) def test_empty_inventory(self): self.monsterT.inventory = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.InventoryIsNone()) def test_mutate_color(self): self.monsterT.color = _COLOR.Color.Red monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Color(), _COLOR.Color.Red) def test_mutate_testtype(self): self.monsterT.testType = _ANY.Any.Monster monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.TestType(), _ANY.Any.Monster) def test_mutate_test(self): testT = _MONSTER.MonsterT() testT.hp = 200 self.monsterT.test = testT monster = self._pack_and_load_buf_class(self.monsterT) # Initializes a Table from a union field Test(...). table = monster.Test() # Initializes a Monster from the Table from the union. test_monster = _MONSTER.Monster() test_monster.Init(table.Bytes, table.Pos) self.assertEqual(test_monster.Hp(), 200) def test_mutate_test4(self): test0T = _TEST.TestT() test0T.a = 10 test0T.b = 20 test1T = _TEST.TestT() test1T.a = 30 test1T.b = 40 self.monsterT.test4 = [test0T, test1T] monster = self._pack_and_load_buf_class(self.monsterT) test0 = monster.Test4(0) self.assertEqual(test0.A(), 10) self.assertEqual(test0.B(), 20) test1 = monster.Test4(1) self.assertEqual(test1.A(), 30) self.assertEqual(test1.B(), 40) def test_empty_test4(self): self.monsterT.test4 = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.Test4IsNone()) def test_mutate_testarrayofstring(self): self.monsterT.testarrayofstring = [] self.monsterT.testarrayofstring.append('test1') self.monsterT.testarrayofstring.append('test2') monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testarrayofstring(0), b'test1') self.assertEqual(monster.Testarrayofstring(1), b'test2') def test_empty_testarrayofstring(self): self.monsterT.testarrayofstring = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.TestarrayofstringIsNone()) def test_mutate_testarrayoftables(self): monsterT0 = _MONSTER.MonsterT() monsterT0.hp = 200 monsterT1 = _MONSTER.MonsterT() monsterT1.hp = 400 self.monsterT.testarrayoftables = [] self.monsterT.testarrayoftables.append(monsterT0) self.monsterT.testarrayoftables.append(monsterT1) monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testarrayoftables(0).Hp(), 200) self.assertEqual(monster.Testarrayoftables(1).Hp(), 400) def test_empty_testarrayoftables(self): self.monsterT.testarrayoftables = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.TestarrayoftablesIsNone()) def test_mutate_enemy(self): monsterT = _MONSTER.MonsterT() monsterT.hp = 200 self.monsterT.enemy = monsterT monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Enemy().Hp(), 200) def test_mutate_testnestedflatbuffer(self): self.monsterT.testnestedflatbuffer = [8, 2, 4] monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testnestedflatbuffer(0), 8) self.assertEqual(monster.Testnestedflatbuffer(1), 2) self.assertEqual(monster.Testnestedflatbuffer(2), 4) def test_empty_testnestedflatbuffer(self): self.monsterT.testnestedflatbuffer = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.TestnestedflatbufferIsNone()) def test_mutate_testbool(self): self.monsterT.testbool = True monster = self._pack_and_load_buf_class(self.monsterT) self.assertTrue(monster.Testbool()) def test_mutate_testhashes(self): self.monsterT.testhashs32Fnv1 = 1 self.monsterT.testhashu32Fnv1 = 2 self.monsterT.testhashs64Fnv1 = 3 self.monsterT.testhashu64Fnv1 = 4 self.monsterT.testhashs32Fnv1a = 5 self.monsterT.testhashu32Fnv1a = 6 self.monsterT.testhashs64Fnv1a = 7 self.monsterT.testhashu64Fnv1a = 8 monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testhashs32Fnv1(), 1) self.assertEqual(monster.Testhashu32Fnv1(), 2) self.assertEqual(monster.Testhashs64Fnv1(), 3) self.assertEqual(monster.Testhashu64Fnv1(), 4) self.assertEqual(monster.Testhashs32Fnv1a(), 5) self.assertEqual(monster.Testhashu32Fnv1a(), 6) self.assertEqual(monster.Testhashs64Fnv1a(), 7) self.assertEqual(monster.Testhashu64Fnv1a(), 8) def test_mutate_testarrayofbools(self): self.monsterT.testarrayofbools = [] self.monsterT.testarrayofbools.append(True) self.monsterT.testarrayofbools.append(True) self.monsterT.testarrayofbools.append(False) monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testarrayofbools(0), True) self.assertEqual(monster.Testarrayofbools(1), True) self.assertEqual(monster.Testarrayofbools(2), False) def test_empty_testarrayofbools(self): self.monsterT.testarrayofbools = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.TestarrayofboolsIsNone()) def test_mutate_testf(self): self.monsterT.testf = 2.0 monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.Testf(), 2.0) def test_mutate_vectoroflongs(self): self.monsterT.vectorOfLongs = [] self.monsterT.vectorOfLongs.append(1) self.monsterT.vectorOfLongs.append(100) self.monsterT.vectorOfLongs.append(10000) self.monsterT.vectorOfLongs.append(1000000) self.monsterT.vectorOfLongs.append(100000000) monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.VectorOfLongs(0), 1) self.assertEqual(monster.VectorOfLongs(1), 100) self.assertEqual(monster.VectorOfLongs(2), 10000) self.assertEqual(monster.VectorOfLongs(3), 1000000) self.assertEqual(monster.VectorOfLongs(4), 100000000) def test_empty_vectoroflongs(self): self.monsterT.vectorOfLongs = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.VectorOfLongsIsNone()) def test_mutate_vectorofdoubles(self): self.monsterT.vectorOfDoubles = [] self.monsterT.vectorOfDoubles.append(-1.7976931348623157e+308) self.monsterT.vectorOfDoubles.append(0) self.monsterT.vectorOfDoubles.append(1.7976931348623157e+308) monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.VectorOfDoubles(0), -1.7976931348623157e+308) self.assertEqual(monster.VectorOfDoubles(1), 0) self.assertEqual(monster.VectorOfDoubles(2), 1.7976931348623157e+308) def test_empty_vectorofdoubles(self): self.monsterT.vectorOfDoubles = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.VectorOfDoublesIsNone()) def test_mutate_parentnamespacetest(self): self.monsterT.parentNamespaceTest = _IN_PARENT_NAMESPACE.InParentNamespaceT( ) monster = self._pack_and_load_buf_class(self.monsterT) self.assertTrue( isinstance(monster.ParentNamespaceTest(), _IN_PARENT_NAMESPACE.InParentNamespace)) def test_mutate_vectorofEnums(self): self.monsterT.vectorOfEnums = [] self.monsterT.vectorOfEnums.append(_COLOR.Color.Red) self.monsterT.vectorOfEnums.append(_COLOR.Color.Blue) self.monsterT.vectorOfEnums.append(_COLOR.Color.Red) monster = self._pack_and_load_buf_class(self.monsterT) self.assertEqual(monster.VectorOfEnums(0), _COLOR.Color.Red) self.assertEqual(monster.VectorOfEnums(1), _COLOR.Color.Blue) self.assertEqual(monster.VectorOfEnums(2), _COLOR.Color.Red) def test_empty_vectorofEnums(self): self.monsterT.vectorOfEnums = [] monster = self._pack_and_load_buf_class(self.monsterT) self.assertFalse(monster.VectorOfEnumsIsNone()) def CheckReadBuffer(buf, offset, sizePrefix=False, file_identifier=None): """ CheckReadBuffer checks that the given buffer is evaluated correctly as the example Monster. """ def asserter(stmt): """ An assertion helper that is separated from TestCase classes. """ if not stmt: raise AssertionError('CheckReadBuffer case failed') if file_identifier: # test prior to removal of size_prefix asserter( util.GetBufferIdentifier(buf, offset, size_prefixed=sizePrefix) == file_identifier) asserter( util.BufferHasIdentifier( buf, offset, file_identifier=file_identifier, size_prefixed=sizePrefix)) asserter( _MONSTER.Monster.MonsterBufferHasIdentifier( buf, offset, size_prefixed=sizePrefix)) if sizePrefix: size = util.GetSizePrefix(buf, offset) asserter(size == len(buf[offset:]) - 4) buf, offset = util.RemoveSizePrefix(buf, offset) if file_identifier: asserter(_MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset)) else: asserter(not _MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset)) monster = _MONSTER.Monster.GetRootAs(buf, offset) asserter(monster.Hp() == 80) asserter(monster.Mana() == 150) asserter(monster.Name() == b'MyMonster') # initialize a Vec3 from Pos() vec = monster.Pos() asserter(vec is not None) # verify the properties of the Vec3 asserter(vec.X() == 1.0) asserter(vec.Y() == 2.0) asserter(vec.Z() == 3.0) asserter(vec.Test1() == 3.0) asserter(vec.Test2() == 2) # initialize a Test from Test3(...) t = _TEST.Test() t = vec.Test3(t) asserter(t is not None) # verify the properties of the Test asserter(t.A() == 5) asserter(t.B() == 6) # verify that the enum code matches the enum declaration: union_type = _ANY.Any asserter(monster.TestType() == union_type.Monster) # initialize a Table from a union field Test(...) table2 = monster.Test() asserter(type(table2) is flatbuffers.table.Table) # initialize a Monster from the Table from the union monster2 = _MONSTER.Monster() monster2.Init(table2.Bytes, table2.Pos) asserter(monster2.Name() == b'Fred') # iterate through the first monster's inventory: asserter(monster.InventoryLength() == 5) asserter(not monster.InventoryIsNone()) invsum = 0 for i in compat_range(monster.InventoryLength()): v = monster.Inventory(i) invsum += int(v) asserter(invsum == 10) for i in range(5): asserter(monster.VectorOfLongs(i) == 10**(i * 2)) asserter(not monster.VectorOfDoublesIsNone()) asserter(([-1.7976931348623157e+308, 0, 1.7976931348623157e+308] == [ monster.VectorOfDoubles(i) for i in range(monster.VectorOfDoublesLength()) ])) try: # if numpy exists, then we should be able to get the # vector as a numpy array import numpy as np asserter(monster.InventoryAsNumpy().sum() == 10) asserter(monster.InventoryAsNumpy().dtype == np.dtype(' ' ' ' '\n' % sys.argv[0]) sys.stderr.write(' Provide COMPARE_GENERATED_TO_GO=1 to check' 'for bytewise comparison to Go data.\n') sys.stderr.write(' Provide COMPARE_GENERATED_TO_JAVA=1 to check' 'for bytewise comparison to Java data.\n') sys.stderr.flush() sys.exit(1) kwargs = dict(argv=sys.argv[:-4]) create_namespace_shortcut(sys.argv[4].lower() == 'true') # show whether numpy is present, as it changes the test logic: try: import numpy print('numpy available') except ImportError: print('numpy not available') # run tests, and run some language comparison checks if needed: success = backward_compatible_run_tests(**kwargs) if success and os.environ.get('COMPARE_GENERATED_TO_GO', 0) == '1': success = success and CheckAgainstGoldDataGo() if success and os.environ.get('COMPARE_GENERATED_TO_JAVA', 0) == '1': success = success and CheckAgainstGoldDataJava() if not success: sys.stderr.write('Tests failed, skipping benchmarks.\n') sys.stderr.flush() sys.exit(1) # run benchmarks (if 0, they will be a noop): bench_vtable = int(sys.argv[1]) bench_traverse = int(sys.argv[2]) bench_build = int(sys.argv[3]) if bench_vtable: BenchmarkVtableDeduplication(bench_vtable) if bench_traverse: buf, off = make_monster_from_generated_code() BenchmarkCheckReadBuffer(bench_traverse, buf, off) if bench_build: buf, off = make_monster_from_generated_code() BenchmarkMakeMonsterFromGeneratedCode(bench_build, len(buf)) if __name__ == '__main__': main()