Austin Schuh | e89fa2d | 2019-08-14 20:24:23 -0700 | [diff] [blame] | 1 | # coding=utf-8 |
| 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 | import os.path |
| 17 | import sys |
| 18 | import imp |
| 19 | PY_VERSION = sys.version_info[:2] |
| 20 | |
| 21 | import ctypes |
| 22 | from collections import defaultdict |
| 23 | import math |
| 24 | import random |
| 25 | import timeit |
| 26 | import unittest |
| 27 | |
| 28 | from flatbuffers import compat |
| 29 | from flatbuffers import util |
| 30 | from flatbuffers.compat import range_func as compat_range |
| 31 | from flatbuffers.compat import NumpyRequiredForThisFeature |
| 32 | |
| 33 | import flatbuffers |
| 34 | from flatbuffers import number_types as N |
| 35 | |
| 36 | import MyGame # refers to generated code |
| 37 | import MyGame.Example # refers to generated code |
| 38 | import MyGame.Example.Any # refers to generated code |
| 39 | import MyGame.Example.Color # refers to generated code |
| 40 | import MyGame.Example.Monster # refers to generated code |
| 41 | import MyGame.Example.Test # refers to generated code |
| 42 | import MyGame.Example.Stat # refers to generated code |
| 43 | import MyGame.Example.Vec3 # refers to generated code |
| 44 | import MyGame.MonsterExtra # refers to generated code |
| 45 | import MyGame.Example.ArrayTable # refers to generated code |
| 46 | import MyGame.Example.ArrayStruct # refers to generated code |
| 47 | import MyGame.Example.NestedStruct # refers to generated code |
| 48 | import MyGame.Example.TestEnum # refers to generated code |
| 49 | |
| 50 | def assertRaises(test_case, fn, exception_class): |
| 51 | ''' Backwards-compatible assertion for exceptions raised. ''' |
| 52 | |
| 53 | exc = None |
| 54 | try: |
| 55 | fn() |
| 56 | except Exception as e: |
| 57 | exc = e |
| 58 | test_case.assertTrue(exc is not None) |
| 59 | test_case.assertTrue(isinstance(exc, exception_class)) |
| 60 | |
| 61 | |
| 62 | class TestWireFormat(unittest.TestCase): |
| 63 | def test_wire_format(self): |
| 64 | # Verify that using the generated Python code builds a buffer without |
| 65 | # returning errors, and is interpreted correctly, for size prefixed |
| 66 | # representation and regular: |
| 67 | for sizePrefix in [True, False]: |
| 68 | for file_identifier in [None, b"MONS"]: |
| 69 | gen_buf, gen_off = make_monster_from_generated_code(sizePrefix=sizePrefix, file_identifier=file_identifier) |
| 70 | CheckReadBuffer(gen_buf, gen_off, sizePrefix=sizePrefix, file_identifier=file_identifier) |
| 71 | |
| 72 | # Verify that the canonical flatbuffer file is readable by the |
| 73 | # generated Python code. Note that context managers are not part of |
| 74 | # Python 2.5, so we use the simpler open/close methods here: |
| 75 | f = open('monsterdata_test.mon', 'rb') |
| 76 | canonicalWireData = f.read() |
| 77 | f.close() |
| 78 | CheckReadBuffer(bytearray(canonicalWireData), 0, file_identifier=b'MONS') |
| 79 | |
| 80 | # Write the generated buffer out to a file: |
| 81 | f = open('monsterdata_python_wire.mon', 'wb') |
| 82 | f.write(gen_buf[gen_off:]) |
| 83 | f.close() |
| 84 | |
| 85 | |
| 86 | def CheckReadBuffer(buf, offset, sizePrefix=False, file_identifier=None): |
| 87 | ''' CheckReadBuffer checks that the given buffer is evaluated correctly |
| 88 | as the example Monster. ''' |
| 89 | |
| 90 | def asserter(stmt): |
| 91 | ''' An assertion helper that is separated from TestCase classes. ''' |
| 92 | if not stmt: |
| 93 | raise AssertionError('CheckReadBuffer case failed') |
| 94 | if file_identifier: |
| 95 | # test prior to removal of size_prefix |
| 96 | asserter(util.GetBufferIdentifier(buf, offset, size_prefixed=sizePrefix) == file_identifier) |
| 97 | asserter(util.BufferHasIdentifier(buf, offset, file_identifier=file_identifier, size_prefixed=sizePrefix)) |
| 98 | if sizePrefix: |
| 99 | size = util.GetSizePrefix(buf, offset) |
| 100 | asserter(size == len(buf[offset:])-4) |
| 101 | buf, offset = util.RemoveSizePrefix(buf, offset) |
| 102 | if file_identifier: |
| 103 | asserter(MyGame.Example.Monster.Monster.MonsterBufferHasIdentifier(buf, offset)) |
| 104 | else: |
| 105 | asserter(not MyGame.Example.Monster.Monster.MonsterBufferHasIdentifier(buf, offset)) |
| 106 | monster = MyGame.Example.Monster.Monster.GetRootAsMonster(buf, offset) |
| 107 | |
| 108 | asserter(monster.Hp() == 80) |
| 109 | asserter(monster.Mana() == 150) |
| 110 | asserter(monster.Name() == b'MyMonster') |
| 111 | |
| 112 | # initialize a Vec3 from Pos() |
| 113 | vec = monster.Pos() |
| 114 | asserter(vec is not None) |
| 115 | |
| 116 | # verify the properties of the Vec3 |
| 117 | asserter(vec.X() == 1.0) |
| 118 | asserter(vec.Y() == 2.0) |
| 119 | asserter(vec.Z() == 3.0) |
| 120 | asserter(vec.Test1() == 3.0) |
| 121 | asserter(vec.Test2() == 2) |
| 122 | |
| 123 | # initialize a Test from Test3(...) |
| 124 | t = MyGame.Example.Test.Test() |
| 125 | t = vec.Test3(t) |
| 126 | asserter(t is not None) |
| 127 | |
| 128 | # verify the properties of the Test |
| 129 | asserter(t.A() == 5) |
| 130 | asserter(t.B() == 6) |
| 131 | |
| 132 | # verify that the enum code matches the enum declaration: |
| 133 | union_type = MyGame.Example.Any.Any |
| 134 | asserter(monster.TestType() == union_type.Monster) |
| 135 | |
| 136 | # initialize a Table from a union field Test(...) |
| 137 | table2 = monster.Test() |
| 138 | asserter(type(table2) is flatbuffers.table.Table) |
| 139 | |
| 140 | # initialize a Monster from the Table from the union |
| 141 | monster2 = MyGame.Example.Monster.Monster() |
| 142 | monster2.Init(table2.Bytes, table2.Pos) |
| 143 | |
| 144 | asserter(monster2.Name() == b"Fred") |
| 145 | |
| 146 | # iterate through the first monster's inventory: |
| 147 | asserter(monster.InventoryLength() == 5) |
| 148 | |
| 149 | invsum = 0 |
| 150 | for i in compat_range(monster.InventoryLength()): |
| 151 | v = monster.Inventory(i) |
| 152 | invsum += int(v) |
| 153 | asserter(invsum == 10) |
| 154 | |
| 155 | for i in range(5): |
| 156 | asserter(monster.VectorOfLongs(i) == 10 ** (i * 2)) |
| 157 | |
| 158 | asserter(([-1.7976931348623157e+308, 0, 1.7976931348623157e+308] |
| 159 | == [monster.VectorOfDoubles(i) |
| 160 | for i in range(monster.VectorOfDoublesLength())])) |
| 161 | |
| 162 | try: |
| 163 | imp.find_module('numpy') |
| 164 | # if numpy exists, then we should be able to get the |
| 165 | # vector as a numpy array |
| 166 | import numpy as np |
| 167 | |
| 168 | asserter(monster.InventoryAsNumpy().sum() == 10) |
| 169 | asserter(monster.InventoryAsNumpy().dtype == np.dtype('uint8')) |
| 170 | |
| 171 | VectorOfLongs = monster.VectorOfLongsAsNumpy() |
| 172 | asserter(VectorOfLongs.dtype == np.dtype('int64')) |
| 173 | for i in range(5): |
| 174 | asserter(VectorOfLongs[i] == 10 ** (i * 2)) |
| 175 | |
| 176 | VectorOfDoubles = monster.VectorOfDoublesAsNumpy() |
| 177 | asserter(VectorOfDoubles.dtype == np.dtype('float64')) |
| 178 | asserter(VectorOfDoubles[0] == np.finfo('float64').min) |
| 179 | asserter(VectorOfDoubles[1] == 0.0) |
| 180 | asserter(VectorOfDoubles[2] == np.finfo('float64').max) |
| 181 | |
| 182 | except ImportError: |
| 183 | # If numpy does not exist, trying to get vector as numpy |
| 184 | # array should raise NumpyRequiredForThisFeature. The way |
| 185 | # assertRaises has been implemented prevents us from |
| 186 | # asserting this error is raised outside of a test case. |
| 187 | pass |
| 188 | |
| 189 | asserter(monster.Test4Length() == 2) |
| 190 | |
| 191 | # create a 'Test' object and populate it: |
| 192 | test0 = monster.Test4(0) |
| 193 | asserter(type(test0) is MyGame.Example.Test.Test) |
| 194 | |
| 195 | test1 = monster.Test4(1) |
| 196 | asserter(type(test1) is MyGame.Example.Test.Test) |
| 197 | |
| 198 | # the position of test0 and test1 are swapped in monsterdata_java_wire |
| 199 | # and monsterdata_test_wire, so ignore ordering |
| 200 | v0 = test0.A() |
| 201 | v1 = test0.B() |
| 202 | v2 = test1.A() |
| 203 | v3 = test1.B() |
| 204 | sumtest12 = int(v0) + int(v1) + int(v2) + int(v3) |
| 205 | |
| 206 | asserter(sumtest12 == 100) |
| 207 | |
| 208 | asserter(monster.TestarrayofstringLength() == 2) |
| 209 | asserter(monster.Testarrayofstring(0) == b"test1") |
| 210 | asserter(monster.Testarrayofstring(1) == b"test2") |
| 211 | |
| 212 | asserter(monster.TestarrayoftablesLength() == 0) |
| 213 | asserter(monster.TestnestedflatbufferLength() == 0) |
| 214 | asserter(monster.Testempty() is None) |
| 215 | |
| 216 | |
| 217 | class TestFuzz(unittest.TestCase): |
| 218 | ''' Low level stress/fuzz test: serialize/deserialize a variety of |
| 219 | different kinds of data in different combinations ''' |
| 220 | |
| 221 | binary_type = compat.binary_types[0] # this will always exist |
| 222 | ofInt32Bytes = binary_type([0x83, 0x33, 0x33, 0x33]) |
| 223 | ofInt64Bytes = binary_type([0x84, 0x44, 0x44, 0x44, |
| 224 | 0x44, 0x44, 0x44, 0x44]) |
| 225 | overflowingInt32Val = flatbuffers.encode.Get(flatbuffers.packer.int32, |
| 226 | ofInt32Bytes, 0) |
| 227 | overflowingInt64Val = flatbuffers.encode.Get(flatbuffers.packer.int64, |
| 228 | ofInt64Bytes, 0) |
| 229 | |
| 230 | # Values we're testing against: chosen to ensure no bits get chopped |
| 231 | # off anywhere, and also be different from eachother. |
| 232 | boolVal = True |
| 233 | int8Val = N.Int8Flags.py_type(-127) # 0x81 |
| 234 | uint8Val = N.Uint8Flags.py_type(0xFF) |
| 235 | int16Val = N.Int16Flags.py_type(-32222) # 0x8222 |
| 236 | uint16Val = N.Uint16Flags.py_type(0xFEEE) |
| 237 | int32Val = N.Int32Flags.py_type(overflowingInt32Val) |
| 238 | uint32Val = N.Uint32Flags.py_type(0xFDDDDDDD) |
| 239 | int64Val = N.Int64Flags.py_type(overflowingInt64Val) |
| 240 | uint64Val = N.Uint64Flags.py_type(0xFCCCCCCCCCCCCCCC) |
| 241 | # Python uses doubles, so force it here |
| 242 | float32Val = N.Float32Flags.py_type(ctypes.c_float(3.14159).value) |
| 243 | float64Val = N.Float64Flags.py_type(3.14159265359) |
| 244 | |
| 245 | def test_fuzz(self): |
| 246 | return self.check_once(11, 100) |
| 247 | |
| 248 | def check_once(self, fuzzFields, fuzzObjects): |
| 249 | testValuesMax = 11 # hardcoded to the number of scalar types |
| 250 | |
| 251 | builder = flatbuffers.Builder(0) |
| 252 | l = LCG() |
| 253 | |
| 254 | objects = [0 for _ in compat_range(fuzzObjects)] |
| 255 | |
| 256 | # Generate fuzzObjects random objects each consisting of |
| 257 | # fuzzFields fields, each of a random type. |
| 258 | for i in compat_range(fuzzObjects): |
| 259 | builder.StartObject(fuzzFields) |
| 260 | |
| 261 | for j in compat_range(fuzzFields): |
| 262 | choice = int(l.Next()) % testValuesMax |
| 263 | if choice == 0: |
| 264 | builder.PrependBoolSlot(int(j), self.boolVal, False) |
| 265 | elif choice == 1: |
| 266 | builder.PrependInt8Slot(int(j), self.int8Val, 0) |
| 267 | elif choice == 2: |
| 268 | builder.PrependUint8Slot(int(j), self.uint8Val, 0) |
| 269 | elif choice == 3: |
| 270 | builder.PrependInt16Slot(int(j), self.int16Val, 0) |
| 271 | elif choice == 4: |
| 272 | builder.PrependUint16Slot(int(j), self.uint16Val, 0) |
| 273 | elif choice == 5: |
| 274 | builder.PrependInt32Slot(int(j), self.int32Val, 0) |
| 275 | elif choice == 6: |
| 276 | builder.PrependUint32Slot(int(j), self.uint32Val, 0) |
| 277 | elif choice == 7: |
| 278 | builder.PrependInt64Slot(int(j), self.int64Val, 0) |
| 279 | elif choice == 8: |
| 280 | builder.PrependUint64Slot(int(j), self.uint64Val, 0) |
| 281 | elif choice == 9: |
| 282 | builder.PrependFloat32Slot(int(j), self.float32Val, 0) |
| 283 | elif choice == 10: |
| 284 | builder.PrependFloat64Slot(int(j), self.float64Val, 0) |
| 285 | else: |
| 286 | raise RuntimeError('unreachable') |
| 287 | |
| 288 | off = builder.EndObject() |
| 289 | |
| 290 | # store the offset from the end of the builder buffer, |
| 291 | # since it will keep growing: |
| 292 | objects[i] = off |
| 293 | |
| 294 | # Do some bookkeeping to generate stats on fuzzes: |
| 295 | stats = defaultdict(int) |
| 296 | def check(table, desc, want, got): |
| 297 | stats[desc] += 1 |
| 298 | self.assertEqual(want, got, "%s != %s, %s" % (want, got, desc)) |
| 299 | |
| 300 | l = LCG() # Reset. |
| 301 | |
| 302 | # Test that all objects we generated are readable and return the |
| 303 | # expected values. We generate random objects in the same order |
| 304 | # so this is deterministic. |
| 305 | for i in compat_range(fuzzObjects): |
| 306 | |
| 307 | table = flatbuffers.table.Table(builder.Bytes, |
| 308 | len(builder.Bytes) - objects[i]) |
| 309 | |
| 310 | for j in compat_range(fuzzFields): |
| 311 | field_count = flatbuffers.builder.VtableMetadataFields + j |
| 312 | f = N.VOffsetTFlags.py_type(field_count * |
| 313 | N.VOffsetTFlags.bytewidth) |
| 314 | choice = int(l.Next()) % testValuesMax |
| 315 | |
| 316 | if choice == 0: |
| 317 | check(table, "bool", self.boolVal, |
| 318 | table.GetSlot(f, False, N.BoolFlags)) |
| 319 | elif choice == 1: |
| 320 | check(table, "int8", self.int8Val, |
| 321 | table.GetSlot(f, 0, N.Int8Flags)) |
| 322 | elif choice == 2: |
| 323 | check(table, "uint8", self.uint8Val, |
| 324 | table.GetSlot(f, 0, N.Uint8Flags)) |
| 325 | elif choice == 3: |
| 326 | check(table, "int16", self.int16Val, |
| 327 | table.GetSlot(f, 0, N.Int16Flags)) |
| 328 | elif choice == 4: |
| 329 | check(table, "uint16", self.uint16Val, |
| 330 | table.GetSlot(f, 0, N.Uint16Flags)) |
| 331 | elif choice == 5: |
| 332 | check(table, "int32", self.int32Val, |
| 333 | table.GetSlot(f, 0, N.Int32Flags)) |
| 334 | elif choice == 6: |
| 335 | check(table, "uint32", self.uint32Val, |
| 336 | table.GetSlot(f, 0, N.Uint32Flags)) |
| 337 | elif choice == 7: |
| 338 | check(table, "int64", self.int64Val, |
| 339 | table.GetSlot(f, 0, N.Int64Flags)) |
| 340 | elif choice == 8: |
| 341 | check(table, "uint64", self.uint64Val, |
| 342 | table.GetSlot(f, 0, N.Uint64Flags)) |
| 343 | elif choice == 9: |
| 344 | check(table, "float32", self.float32Val, |
| 345 | table.GetSlot(f, 0, N.Float32Flags)) |
| 346 | elif choice == 10: |
| 347 | check(table, "float64", self.float64Val, |
| 348 | table.GetSlot(f, 0, N.Float64Flags)) |
| 349 | else: |
| 350 | raise RuntimeError('unreachable') |
| 351 | |
| 352 | # If enough checks were made, verify that all scalar types were used: |
| 353 | self.assertEqual(testValuesMax, len(stats), |
| 354 | "fuzzing failed to test all scalar types: %s" % stats) |
| 355 | |
| 356 | |
| 357 | class TestByteLayout(unittest.TestCase): |
| 358 | ''' TestByteLayout checks the bytes of a Builder in various scenarios. ''' |
| 359 | |
| 360 | def assertBuilderEquals(self, builder, want_chars_or_ints): |
| 361 | def integerize(x): |
| 362 | if isinstance(x, compat.string_types): |
| 363 | return ord(x) |
| 364 | return x |
| 365 | |
| 366 | want_ints = list(map(integerize, want_chars_or_ints)) |
| 367 | want = bytearray(want_ints) |
| 368 | got = builder.Bytes[builder.Head():] # use the buffer directly |
| 369 | self.assertEqual(want, got) |
| 370 | |
| 371 | def test_numbers(self): |
| 372 | b = flatbuffers.Builder(0) |
| 373 | self.assertBuilderEquals(b, []) |
| 374 | b.PrependBool(True) |
| 375 | self.assertBuilderEquals(b, [1]) |
| 376 | b.PrependInt8(-127) |
| 377 | self.assertBuilderEquals(b, [129, 1]) |
| 378 | b.PrependUint8(255) |
| 379 | self.assertBuilderEquals(b, [255, 129, 1]) |
| 380 | b.PrependInt16(-32222) |
| 381 | self.assertBuilderEquals(b, [0x22, 0x82, 0, 255, 129, 1]) # first pad |
| 382 | b.PrependUint16(0xFEEE) |
| 383 | # no pad this time: |
| 384 | self.assertBuilderEquals(b, [0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]) |
| 385 | b.PrependInt32(-53687092) |
| 386 | self.assertBuilderEquals(b, [204, 204, 204, 252, 0xEE, 0xFE, |
| 387 | 0x22, 0x82, 0, 255, 129, 1]) |
| 388 | b.PrependUint32(0x98765432) |
| 389 | self.assertBuilderEquals(b, [0x32, 0x54, 0x76, 0x98, |
| 390 | 204, 204, 204, 252, |
| 391 | 0xEE, 0xFE, 0x22, 0x82, |
| 392 | 0, 255, 129, 1]) |
| 393 | |
| 394 | def test_numbers64(self): |
| 395 | b = flatbuffers.Builder(0) |
| 396 | b.PrependUint64(0x1122334455667788) |
| 397 | self.assertBuilderEquals(b, [0x88, 0x77, 0x66, 0x55, |
| 398 | 0x44, 0x33, 0x22, 0x11]) |
| 399 | |
| 400 | b = flatbuffers.Builder(0) |
| 401 | b.PrependInt64(0x1122334455667788) |
| 402 | self.assertBuilderEquals(b, [0x88, 0x77, 0x66, 0x55, |
| 403 | 0x44, 0x33, 0x22, 0x11]) |
| 404 | |
| 405 | def test_1xbyte_vector(self): |
| 406 | b = flatbuffers.Builder(0) |
| 407 | self.assertBuilderEquals(b, []) |
| 408 | b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 1, 1) |
| 409 | self.assertBuilderEquals(b, [0, 0, 0]) # align to 4bytes |
| 410 | b.PrependByte(1) |
| 411 | self.assertBuilderEquals(b, [1, 0, 0, 0]) |
| 412 | b.EndVector(1) |
| 413 | self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding |
| 414 | |
| 415 | def test_2xbyte_vector(self): |
| 416 | b = flatbuffers.Builder(0) |
| 417 | b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 2, 1) |
| 418 | self.assertBuilderEquals(b, [0, 0]) # align to 4bytes |
| 419 | b.PrependByte(1) |
| 420 | self.assertBuilderEquals(b, [1, 0, 0]) |
| 421 | b.PrependByte(2) |
| 422 | self.assertBuilderEquals(b, [2, 1, 0, 0]) |
| 423 | b.EndVector(2) |
| 424 | self.assertBuilderEquals(b, [2, 0, 0, 0, 2, 1, 0, 0]) # padding |
| 425 | |
| 426 | def test_1xuint16_vector(self): |
| 427 | b = flatbuffers.Builder(0) |
| 428 | b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 1, 1) |
| 429 | self.assertBuilderEquals(b, [0, 0]) # align to 4bytes |
| 430 | b.PrependUint16(1) |
| 431 | self.assertBuilderEquals(b, [1, 0, 0, 0]) |
| 432 | b.EndVector(1) |
| 433 | self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding |
| 434 | |
| 435 | def test_2xuint16_vector(self): |
| 436 | b = flatbuffers.Builder(0) |
| 437 | b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 2, 1) |
| 438 | self.assertBuilderEquals(b, []) # align to 4bytes |
| 439 | b.PrependUint16(0xABCD) |
| 440 | self.assertBuilderEquals(b, [0xCD, 0xAB]) |
| 441 | b.PrependUint16(0xDCBA) |
| 442 | self.assertBuilderEquals(b, [0xBA, 0xDC, 0xCD, 0xAB]) |
| 443 | b.EndVector(2) |
| 444 | self.assertBuilderEquals(b, [2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB]) |
| 445 | |
| 446 | def test_create_ascii_string(self): |
| 447 | b = flatbuffers.Builder(0) |
| 448 | b.CreateString(u"foo", encoding='ascii') |
| 449 | |
| 450 | # 0-terminated, no pad: |
| 451 | self.assertBuilderEquals(b, [3, 0, 0, 0, 'f', 'o', 'o', 0]) |
| 452 | b.CreateString(u"moop", encoding='ascii') |
| 453 | # 0-terminated, 3-byte pad: |
| 454 | self.assertBuilderEquals(b, [4, 0, 0, 0, 'm', 'o', 'o', 'p', |
| 455 | 0, 0, 0, 0, |
| 456 | 3, 0, 0, 0, 'f', 'o', 'o', 0]) |
| 457 | |
| 458 | def test_create_utf8_string(self): |
| 459 | b = flatbuffers.Builder(0) |
| 460 | b.CreateString(u"Цлїςσδε") |
| 461 | self.assertBuilderEquals(b, "\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97" \ |
| 462 | "\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00") |
| 463 | |
| 464 | b.CreateString(u"フムアムカモケモ") |
| 465 | self.assertBuilderEquals(b, "\x18\x00\x00\x00\xef\xbe\x8c\xef\xbe\x91" \ |
| 466 | "\xef\xbd\xb1\xef\xbe\x91\xef\xbd\xb6\xef\xbe\x93\xef\xbd\xb9\xef" \ |
| 467 | "\xbe\x93\x00\x00\x00\x00\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97" \ |
| 468 | "\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00") |
| 469 | |
| 470 | def test_create_arbitrary_string(self): |
| 471 | b = flatbuffers.Builder(0) |
| 472 | s = "\x01\x02\x03" |
| 473 | b.CreateString(s) # Default encoding is utf-8. |
| 474 | # 0-terminated, no pad: |
| 475 | self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0]) |
| 476 | s2 = "\x04\x05\x06\x07" |
| 477 | b.CreateString(s2) # Default encoding is utf-8. |
| 478 | # 0-terminated, 3-byte pad: |
| 479 | self.assertBuilderEquals(b, [4, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0, |
| 480 | 3, 0, 0, 0, 1, 2, 3, 0]) |
| 481 | |
| 482 | def test_create_byte_vector(self): |
| 483 | b = flatbuffers.Builder(0) |
| 484 | b.CreateByteVector(b"") |
| 485 | # 0-byte pad: |
| 486 | self.assertBuilderEquals(b, [0, 0, 0, 0]) |
| 487 | |
| 488 | b = flatbuffers.Builder(0) |
| 489 | b.CreateByteVector(b"\x01\x02\x03") |
| 490 | # 1-byte pad: |
| 491 | self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0]) |
| 492 | |
| 493 | def test_create_numpy_vector_int8(self): |
| 494 | try: |
| 495 | imp.find_module('numpy') |
| 496 | # if numpy exists, then we should be able to get the |
| 497 | # vector as a numpy array |
| 498 | import numpy as np |
| 499 | |
| 500 | # Systems endian: |
| 501 | b = flatbuffers.Builder(0) |
| 502 | x = np.array([1, 2, -3], dtype=np.int8) |
| 503 | b.CreateNumpyVector(x) |
| 504 | self.assertBuilderEquals(b, [ |
| 505 | 3, 0, 0, 0, # vector length |
| 506 | 1, 2, 256 - 3, 0 # vector value + padding |
| 507 | ]) |
| 508 | |
| 509 | # Reverse endian: |
| 510 | b = flatbuffers.Builder(0) |
| 511 | x_other_endian = x.byteswap().newbyteorder() |
| 512 | b.CreateNumpyVector(x_other_endian) |
| 513 | self.assertBuilderEquals(b, [ |
| 514 | 3, 0, 0, 0, # vector length |
| 515 | 1, 2, 256 - 3, 0 # vector value + padding |
| 516 | ]) |
| 517 | except ImportError: |
| 518 | b = flatbuffers.Builder(0) |
| 519 | x = 0 |
| 520 | assertRaises( |
| 521 | self, |
| 522 | lambda: b.CreateNumpyVector(x), |
| 523 | NumpyRequiredForThisFeature) |
| 524 | |
| 525 | def test_create_numpy_vector_uint16(self): |
| 526 | try: |
| 527 | imp.find_module('numpy') |
| 528 | # if numpy exists, then we should be able to get the |
| 529 | # vector as a numpy array |
| 530 | import numpy as np |
| 531 | |
| 532 | # Systems endian: |
| 533 | b = flatbuffers.Builder(0) |
| 534 | x = np.array([1, 2, 312], dtype=np.uint16) |
| 535 | b.CreateNumpyVector(x) |
| 536 | self.assertBuilderEquals(b, [ |
| 537 | 3, 0, 0, 0, # vector length |
| 538 | 1, 0, # 1 |
| 539 | 2, 0, # 2 |
| 540 | 312 - 256, 1, # 312 |
| 541 | 0, 0 # padding |
| 542 | ]) |
| 543 | |
| 544 | # Reverse endian: |
| 545 | b = flatbuffers.Builder(0) |
| 546 | x_other_endian = x.byteswap().newbyteorder() |
| 547 | b.CreateNumpyVector(x_other_endian) |
| 548 | self.assertBuilderEquals(b, [ |
| 549 | 3, 0, 0, 0, # vector length |
| 550 | 1, 0, # 1 |
| 551 | 2, 0, # 2 |
| 552 | 312 - 256, 1, # 312 |
| 553 | 0, 0 # padding |
| 554 | ]) |
| 555 | except ImportError: |
| 556 | b = flatbuffers.Builder(0) |
| 557 | x = 0 |
| 558 | assertRaises( |
| 559 | self, |
| 560 | lambda: b.CreateNumpyVector(x), |
| 561 | NumpyRequiredForThisFeature) |
| 562 | |
| 563 | def test_create_numpy_vector_int64(self): |
| 564 | try: |
| 565 | imp.find_module('numpy') |
| 566 | # if numpy exists, then we should be able to get the |
| 567 | # vector as a numpy array |
| 568 | import numpy as np |
| 569 | |
| 570 | # Systems endian: |
| 571 | b = flatbuffers.Builder(0) |
| 572 | x = np.array([1, 2, -12], dtype=np.int64) |
| 573 | b.CreateNumpyVector(x) |
| 574 | self.assertBuilderEquals(b, [ |
| 575 | 3, 0, 0, 0, # vector length |
| 576 | 1, 0, 0, 0, 0, 0, 0, 0, # 1 |
| 577 | 2, 0, 0, 0, 0, 0, 0, 0, # 2 |
| 578 | 256 - 12, 255, 255, 255, 255, 255, 255, 255 # -12 |
| 579 | ]) |
| 580 | |
| 581 | # Reverse endian: |
| 582 | b = flatbuffers.Builder(0) |
| 583 | x_other_endian = x.byteswap().newbyteorder() |
| 584 | b.CreateNumpyVector(x_other_endian) |
| 585 | self.assertBuilderEquals(b, [ |
| 586 | 3, 0, 0, 0, # vector length |
| 587 | 1, 0, 0, 0, 0, 0, 0, 0, # 1 |
| 588 | 2, 0, 0, 0, 0, 0, 0, 0, # 2 |
| 589 | 256 - 12, 255, 255, 255, 255, 255, 255, 255 # -12 |
| 590 | ]) |
| 591 | |
| 592 | except ImportError: |
| 593 | b = flatbuffers.Builder(0) |
| 594 | x = 0 |
| 595 | assertRaises( |
| 596 | self, |
| 597 | lambda: b.CreateNumpyVector(x), |
| 598 | NumpyRequiredForThisFeature) |
| 599 | |
| 600 | def test_create_numpy_vector_float32(self): |
| 601 | try: |
| 602 | imp.find_module('numpy') |
| 603 | # if numpy exists, then we should be able to get the |
| 604 | # vector as a numpy array |
| 605 | import numpy as np |
| 606 | |
| 607 | # Systems endian: |
| 608 | b = flatbuffers.Builder(0) |
| 609 | x = np.array([1, 2, -12], dtype=np.float32) |
| 610 | b.CreateNumpyVector(x) |
| 611 | self.assertBuilderEquals(b, [ |
| 612 | 3, 0, 0, 0, # vector length |
| 613 | 0, 0, 128, 63, # 1 |
| 614 | 0, 0, 0, 64, # 2 |
| 615 | 0, 0, 64, 193 # -12 |
| 616 | ]) |
| 617 | |
| 618 | # Reverse endian: |
| 619 | b = flatbuffers.Builder(0) |
| 620 | x_other_endian = x.byteswap().newbyteorder() |
| 621 | b.CreateNumpyVector(x_other_endian) |
| 622 | self.assertBuilderEquals(b, [ |
| 623 | 3, 0, 0, 0, # vector length |
| 624 | 0, 0, 128, 63, # 1 |
| 625 | 0, 0, 0, 64, # 2 |
| 626 | 0, 0, 64, 193 # -12 |
| 627 | ]) |
| 628 | |
| 629 | except ImportError: |
| 630 | b = flatbuffers.Builder(0) |
| 631 | x = 0 |
| 632 | assertRaises( |
| 633 | self, |
| 634 | lambda: b.CreateNumpyVector(x), |
| 635 | NumpyRequiredForThisFeature) |
| 636 | |
| 637 | def test_create_numpy_vector_float64(self): |
| 638 | try: |
| 639 | imp.find_module('numpy') |
| 640 | # if numpy exists, then we should be able to get the |
| 641 | # vector as a numpy array |
| 642 | import numpy as np |
| 643 | |
| 644 | # Systems endian: |
| 645 | b = flatbuffers.Builder(0) |
| 646 | x = np.array([1, 2, -12], dtype=np.float64) |
| 647 | b.CreateNumpyVector(x) |
| 648 | self.assertBuilderEquals(b, [ |
| 649 | 3, 0, 0, 0, # vector length |
| 650 | 0, 0, 0, 0, 0, 0, 240, 63, # 1 |
| 651 | 0, 0, 0, 0, 0, 0, 0, 64, # 2 |
| 652 | 0, 0, 0, 0, 0, 0, 40, 192 # -12 |
| 653 | ]) |
| 654 | |
| 655 | # Reverse endian: |
| 656 | b = flatbuffers.Builder(0) |
| 657 | x_other_endian = x.byteswap().newbyteorder() |
| 658 | b.CreateNumpyVector(x_other_endian) |
| 659 | self.assertBuilderEquals(b, [ |
| 660 | 3, 0, 0, 0, # vector length |
| 661 | 0, 0, 0, 0, 0, 0, 240, 63, # 1 |
| 662 | 0, 0, 0, 0, 0, 0, 0, 64, # 2 |
| 663 | 0, 0, 0, 0, 0, 0, 40, 192 # -12 |
| 664 | ]) |
| 665 | |
| 666 | except ImportError: |
| 667 | b = flatbuffers.Builder(0) |
| 668 | x = 0 |
| 669 | assertRaises( |
| 670 | self, |
| 671 | lambda: b.CreateNumpyVector(x), |
| 672 | NumpyRequiredForThisFeature) |
| 673 | |
| 674 | def test_create_numpy_vector_bool(self): |
| 675 | try: |
| 676 | imp.find_module('numpy') |
| 677 | # if numpy exists, then we should be able to get the |
| 678 | # vector as a numpy array |
| 679 | import numpy as np |
| 680 | |
| 681 | # Systems endian: |
| 682 | b = flatbuffers.Builder(0) |
| 683 | x = np.array([True, False, True], dtype=np.bool) |
| 684 | b.CreateNumpyVector(x) |
| 685 | self.assertBuilderEquals(b, [ |
| 686 | 3, 0, 0, 0, # vector length |
| 687 | 1, 0, 1, 0 # vector values + padding |
| 688 | ]) |
| 689 | |
| 690 | # Reverse endian: |
| 691 | b = flatbuffers.Builder(0) |
| 692 | x_other_endian = x.byteswap().newbyteorder() |
| 693 | b.CreateNumpyVector(x_other_endian) |
| 694 | self.assertBuilderEquals(b, [ |
| 695 | 3, 0, 0, 0, # vector length |
| 696 | 1, 0, 1, 0 # vector values + padding |
| 697 | ]) |
| 698 | |
| 699 | except ImportError: |
| 700 | b = flatbuffers.Builder(0) |
| 701 | x = 0 |
| 702 | assertRaises( |
| 703 | self, |
| 704 | lambda: b.CreateNumpyVector(x), |
| 705 | NumpyRequiredForThisFeature) |
| 706 | |
| 707 | def test_create_numpy_vector_reject_strings(self): |
| 708 | try: |
| 709 | imp.find_module('numpy') |
| 710 | # if numpy exists, then we should be able to get the |
| 711 | # vector as a numpy array |
| 712 | import numpy as np |
| 713 | |
| 714 | # Create String array |
| 715 | b = flatbuffers.Builder(0) |
| 716 | x = np.array(["hello", "fb", "testing"]) |
| 717 | assertRaises( |
| 718 | self, |
| 719 | lambda: b.CreateNumpyVector(x), |
| 720 | TypeError) |
| 721 | |
| 722 | except ImportError: |
| 723 | b = flatbuffers.Builder(0) |
| 724 | x = 0 |
| 725 | assertRaises( |
| 726 | self, |
| 727 | lambda: b.CreateNumpyVector(x), |
| 728 | NumpyRequiredForThisFeature) |
| 729 | |
| 730 | def test_create_numpy_vector_reject_object(self): |
| 731 | try: |
| 732 | imp.find_module('numpy') |
| 733 | # if numpy exists, then we should be able to get the |
| 734 | # vector as a numpy array |
| 735 | import numpy as np |
| 736 | |
| 737 | # Create String array |
| 738 | b = flatbuffers.Builder(0) |
| 739 | x = np.array([{"m": 0}, {"as": -2.1, 'c': 'c'}]) |
| 740 | assertRaises( |
| 741 | self, |
| 742 | lambda: b.CreateNumpyVector(x), |
| 743 | TypeError) |
| 744 | |
| 745 | except ImportError: |
| 746 | b = flatbuffers.Builder(0) |
| 747 | x = 0 |
| 748 | assertRaises( |
| 749 | self, |
| 750 | lambda: b.CreateNumpyVector(x), |
| 751 | NumpyRequiredForThisFeature) |
| 752 | |
| 753 | def test_empty_vtable(self): |
| 754 | b = flatbuffers.Builder(0) |
| 755 | b.StartObject(0) |
| 756 | self.assertBuilderEquals(b, []) |
| 757 | b.EndObject() |
| 758 | self.assertBuilderEquals(b, [4, 0, 4, 0, 4, 0, 0, 0]) |
| 759 | |
| 760 | def test_vtable_with_one_true_bool(self): |
| 761 | b = flatbuffers.Builder(0) |
| 762 | self.assertBuilderEquals(b, []) |
| 763 | b.StartObject(1) |
| 764 | self.assertBuilderEquals(b, []) |
| 765 | b.PrependBoolSlot(0, True, False) |
| 766 | b.EndObject() |
| 767 | self.assertBuilderEquals(b, [ |
| 768 | 6, 0, # vtable bytes |
| 769 | 8, 0, # length of object including vtable offset |
| 770 | 7, 0, # start of bool value |
| 771 | 6, 0, 0, 0, # offset for start of vtable (int32) |
| 772 | 0, 0, 0, # padded to 4 bytes |
| 773 | 1, # bool value |
| 774 | ]) |
| 775 | |
| 776 | def test_vtable_with_one_default_bool(self): |
| 777 | b = flatbuffers.Builder(0) |
| 778 | self.assertBuilderEquals(b, []) |
| 779 | b.StartObject(1) |
| 780 | self.assertBuilderEquals(b, []) |
| 781 | b.PrependBoolSlot(0, False, False) |
| 782 | b.EndObject() |
| 783 | self.assertBuilderEquals(b, [ |
| 784 | 4, 0, # vtable bytes |
| 785 | 4, 0, # end of object from here |
| 786 | # entry 1 is zero and not stored |
| 787 | 4, 0, 0, 0, # offset for start of vtable (int32) |
| 788 | ]) |
| 789 | |
| 790 | def test_vtable_with_one_int16(self): |
| 791 | b = flatbuffers.Builder(0) |
| 792 | b.StartObject(1) |
| 793 | b.PrependInt16Slot(0, 0x789A, 0) |
| 794 | b.EndObject() |
| 795 | self.assertBuilderEquals(b, [ |
| 796 | 6, 0, # vtable bytes |
| 797 | 8, 0, # end of object from here |
| 798 | 6, 0, # offset to value |
| 799 | 6, 0, 0, 0, # offset for start of vtable (int32) |
| 800 | 0, 0, # padding to 4 bytes |
| 801 | 0x9A, 0x78, |
| 802 | ]) |
| 803 | |
| 804 | def test_vtable_with_two_int16(self): |
| 805 | b = flatbuffers.Builder(0) |
| 806 | b.StartObject(2) |
| 807 | b.PrependInt16Slot(0, 0x3456, 0) |
| 808 | b.PrependInt16Slot(1, 0x789A, 0) |
| 809 | b.EndObject() |
| 810 | self.assertBuilderEquals(b, [ |
| 811 | 8, 0, # vtable bytes |
| 812 | 8, 0, # end of object from here |
| 813 | 6, 0, # offset to value 0 |
| 814 | 4, 0, # offset to value 1 |
| 815 | 8, 0, 0, 0, # offset for start of vtable (int32) |
| 816 | 0x9A, 0x78, # value 1 |
| 817 | 0x56, 0x34, # value 0 |
| 818 | ]) |
| 819 | |
| 820 | def test_vtable_with_int16_and_bool(self): |
| 821 | b = flatbuffers.Builder(0) |
| 822 | b.StartObject(2) |
| 823 | b.PrependInt16Slot(0, 0x3456, 0) |
| 824 | b.PrependBoolSlot(1, True, False) |
| 825 | b.EndObject() |
| 826 | self.assertBuilderEquals(b, [ |
| 827 | 8, 0, # vtable bytes |
| 828 | 8, 0, # end of object from here |
| 829 | 6, 0, # offset to value 0 |
| 830 | 5, 0, # offset to value 1 |
| 831 | 8, 0, 0, 0, # offset for start of vtable (int32) |
| 832 | 0, # padding |
| 833 | 1, # value 1 |
| 834 | 0x56, 0x34, # value 0 |
| 835 | ]) |
| 836 | |
| 837 | def test_vtable_with_empty_vector(self): |
| 838 | b = flatbuffers.Builder(0) |
| 839 | b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1) |
| 840 | vecend = b.EndVector(0) |
| 841 | b.StartObject(1) |
| 842 | b.PrependUOffsetTRelativeSlot(0, vecend, 0) |
| 843 | b.EndObject() |
| 844 | self.assertBuilderEquals(b, [ |
| 845 | 6, 0, # vtable bytes |
| 846 | 8, 0, |
| 847 | 4, 0, # offset to vector offset |
| 848 | 6, 0, 0, 0, # offset for start of vtable (int32) |
| 849 | 4, 0, 0, 0, |
| 850 | 0, 0, 0, 0, # length of vector (not in struct) |
| 851 | ]) |
| 852 | |
| 853 | def test_vtable_with_empty_vector_of_byte_and_some_scalars(self): |
| 854 | b = flatbuffers.Builder(0) |
| 855 | b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1) |
| 856 | vecend = b.EndVector(0) |
| 857 | b.StartObject(2) |
| 858 | b.PrependInt16Slot(0, 55, 0) |
| 859 | b.PrependUOffsetTRelativeSlot(1, vecend, 0) |
| 860 | b.EndObject() |
| 861 | self.assertBuilderEquals(b, [ |
| 862 | 8, 0, # vtable bytes |
| 863 | 12, 0, |
| 864 | 10, 0, # offset to value 0 |
| 865 | 4, 0, # offset to vector offset |
| 866 | 8, 0, 0, 0, # vtable loc |
| 867 | 8, 0, 0, 0, # value 1 |
| 868 | 0, 0, 55, 0, # value 0 |
| 869 | |
| 870 | 0, 0, 0, 0, # length of vector (not in struct) |
| 871 | ]) |
| 872 | |
| 873 | def test_vtable_with_1_int16_and_2vector_of_int16(self): |
| 874 | b = flatbuffers.Builder(0) |
| 875 | b.StartVector(flatbuffers.number_types.Int16Flags.bytewidth, 2, 1) |
| 876 | b.PrependInt16(0x1234) |
| 877 | b.PrependInt16(0x5678) |
| 878 | vecend = b.EndVector(2) |
| 879 | b.StartObject(2) |
| 880 | b.PrependUOffsetTRelativeSlot(1, vecend, 0) |
| 881 | b.PrependInt16Slot(0, 55, 0) |
| 882 | b.EndObject() |
| 883 | self.assertBuilderEquals(b, [ |
| 884 | 8, 0, # vtable bytes |
| 885 | 12, 0, # length of object |
| 886 | 6, 0, # start of value 0 from end of vtable |
| 887 | 8, 0, # start of value 1 from end of buffer |
| 888 | 8, 0, 0, 0, # offset for start of vtable (int32) |
| 889 | 0, 0, # padding |
| 890 | 55, 0, # value 0 |
| 891 | 4, 0, 0, 0, # vector position from here |
| 892 | 2, 0, 0, 0, # length of vector (uint32) |
| 893 | 0x78, 0x56, # vector value 1 |
| 894 | 0x34, 0x12, # vector value 0 |
| 895 | ]) |
| 896 | |
| 897 | def test_vtable_with_1_struct_of_1_int8__1_int16__1_int32(self): |
| 898 | b = flatbuffers.Builder(0) |
| 899 | b.StartObject(1) |
| 900 | b.Prep(4+4+4, 0) |
| 901 | b.PrependInt8(55) |
| 902 | b.Pad(3) |
| 903 | b.PrependInt16(0x1234) |
| 904 | b.Pad(2) |
| 905 | b.PrependInt32(0x12345678) |
| 906 | structStart = b.Offset() |
| 907 | b.PrependStructSlot(0, structStart, 0) |
| 908 | b.EndObject() |
| 909 | self.assertBuilderEquals(b, [ |
| 910 | 6, 0, # vtable bytes |
| 911 | 16, 0, # end of object from here |
| 912 | 4, 0, # start of struct from here |
| 913 | 6, 0, 0, 0, # offset for start of vtable (int32) |
| 914 | 0x78, 0x56, 0x34, 0x12, # value 2 |
| 915 | 0, 0, # padding |
| 916 | 0x34, 0x12, # value 1 |
| 917 | 0, 0, 0, # padding |
| 918 | 55, # value 0 |
| 919 | ]) |
| 920 | |
| 921 | def test_vtable_with_1_vector_of_2_struct_of_2_int8(self): |
| 922 | b = flatbuffers.Builder(0) |
| 923 | b.StartVector(flatbuffers.number_types.Int8Flags.bytewidth*2, 2, 1) |
| 924 | b.PrependInt8(33) |
| 925 | b.PrependInt8(44) |
| 926 | b.PrependInt8(55) |
| 927 | b.PrependInt8(66) |
| 928 | vecend = b.EndVector(2) |
| 929 | b.StartObject(1) |
| 930 | b.PrependUOffsetTRelativeSlot(0, vecend, 0) |
| 931 | b.EndObject() |
| 932 | self.assertBuilderEquals(b, [ |
| 933 | 6, 0, # vtable bytes |
| 934 | 8, 0, |
| 935 | 4, 0, # offset of vector offset |
| 936 | 6, 0, 0, 0, # offset for start of vtable (int32) |
| 937 | 4, 0, 0, 0, # vector start offset |
| 938 | |
| 939 | 2, 0, 0, 0, # vector length |
| 940 | 66, # vector value 1,1 |
| 941 | 55, # vector value 1,0 |
| 942 | 44, # vector value 0,1 |
| 943 | 33, # vector value 0,0 |
| 944 | ]) |
| 945 | |
| 946 | def test_table_with_some_elements(self): |
| 947 | b = flatbuffers.Builder(0) |
| 948 | b.StartObject(2) |
| 949 | b.PrependInt8Slot(0, 33, 0) |
| 950 | b.PrependInt16Slot(1, 66, 0) |
| 951 | off = b.EndObject() |
| 952 | b.Finish(off) |
| 953 | |
| 954 | self.assertBuilderEquals(b, [ |
| 955 | 12, 0, 0, 0, # root of table: points to vtable offset |
| 956 | |
| 957 | 8, 0, # vtable bytes |
| 958 | 8, 0, # end of object from here |
| 959 | 7, 0, # start of value 0 |
| 960 | 4, 0, # start of value 1 |
| 961 | |
| 962 | 8, 0, 0, 0, # offset for start of vtable (int32) |
| 963 | |
| 964 | 66, 0, # value 1 |
| 965 | 0, # padding |
| 966 | 33, # value 0 |
| 967 | ]) |
| 968 | |
| 969 | def test__one_unfinished_table_and_one_finished_table(self): |
| 970 | b = flatbuffers.Builder(0) |
| 971 | b.StartObject(2) |
| 972 | b.PrependInt8Slot(0, 33, 0) |
| 973 | b.PrependInt8Slot(1, 44, 0) |
| 974 | off = b.EndObject() |
| 975 | b.Finish(off) |
| 976 | |
| 977 | b.StartObject(3) |
| 978 | b.PrependInt8Slot(0, 55, 0) |
| 979 | b.PrependInt8Slot(1, 66, 0) |
| 980 | b.PrependInt8Slot(2, 77, 0) |
| 981 | off = b.EndObject() |
| 982 | b.Finish(off) |
| 983 | |
| 984 | self.assertBuilderEquals(b, [ |
| 985 | 16, 0, 0, 0, # root of table: points to object |
| 986 | 0, 0, # padding |
| 987 | |
| 988 | 10, 0, # vtable bytes |
| 989 | 8, 0, # size of object |
| 990 | 7, 0, # start of value 0 |
| 991 | 6, 0, # start of value 1 |
| 992 | 5, 0, # start of value 2 |
| 993 | 10, 0, 0, 0, # offset for start of vtable (int32) |
| 994 | 0, # padding |
| 995 | 77, # value 2 |
| 996 | 66, # value 1 |
| 997 | 55, # value 0 |
| 998 | |
| 999 | 12, 0, 0, 0, # root of table: points to object |
| 1000 | |
| 1001 | 8, 0, # vtable bytes |
| 1002 | 8, 0, # size of object |
| 1003 | 7, 0, # start of value 0 |
| 1004 | 6, 0, # start of value 1 |
| 1005 | 8, 0, 0, 0, # offset for start of vtable (int32) |
| 1006 | 0, 0, # padding |
| 1007 | 44, # value 1 |
| 1008 | 33, # value 0 |
| 1009 | ]) |
| 1010 | |
| 1011 | def test_a_bunch_of_bools(self): |
| 1012 | b = flatbuffers.Builder(0) |
| 1013 | b.StartObject(8) |
| 1014 | b.PrependBoolSlot(0, True, False) |
| 1015 | b.PrependBoolSlot(1, True, False) |
| 1016 | b.PrependBoolSlot(2, True, False) |
| 1017 | b.PrependBoolSlot(3, True, False) |
| 1018 | b.PrependBoolSlot(4, True, False) |
| 1019 | b.PrependBoolSlot(5, True, False) |
| 1020 | b.PrependBoolSlot(6, True, False) |
| 1021 | b.PrependBoolSlot(7, True, False) |
| 1022 | off = b.EndObject() |
| 1023 | b.Finish(off) |
| 1024 | |
| 1025 | self.assertBuilderEquals(b, [ |
| 1026 | 24, 0, 0, 0, # root of table: points to vtable offset |
| 1027 | |
| 1028 | 20, 0, # vtable bytes |
| 1029 | 12, 0, # size of object |
| 1030 | 11, 0, # start of value 0 |
| 1031 | 10, 0, # start of value 1 |
| 1032 | 9, 0, # start of value 2 |
| 1033 | 8, 0, # start of value 3 |
| 1034 | 7, 0, # start of value 4 |
| 1035 | 6, 0, # start of value 5 |
| 1036 | 5, 0, # start of value 6 |
| 1037 | 4, 0, # start of value 7 |
| 1038 | 20, 0, 0, 0, # vtable offset |
| 1039 | |
| 1040 | 1, # value 7 |
| 1041 | 1, # value 6 |
| 1042 | 1, # value 5 |
| 1043 | 1, # value 4 |
| 1044 | 1, # value 3 |
| 1045 | 1, # value 2 |
| 1046 | 1, # value 1 |
| 1047 | 1, # value 0 |
| 1048 | ]) |
| 1049 | |
| 1050 | def test_three_bools(self): |
| 1051 | b = flatbuffers.Builder(0) |
| 1052 | b.StartObject(3) |
| 1053 | b.PrependBoolSlot(0, True, False) |
| 1054 | b.PrependBoolSlot(1, True, False) |
| 1055 | b.PrependBoolSlot(2, True, False) |
| 1056 | off = b.EndObject() |
| 1057 | b.Finish(off) |
| 1058 | |
| 1059 | self.assertBuilderEquals(b, [ |
| 1060 | 16, 0, 0, 0, # root of table: points to vtable offset |
| 1061 | |
| 1062 | 0, 0, # padding |
| 1063 | |
| 1064 | 10, 0, # vtable bytes |
| 1065 | 8, 0, # size of object |
| 1066 | 7, 0, # start of value 0 |
| 1067 | 6, 0, # start of value 1 |
| 1068 | 5, 0, # start of value 2 |
| 1069 | 10, 0, 0, 0, # vtable offset from here |
| 1070 | |
| 1071 | 0, # padding |
| 1072 | 1, # value 2 |
| 1073 | 1, # value 1 |
| 1074 | 1, # value 0 |
| 1075 | ]) |
| 1076 | |
| 1077 | def test_some_floats(self): |
| 1078 | b = flatbuffers.Builder(0) |
| 1079 | b.StartObject(1) |
| 1080 | b.PrependFloat32Slot(0, 1.0, 0.0) |
| 1081 | off = b.EndObject() |
| 1082 | |
| 1083 | self.assertBuilderEquals(b, [ |
| 1084 | 6, 0, # vtable bytes |
| 1085 | 8, 0, # size of object |
| 1086 | 4, 0, # start of value 0 |
| 1087 | 6, 0, 0, 0, # vtable offset |
| 1088 | |
| 1089 | 0, 0, 128, 63, # value 0 |
| 1090 | ]) |
| 1091 | |
| 1092 | |
| 1093 | def make_monster_from_generated_code(sizePrefix = False, file_identifier=None): |
| 1094 | ''' Use generated code to build the example Monster. ''' |
| 1095 | |
| 1096 | b = flatbuffers.Builder(0) |
| 1097 | string = b.CreateString("MyMonster") |
| 1098 | test1 = b.CreateString("test1") |
| 1099 | test2 = b.CreateString("test2") |
| 1100 | fred = b.CreateString("Fred") |
| 1101 | |
| 1102 | MyGame.Example.Monster.MonsterStartInventoryVector(b, 5) |
| 1103 | b.PrependByte(4) |
| 1104 | b.PrependByte(3) |
| 1105 | b.PrependByte(2) |
| 1106 | b.PrependByte(1) |
| 1107 | b.PrependByte(0) |
| 1108 | inv = b.EndVector(5) |
| 1109 | |
| 1110 | MyGame.Example.Monster.MonsterStart(b) |
| 1111 | MyGame.Example.Monster.MonsterAddName(b, fred) |
| 1112 | mon2 = MyGame.Example.Monster.MonsterEnd(b) |
| 1113 | |
| 1114 | MyGame.Example.Monster.MonsterStartTest4Vector(b, 2) |
| 1115 | MyGame.Example.Test.CreateTest(b, 10, 20) |
| 1116 | MyGame.Example.Test.CreateTest(b, 30, 40) |
| 1117 | test4 = b.EndVector(2) |
| 1118 | |
| 1119 | MyGame.Example.Monster.MonsterStartTestarrayofstringVector(b, 2) |
| 1120 | b.PrependUOffsetTRelative(test2) |
| 1121 | b.PrependUOffsetTRelative(test1) |
| 1122 | testArrayOfString = b.EndVector(2) |
| 1123 | |
| 1124 | MyGame.Example.Monster.MonsterStartVectorOfLongsVector(b, 5) |
| 1125 | b.PrependInt64(100000000) |
| 1126 | b.PrependInt64(1000000) |
| 1127 | b.PrependInt64(10000) |
| 1128 | b.PrependInt64(100) |
| 1129 | b.PrependInt64(1) |
| 1130 | VectorOfLongs = b.EndVector(5) |
| 1131 | |
| 1132 | MyGame.Example.Monster.MonsterStartVectorOfDoublesVector(b, 3) |
| 1133 | b.PrependFloat64(1.7976931348623157e+308) |
| 1134 | b.PrependFloat64(0) |
| 1135 | b.PrependFloat64(-1.7976931348623157e+308) |
| 1136 | VectorOfDoubles = b.EndVector(3) |
| 1137 | |
| 1138 | MyGame.Example.Monster.MonsterStart(b) |
| 1139 | |
| 1140 | pos = MyGame.Example.Vec3.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, 2, 5, 6) |
| 1141 | MyGame.Example.Monster.MonsterAddPos(b, pos) |
| 1142 | |
| 1143 | MyGame.Example.Monster.MonsterAddHp(b, 80) |
| 1144 | MyGame.Example.Monster.MonsterAddName(b, string) |
| 1145 | MyGame.Example.Monster.MonsterAddInventory(b, inv) |
| 1146 | MyGame.Example.Monster.MonsterAddTestType(b, 1) |
| 1147 | MyGame.Example.Monster.MonsterAddTest(b, mon2) |
| 1148 | MyGame.Example.Monster.MonsterAddTest4(b, test4) |
| 1149 | MyGame.Example.Monster.MonsterAddTestarrayofstring(b, testArrayOfString) |
| 1150 | MyGame.Example.Monster.MonsterAddVectorOfLongs(b, VectorOfLongs) |
| 1151 | MyGame.Example.Monster.MonsterAddVectorOfDoubles(b, VectorOfDoubles) |
| 1152 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1153 | |
| 1154 | if sizePrefix: |
| 1155 | b.FinishSizePrefixed(mon, file_identifier) |
| 1156 | else: |
| 1157 | b.Finish(mon, file_identifier) |
| 1158 | |
| 1159 | return b.Bytes, b.Head() |
| 1160 | |
| 1161 | |
| 1162 | class TestAllCodePathsOfExampleSchema(unittest.TestCase): |
| 1163 | def setUp(self, *args, **kwargs): |
| 1164 | super(TestAllCodePathsOfExampleSchema, self).setUp(*args, **kwargs) |
| 1165 | |
| 1166 | b = flatbuffers.Builder(0) |
| 1167 | MyGame.Example.Monster.MonsterStart(b) |
| 1168 | gen_mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1169 | b.Finish(gen_mon) |
| 1170 | |
| 1171 | self.mon = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1172 | b.Head()) |
| 1173 | |
| 1174 | def test_default_monster_pos(self): |
| 1175 | self.assertTrue(self.mon.Pos() is None) |
| 1176 | |
| 1177 | def test_nondefault_monster_mana(self): |
| 1178 | b = flatbuffers.Builder(0) |
| 1179 | MyGame.Example.Monster.MonsterStart(b) |
| 1180 | MyGame.Example.Monster.MonsterAddMana(b, 50) |
| 1181 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1182 | b.Finish(mon) |
| 1183 | |
| 1184 | got_mon = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1185 | b.Head()) |
| 1186 | self.assertEqual(50, got_mon.Mana()) |
| 1187 | |
| 1188 | def test_default_monster_hp(self): |
| 1189 | self.assertEqual(100, self.mon.Hp()) |
| 1190 | |
| 1191 | def test_default_monster_name(self): |
| 1192 | self.assertEqual(None, self.mon.Name()) |
| 1193 | |
| 1194 | def test_default_monster_inventory_item(self): |
| 1195 | self.assertEqual(0, self.mon.Inventory(0)) |
| 1196 | |
| 1197 | def test_default_monster_inventory_length(self): |
| 1198 | self.assertEqual(0, self.mon.InventoryLength()) |
| 1199 | |
| 1200 | def test_default_monster_color(self): |
| 1201 | self.assertEqual(MyGame.Example.Color.Color.Blue, self.mon.Color()) |
| 1202 | |
| 1203 | def test_nondefault_monster_color(self): |
| 1204 | b = flatbuffers.Builder(0) |
| 1205 | color = MyGame.Example.Color.Color.Red |
| 1206 | MyGame.Example.Monster.MonsterStart(b) |
| 1207 | MyGame.Example.Monster.MonsterAddColor(b, color) |
| 1208 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1209 | b.Finish(mon) |
| 1210 | |
| 1211 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1212 | b.Head()) |
| 1213 | self.assertEqual(MyGame.Example.Color.Color.Red, mon2.Color()) |
| 1214 | |
| 1215 | def test_default_monster_testtype(self): |
| 1216 | self.assertEqual(0, self.mon.TestType()) |
| 1217 | |
| 1218 | def test_default_monster_test_field(self): |
| 1219 | self.assertEqual(None, self.mon.Test()) |
| 1220 | |
| 1221 | def test_default_monster_test4_item(self): |
| 1222 | self.assertEqual(None, self.mon.Test4(0)) |
| 1223 | |
| 1224 | def test_default_monster_test4_length(self): |
| 1225 | self.assertEqual(0, self.mon.Test4Length()) |
| 1226 | |
| 1227 | def test_default_monster_testarrayofstring(self): |
| 1228 | self.assertEqual("", self.mon.Testarrayofstring(0)) |
| 1229 | |
| 1230 | def test_default_monster_testarrayofstring_length(self): |
| 1231 | self.assertEqual(0, self.mon.TestarrayofstringLength()) |
| 1232 | |
| 1233 | def test_default_monster_testarrayoftables(self): |
| 1234 | self.assertEqual(None, self.mon.Testarrayoftables(0)) |
| 1235 | |
| 1236 | def test_nondefault_monster_testarrayoftables(self): |
| 1237 | b = flatbuffers.Builder(0) |
| 1238 | |
| 1239 | # make a child Monster within a vector of Monsters: |
| 1240 | MyGame.Example.Monster.MonsterStart(b) |
| 1241 | MyGame.Example.Monster.MonsterAddHp(b, 99) |
| 1242 | sub_monster = MyGame.Example.Monster.MonsterEnd(b) |
| 1243 | |
| 1244 | # build the vector: |
| 1245 | MyGame.Example.Monster.MonsterStartTestarrayoftablesVector(b, 1) |
| 1246 | b.PrependUOffsetTRelative(sub_monster) |
| 1247 | vec = b.EndVector(1) |
| 1248 | |
| 1249 | # make the parent monster and include the vector of Monster: |
| 1250 | MyGame.Example.Monster.MonsterStart(b) |
| 1251 | MyGame.Example.Monster.MonsterAddTestarrayoftables(b, vec) |
| 1252 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1253 | b.Finish(mon) |
| 1254 | |
| 1255 | # inspect the resulting data: |
| 1256 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Output(), 0) |
| 1257 | self.assertEqual(99, mon2.Testarrayoftables(0).Hp()) |
| 1258 | self.assertEqual(1, mon2.TestarrayoftablesLength()) |
| 1259 | |
| 1260 | def test_default_monster_testarrayoftables_length(self): |
| 1261 | self.assertEqual(0, self.mon.TestarrayoftablesLength()) |
| 1262 | |
| 1263 | def test_nondefault_monster_enemy(self): |
| 1264 | b = flatbuffers.Builder(0) |
| 1265 | |
| 1266 | # make an Enemy object: |
| 1267 | MyGame.Example.Monster.MonsterStart(b) |
| 1268 | MyGame.Example.Monster.MonsterAddHp(b, 88) |
| 1269 | enemy = MyGame.Example.Monster.MonsterEnd(b) |
| 1270 | b.Finish(enemy) |
| 1271 | |
| 1272 | # make the parent monster and include the vector of Monster: |
| 1273 | MyGame.Example.Monster.MonsterStart(b) |
| 1274 | MyGame.Example.Monster.MonsterAddEnemy(b, enemy) |
| 1275 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1276 | b.Finish(mon) |
| 1277 | |
| 1278 | # inspect the resulting data: |
| 1279 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1280 | b.Head()) |
| 1281 | self.assertEqual(88, mon2.Enemy().Hp()) |
| 1282 | |
| 1283 | def test_default_monster_testnestedflatbuffer(self): |
| 1284 | self.assertEqual(0, self.mon.Testnestedflatbuffer(0)) |
| 1285 | |
| 1286 | def test_default_monster_testnestedflatbuffer_length(self): |
| 1287 | self.assertEqual(0, self.mon.TestnestedflatbufferLength()) |
| 1288 | |
| 1289 | def test_nondefault_monster_testnestedflatbuffer(self): |
| 1290 | b = flatbuffers.Builder(0) |
| 1291 | |
| 1292 | MyGame.Example.Monster.MonsterStartTestnestedflatbufferVector(b, 3) |
| 1293 | b.PrependByte(4) |
| 1294 | b.PrependByte(2) |
| 1295 | b.PrependByte(0) |
| 1296 | sub_buf = b.EndVector(3) |
| 1297 | |
| 1298 | # make the parent monster and include the vector of Monster: |
| 1299 | MyGame.Example.Monster.MonsterStart(b) |
| 1300 | MyGame.Example.Monster.MonsterAddTestnestedflatbuffer(b, sub_buf) |
| 1301 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1302 | b.Finish(mon) |
| 1303 | |
| 1304 | # inspect the resulting data: |
| 1305 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1306 | b.Head()) |
| 1307 | self.assertEqual(3, mon2.TestnestedflatbufferLength()) |
| 1308 | self.assertEqual(0, mon2.Testnestedflatbuffer(0)) |
| 1309 | self.assertEqual(2, mon2.Testnestedflatbuffer(1)) |
| 1310 | self.assertEqual(4, mon2.Testnestedflatbuffer(2)) |
| 1311 | try: |
| 1312 | imp.find_module('numpy') |
| 1313 | # if numpy exists, then we should be able to get the |
| 1314 | # vector as a numpy array |
| 1315 | self.assertEqual([0, 2, 4], mon2.TestnestedflatbufferAsNumpy().tolist()) |
| 1316 | except ImportError: |
| 1317 | assertRaises(self, |
| 1318 | lambda: mon2.TestnestedflatbufferAsNumpy(), |
| 1319 | NumpyRequiredForThisFeature) |
| 1320 | |
| 1321 | def test_nondefault_monster_testempty(self): |
| 1322 | b = flatbuffers.Builder(0) |
| 1323 | |
| 1324 | # make a Stat object: |
| 1325 | MyGame.Example.Stat.StatStart(b) |
| 1326 | MyGame.Example.Stat.StatAddVal(b, 123) |
| 1327 | my_stat = MyGame.Example.Stat.StatEnd(b) |
| 1328 | b.Finish(my_stat) |
| 1329 | |
| 1330 | # include the stat object in a monster: |
| 1331 | MyGame.Example.Monster.MonsterStart(b) |
| 1332 | MyGame.Example.Monster.MonsterAddTestempty(b, my_stat) |
| 1333 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1334 | b.Finish(mon) |
| 1335 | |
| 1336 | # inspect the resulting data: |
| 1337 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1338 | b.Head()) |
| 1339 | self.assertEqual(123, mon2.Testempty().Val()) |
| 1340 | |
| 1341 | def test_default_monster_testbool(self): |
| 1342 | self.assertFalse(self.mon.Testbool()) |
| 1343 | |
| 1344 | def test_nondefault_monster_testbool(self): |
| 1345 | b = flatbuffers.Builder(0) |
| 1346 | MyGame.Example.Monster.MonsterStart(b) |
| 1347 | MyGame.Example.Monster.MonsterAddTestbool(b, True) |
| 1348 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1349 | b.Finish(mon) |
| 1350 | |
| 1351 | # inspect the resulting data: |
| 1352 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1353 | b.Head()) |
| 1354 | self.assertTrue(mon2.Testbool()) |
| 1355 | |
| 1356 | def test_default_monster_testhashes(self): |
| 1357 | self.assertEqual(0, self.mon.Testhashs32Fnv1()) |
| 1358 | self.assertEqual(0, self.mon.Testhashu32Fnv1()) |
| 1359 | self.assertEqual(0, self.mon.Testhashs64Fnv1()) |
| 1360 | self.assertEqual(0, self.mon.Testhashu64Fnv1()) |
| 1361 | self.assertEqual(0, self.mon.Testhashs32Fnv1a()) |
| 1362 | self.assertEqual(0, self.mon.Testhashu32Fnv1a()) |
| 1363 | self.assertEqual(0, self.mon.Testhashs64Fnv1a()) |
| 1364 | self.assertEqual(0, self.mon.Testhashu64Fnv1a()) |
| 1365 | |
| 1366 | def test_nondefault_monster_testhashes(self): |
| 1367 | b = flatbuffers.Builder(0) |
| 1368 | MyGame.Example.Monster.MonsterStart(b) |
| 1369 | MyGame.Example.Monster.MonsterAddTesthashs32Fnv1(b, 1) |
| 1370 | MyGame.Example.Monster.MonsterAddTesthashu32Fnv1(b, 2) |
| 1371 | MyGame.Example.Monster.MonsterAddTesthashs64Fnv1(b, 3) |
| 1372 | MyGame.Example.Monster.MonsterAddTesthashu64Fnv1(b, 4) |
| 1373 | MyGame.Example.Monster.MonsterAddTesthashs32Fnv1a(b, 5) |
| 1374 | MyGame.Example.Monster.MonsterAddTesthashu32Fnv1a(b, 6) |
| 1375 | MyGame.Example.Monster.MonsterAddTesthashs64Fnv1a(b, 7) |
| 1376 | MyGame.Example.Monster.MonsterAddTesthashu64Fnv1a(b, 8) |
| 1377 | mon = MyGame.Example.Monster.MonsterEnd(b) |
| 1378 | b.Finish(mon) |
| 1379 | |
| 1380 | # inspect the resulting data: |
| 1381 | mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes, |
| 1382 | b.Head()) |
| 1383 | self.assertEqual(1, mon2.Testhashs32Fnv1()) |
| 1384 | self.assertEqual(2, mon2.Testhashu32Fnv1()) |
| 1385 | self.assertEqual(3, mon2.Testhashs64Fnv1()) |
| 1386 | self.assertEqual(4, mon2.Testhashu64Fnv1()) |
| 1387 | self.assertEqual(5, mon2.Testhashs32Fnv1a()) |
| 1388 | self.assertEqual(6, mon2.Testhashu32Fnv1a()) |
| 1389 | self.assertEqual(7, mon2.Testhashs64Fnv1a()) |
| 1390 | self.assertEqual(8, mon2.Testhashu64Fnv1a()) |
| 1391 | |
| 1392 | def test_getrootas_for_nonroot_table(self): |
| 1393 | b = flatbuffers.Builder(0) |
| 1394 | string = b.CreateString("MyStat") |
| 1395 | |
| 1396 | MyGame.Example.Stat.StatStart(b) |
| 1397 | MyGame.Example.Stat.StatAddId(b, string) |
| 1398 | MyGame.Example.Stat.StatAddVal(b, 12345678) |
| 1399 | MyGame.Example.Stat.StatAddCount(b, 12345) |
| 1400 | stat = MyGame.Example.Stat.StatEnd(b) |
| 1401 | b.Finish(stat) |
| 1402 | |
| 1403 | stat2 = MyGame.Example.Stat.Stat.GetRootAsStat(b.Bytes, b.Head()) |
| 1404 | |
| 1405 | self.assertEqual(b"MyStat", stat2.Id()) |
| 1406 | self.assertEqual(12345678, stat2.Val()) |
| 1407 | self.assertEqual(12345, stat2.Count()) |
| 1408 | |
| 1409 | |
| 1410 | class TestAllCodePathsOfMonsterExtraSchema(unittest.TestCase): |
| 1411 | def setUp(self, *args, **kwargs): |
| 1412 | super(TestAllCodePathsOfMonsterExtraSchema, self).setUp(*args, **kwargs) |
| 1413 | |
| 1414 | b = flatbuffers.Builder(0) |
| 1415 | MyGame.MonsterExtra.MonsterExtraStart(b) |
| 1416 | gen_mon = MyGame.MonsterExtra.MonsterExtraEnd(b) |
| 1417 | b.Finish(gen_mon) |
| 1418 | |
| 1419 | self.mon = MyGame.MonsterExtra.MonsterExtra.GetRootAsMonsterExtra(b.Bytes, b.Head()) |
| 1420 | |
| 1421 | def test_default_nan_inf(self): |
| 1422 | self.assertTrue(math.isnan(self.mon.F1())) |
| 1423 | self.assertEqual(self.mon.F2(), float("inf")) |
| 1424 | self.assertEqual(self.mon.F3(), float("-inf")) |
| 1425 | |
| 1426 | self.assertTrue(math.isnan(self.mon.D1())) |
| 1427 | self.assertEqual(self.mon.D2(), float("inf")) |
| 1428 | self.assertEqual(self.mon.D3(), float("-inf")) |
| 1429 | |
| 1430 | |
| 1431 | class TestVtableDeduplication(unittest.TestCase): |
| 1432 | ''' TestVtableDeduplication verifies that vtables are deduplicated. ''' |
| 1433 | |
| 1434 | def test_vtable_deduplication(self): |
| 1435 | b = flatbuffers.Builder(0) |
| 1436 | |
| 1437 | b.StartObject(4) |
| 1438 | b.PrependByteSlot(0, 0, 0) |
| 1439 | b.PrependByteSlot(1, 11, 0) |
| 1440 | b.PrependByteSlot(2, 22, 0) |
| 1441 | b.PrependInt16Slot(3, 33, 0) |
| 1442 | obj0 = b.EndObject() |
| 1443 | |
| 1444 | b.StartObject(4) |
| 1445 | b.PrependByteSlot(0, 0, 0) |
| 1446 | b.PrependByteSlot(1, 44, 0) |
| 1447 | b.PrependByteSlot(2, 55, 0) |
| 1448 | b.PrependInt16Slot(3, 66, 0) |
| 1449 | obj1 = b.EndObject() |
| 1450 | |
| 1451 | b.StartObject(4) |
| 1452 | b.PrependByteSlot(0, 0, 0) |
| 1453 | b.PrependByteSlot(1, 77, 0) |
| 1454 | b.PrependByteSlot(2, 88, 0) |
| 1455 | b.PrependInt16Slot(3, 99, 0) |
| 1456 | obj2 = b.EndObject() |
| 1457 | |
| 1458 | got = b.Bytes[b.Head():] |
| 1459 | |
| 1460 | want = bytearray([ |
| 1461 | 240, 255, 255, 255, # == -12. offset to dedupped vtable. |
| 1462 | 99, 0, |
| 1463 | 88, |
| 1464 | 77, |
| 1465 | 248, 255, 255, 255, # == -8. offset to dedupped vtable. |
| 1466 | 66, 0, |
| 1467 | 55, |
| 1468 | 44, |
| 1469 | 12, 0, |
| 1470 | 8, 0, |
| 1471 | 0, 0, |
| 1472 | 7, 0, |
| 1473 | 6, 0, |
| 1474 | 4, 0, |
| 1475 | 12, 0, 0, 0, |
| 1476 | 33, 0, |
| 1477 | 22, |
| 1478 | 11, |
| 1479 | ]) |
| 1480 | |
| 1481 | self.assertEqual((len(want), want), (len(got), got)) |
| 1482 | |
| 1483 | table0 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj0) |
| 1484 | table1 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj1) |
| 1485 | table2 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj2) |
| 1486 | |
| 1487 | def _checkTable(tab, voffsett_value, b, c, d): |
| 1488 | # vtable size |
| 1489 | got = tab.GetVOffsetTSlot(0, 0) |
| 1490 | self.assertEqual(12, got, 'case 0, 0') |
| 1491 | |
| 1492 | # object size |
| 1493 | got = tab.GetVOffsetTSlot(2, 0) |
| 1494 | self.assertEqual(8, got, 'case 2, 0') |
| 1495 | |
| 1496 | # default value |
| 1497 | got = tab.GetVOffsetTSlot(4, 0) |
| 1498 | self.assertEqual(voffsett_value, got, 'case 4, 0') |
| 1499 | |
| 1500 | got = tab.GetSlot(6, 0, N.Uint8Flags) |
| 1501 | self.assertEqual(b, got, 'case 6, 0') |
| 1502 | |
| 1503 | val = tab.GetSlot(8, 0, N.Uint8Flags) |
| 1504 | self.assertEqual(c, val, 'failed 8, 0') |
| 1505 | |
| 1506 | got = tab.GetSlot(10, 0, N.Uint8Flags) |
| 1507 | self.assertEqual(d, got, 'failed 10, 0') |
| 1508 | |
| 1509 | _checkTable(table0, 0, 11, 22, 33) |
| 1510 | _checkTable(table1, 0, 44, 55, 66) |
| 1511 | _checkTable(table2, 0, 77, 88, 99) |
| 1512 | |
| 1513 | |
| 1514 | class TestExceptions(unittest.TestCase): |
| 1515 | def test_object_is_nested_error(self): |
| 1516 | b = flatbuffers.Builder(0) |
| 1517 | b.StartObject(0) |
| 1518 | assertRaises(self, lambda: b.StartObject(0), |
| 1519 | flatbuffers.builder.IsNestedError) |
| 1520 | |
| 1521 | def test_object_is_not_nested_error(self): |
| 1522 | b = flatbuffers.Builder(0) |
| 1523 | assertRaises(self, lambda: b.EndObject(), |
| 1524 | flatbuffers.builder.IsNotNestedError) |
| 1525 | |
| 1526 | def test_struct_is_not_inline_error(self): |
| 1527 | b = flatbuffers.Builder(0) |
| 1528 | b.StartObject(0) |
| 1529 | assertRaises(self, lambda: b.PrependStructSlot(0, 1, 0), |
| 1530 | flatbuffers.builder.StructIsNotInlineError) |
| 1531 | |
| 1532 | def test_unreachable_error(self): |
| 1533 | b = flatbuffers.Builder(0) |
| 1534 | assertRaises(self, lambda: b.PrependUOffsetTRelative(1), |
| 1535 | flatbuffers.builder.OffsetArithmeticError) |
| 1536 | |
| 1537 | def test_create_string_is_nested_error(self): |
| 1538 | b = flatbuffers.Builder(0) |
| 1539 | b.StartObject(0) |
| 1540 | s = 'test1' |
| 1541 | assertRaises(self, lambda: b.CreateString(s), |
| 1542 | flatbuffers.builder.IsNestedError) |
| 1543 | |
| 1544 | def test_create_byte_vector_is_nested_error(self): |
| 1545 | b = flatbuffers.Builder(0) |
| 1546 | b.StartObject(0) |
| 1547 | s = b'test1' |
| 1548 | assertRaises(self, lambda: b.CreateByteVector(s), |
| 1549 | flatbuffers.builder.IsNestedError) |
| 1550 | |
| 1551 | def test_finished_bytes_error(self): |
| 1552 | b = flatbuffers.Builder(0) |
| 1553 | assertRaises(self, lambda: b.Output(), |
| 1554 | flatbuffers.builder.BuilderNotFinishedError) |
| 1555 | |
| 1556 | |
| 1557 | class TestFixedLengthArrays(unittest.TestCase): |
| 1558 | def test_fixed_length_array(self): |
| 1559 | builder = flatbuffers.Builder(0) |
| 1560 | |
| 1561 | a = 0.5 |
| 1562 | b = range(0, 15) |
| 1563 | c = 1 |
| 1564 | d_a = [[1, 2], [3, 4]] |
| 1565 | d_b = [MyGame.Example.TestEnum.TestEnum.B, \ |
| 1566 | MyGame.Example.TestEnum.TestEnum.C] |
| 1567 | d_c = [[MyGame.Example.TestEnum.TestEnum.A, \ |
| 1568 | MyGame.Example.TestEnum.TestEnum.B], \ |
| 1569 | [MyGame.Example.TestEnum.TestEnum.C, \ |
| 1570 | MyGame.Example.TestEnum.TestEnum.B]] |
| 1571 | |
| 1572 | arrayOffset = MyGame.Example.ArrayStruct.CreateArrayStruct(builder, \ |
| 1573 | a, b, c, d_a, d_b, d_c) |
| 1574 | |
| 1575 | # Create a table with the ArrayStruct. |
| 1576 | MyGame.Example.ArrayTable.ArrayTableStart(builder) |
| 1577 | MyGame.Example.ArrayTable.ArrayTableAddA(builder, arrayOffset) |
| 1578 | tableOffset = MyGame.Example.ArrayTable.ArrayTableEnd(builder) |
| 1579 | |
| 1580 | builder.Finish(tableOffset) |
| 1581 | |
| 1582 | buf = builder.Output() |
| 1583 | |
| 1584 | table = MyGame.Example.ArrayTable.ArrayTable.GetRootAsArrayTable(buf, 0) |
| 1585 | |
| 1586 | # Verify structure. |
| 1587 | nested = MyGame.Example.NestedStruct.NestedStruct() |
| 1588 | self.assertEqual(table.A().A(), 0.5) |
| 1589 | self.assertEqual(table.A().B(), \ |
| 1590 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) |
| 1591 | self.assertEqual(table.A().C(), 1) |
| 1592 | self.assertEqual(table.A().D(nested, 0).A(), [1, 2]) |
| 1593 | self.assertEqual(table.A().D(nested, 1).A(), [3, 4]) |
| 1594 | self.assertEqual(table.A().D(nested, 0).B(), \ |
| 1595 | MyGame.Example.TestEnum.TestEnum.B) |
| 1596 | self.assertEqual(table.A().D(nested, 1).B(), \ |
| 1597 | MyGame.Example.TestEnum.TestEnum.C) |
| 1598 | self.assertEqual(table.A().D(nested, 0).C(), \ |
| 1599 | [MyGame.Example.TestEnum.TestEnum.A, \ |
| 1600 | MyGame.Example.TestEnum.TestEnum.B]) |
| 1601 | self.assertEqual(table.A().D(nested, 1).C(), \ |
| 1602 | [MyGame.Example.TestEnum.TestEnum.C, \ |
| 1603 | MyGame.Example.TestEnum.TestEnum.B]) |
| 1604 | |
| 1605 | |
| 1606 | def CheckAgainstGoldDataGo(): |
| 1607 | try: |
| 1608 | gen_buf, gen_off = make_monster_from_generated_code() |
| 1609 | fn = 'monsterdata_go_wire.mon' |
| 1610 | if not os.path.exists(fn): |
| 1611 | print('Go-generated data does not exist, failed.') |
| 1612 | return False |
| 1613 | |
| 1614 | # would like to use a context manager here, but it's less |
| 1615 | # backwards-compatible: |
| 1616 | f = open(fn, 'rb') |
| 1617 | go_wire_data = f.read() |
| 1618 | f.close() |
| 1619 | |
| 1620 | CheckReadBuffer(bytearray(go_wire_data), 0) |
| 1621 | if not bytearray(gen_buf[gen_off:]) == bytearray(go_wire_data): |
| 1622 | raise AssertionError('CheckAgainstGoldDataGo failed') |
| 1623 | except: |
| 1624 | print('Failed to test against Go-generated test data.') |
| 1625 | return False |
| 1626 | |
| 1627 | print('Can read Go-generated test data, and Python generates bytewise identical data.') |
| 1628 | return True |
| 1629 | |
| 1630 | |
| 1631 | def CheckAgainstGoldDataJava(): |
| 1632 | try: |
| 1633 | gen_buf, gen_off = make_monster_from_generated_code() |
| 1634 | fn = 'monsterdata_java_wire.mon' |
| 1635 | if not os.path.exists(fn): |
| 1636 | print('Java-generated data does not exist, failed.') |
| 1637 | return False |
| 1638 | f = open(fn, 'rb') |
| 1639 | java_wire_data = f.read() |
| 1640 | f.close() |
| 1641 | |
| 1642 | CheckReadBuffer(bytearray(java_wire_data), 0) |
| 1643 | except: |
| 1644 | print('Failed to read Java-generated test data.') |
| 1645 | return False |
| 1646 | |
| 1647 | print('Can read Java-generated test data.') |
| 1648 | return True |
| 1649 | |
| 1650 | |
| 1651 | class LCG(object): |
| 1652 | ''' Include simple random number generator to ensure results will be the |
| 1653 | same cross platform. |
| 1654 | http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator ''' |
| 1655 | |
| 1656 | __slots__ = ['n'] |
| 1657 | |
| 1658 | InitialLCGSeed = 48271 |
| 1659 | |
| 1660 | def __init__(self): |
| 1661 | self.n = self.InitialLCGSeed |
| 1662 | |
| 1663 | def Reset(self): |
| 1664 | self.n = self.InitialLCGSeed |
| 1665 | |
| 1666 | def Next(self): |
| 1667 | self.n = ((self.n * 279470273) % 4294967291) & 0xFFFFFFFF |
| 1668 | return self.n |
| 1669 | |
| 1670 | |
| 1671 | def BenchmarkVtableDeduplication(count): |
| 1672 | ''' |
| 1673 | BenchmarkVtableDeduplication measures the speed of vtable deduplication |
| 1674 | by creating `prePop` vtables, then populating `count` objects with a |
| 1675 | different single vtable. |
| 1676 | |
| 1677 | When count is large (as in long benchmarks), memory usage may be high. |
| 1678 | ''' |
| 1679 | |
| 1680 | for prePop in (1, 10, 100, 1000): |
| 1681 | builder = flatbuffers.Builder(0) |
| 1682 | n = 1 + int(math.log(prePop, 1.5)) |
| 1683 | |
| 1684 | # generate some layouts: |
| 1685 | layouts = set() |
| 1686 | r = list(compat_range(n)) |
| 1687 | while len(layouts) < prePop: |
| 1688 | layouts.add(tuple(sorted(random.sample(r, int(max(1, n / 2)))))) |
| 1689 | |
| 1690 | layouts = list(layouts) |
| 1691 | |
| 1692 | # pre-populate vtables: |
| 1693 | for layout in layouts: |
| 1694 | builder.StartObject(n) |
| 1695 | for j in layout: |
| 1696 | builder.PrependInt16Slot(j, j, 0) |
| 1697 | builder.EndObject() |
| 1698 | |
| 1699 | # benchmark deduplication of a new vtable: |
| 1700 | def f(): |
| 1701 | layout = random.choice(layouts) |
| 1702 | builder.StartObject(n) |
| 1703 | for j in layout: |
| 1704 | builder.PrependInt16Slot(j, j, 0) |
| 1705 | builder.EndObject() |
| 1706 | |
| 1707 | duration = timeit.timeit(stmt=f, number=count) |
| 1708 | rate = float(count) / duration |
| 1709 | print(('vtable deduplication rate (n=%d, vtables=%d): %.2f sec' % ( |
| 1710 | prePop, |
| 1711 | len(builder.vtables), |
| 1712 | rate)) |
| 1713 | ) |
| 1714 | |
| 1715 | |
| 1716 | def BenchmarkCheckReadBuffer(count, buf, off): |
| 1717 | ''' |
| 1718 | BenchmarkCheckReadBuffer measures the speed of flatbuffer reading |
| 1719 | by re-using the CheckReadBuffer function with the gold data. |
| 1720 | ''' |
| 1721 | |
| 1722 | def f(): |
| 1723 | CheckReadBuffer(buf, off) |
| 1724 | |
| 1725 | duration = timeit.timeit(stmt=f, number=count) |
| 1726 | rate = float(count) / duration |
| 1727 | data = float(len(buf) * count) / float(1024 * 1024) |
| 1728 | data_rate = data / float(duration) |
| 1729 | |
| 1730 | print(('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec') |
| 1731 | % (count, len(buf), duration, rate, data_rate)) |
| 1732 | |
| 1733 | |
| 1734 | def BenchmarkMakeMonsterFromGeneratedCode(count, length): |
| 1735 | ''' |
| 1736 | BenchmarkMakeMonsterFromGeneratedCode measures the speed of flatbuffer |
| 1737 | creation by re-using the make_monster_from_generated_code function for |
| 1738 | generating gold data examples. |
| 1739 | ''' |
| 1740 | |
| 1741 | duration = timeit.timeit(stmt=make_monster_from_generated_code, |
| 1742 | number=count) |
| 1743 | rate = float(count) / duration |
| 1744 | data = float(length * count) / float(1024 * 1024) |
| 1745 | data_rate = data / float(duration) |
| 1746 | |
| 1747 | print(('built %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec' % \ |
| 1748 | (count, length, duration, rate, data_rate))) |
| 1749 | |
| 1750 | |
| 1751 | def backward_compatible_run_tests(**kwargs): |
| 1752 | if PY_VERSION < (2, 6): |
| 1753 | sys.stderr.write("Python version less than 2.6 are not supported") |
| 1754 | sys.stderr.flush() |
| 1755 | return False |
| 1756 | |
| 1757 | # python2.6 has a reduced-functionality unittest.main function: |
| 1758 | if PY_VERSION == (2, 6): |
| 1759 | try: |
| 1760 | unittest.main(**kwargs) |
| 1761 | except SystemExit as e: |
| 1762 | if not e.code == 0: |
| 1763 | return False |
| 1764 | return True |
| 1765 | |
| 1766 | # python2.7 and above let us not exit once unittest.main is run: |
| 1767 | kwargs['exit'] = False |
| 1768 | kwargs['verbosity'] = 0 |
| 1769 | ret = unittest.main(**kwargs) |
| 1770 | if ret.result.errors or ret.result.failures: |
| 1771 | return False |
| 1772 | |
| 1773 | return True |
| 1774 | |
| 1775 | def main(): |
| 1776 | import os |
| 1777 | import sys |
| 1778 | if not len(sys.argv) == 4: |
| 1779 | sys.stderr.write('Usage: %s <benchmark vtable count>' |
| 1780 | '<benchmark read count> <benchmark build count>\n' |
| 1781 | % sys.argv[0]) |
| 1782 | sys.stderr.write(' Provide COMPARE_GENERATED_TO_GO=1 to check' |
| 1783 | 'for bytewise comparison to Go data.\n') |
| 1784 | sys.stderr.write(' Provide COMPARE_GENERATED_TO_JAVA=1 to check' |
| 1785 | 'for bytewise comparison to Java data.\n') |
| 1786 | sys.stderr.flush() |
| 1787 | sys.exit(1) |
| 1788 | |
| 1789 | kwargs = dict(argv=sys.argv[:-3]) |
| 1790 | |
| 1791 | # run tests, and run some language comparison checks if needed: |
| 1792 | success = backward_compatible_run_tests(**kwargs) |
| 1793 | if success and os.environ.get('COMPARE_GENERATED_TO_GO', 0) == "1": |
| 1794 | success = success and CheckAgainstGoldDataGo() |
| 1795 | if success and os.environ.get('COMPARE_GENERATED_TO_JAVA', 0) == "1": |
| 1796 | success = success and CheckAgainstGoldDataJava() |
| 1797 | |
| 1798 | if not success: |
| 1799 | sys.stderr.write('Tests failed, skipping benchmarks.\n') |
| 1800 | sys.stderr.flush() |
| 1801 | sys.exit(1) |
| 1802 | |
| 1803 | # run benchmarks (if 0, they will be a noop): |
| 1804 | bench_vtable = int(sys.argv[1]) |
| 1805 | bench_traverse = int(sys.argv[2]) |
| 1806 | bench_build = int(sys.argv[3]) |
| 1807 | if bench_vtable: |
| 1808 | BenchmarkVtableDeduplication(bench_vtable) |
| 1809 | if bench_traverse: |
| 1810 | buf, off = make_monster_from_generated_code() |
| 1811 | BenchmarkCheckReadBuffer(bench_traverse, buf, off) |
| 1812 | if bench_build: |
| 1813 | buf, off = make_monster_from_generated_code() |
| 1814 | BenchmarkMakeMonsterFromGeneratedCode(bench_build, len(buf)) |
| 1815 | |
| 1816 | if __name__ == '__main__': |
| 1817 | main() |