Exemplo n.º 1
0
    def test_field_name_error(self):
        from flatbuf._builder import locate

        self.assertTrue(
            locate(fbs_test.Composite, 'CompositeAddShade') is not None)

        with self.assertRaises(AttributeError):
            locate(fbs_test.Composite, 'boo')

        with self.assertRaises(AttributeError) as err:
            locate(fbs_test.Composite, 'CompositeAddshade')
        self.assertTrue('CompositeAddshade' in str(err.exception))
        self.assertTrue('field name Shade' in str(err.exception))

        with self.assertRaises(AttributeError) as err:
            locate(fbs_test.Composite, 'CompositeStartrefdataVector')
        self.assertTrue('CompositeStartRefDataVector' in str(err.exception))
        self.assertTrue('field name RefData' in str(err.exception))

        with self.assertRaises(AttributeError) as err:
            locate(fbs_test.Composite, 'CompositeStartref_dataVector')
        self.assertTrue('CompositeStartRefDataVector' in str(err.exception))
        self.assertTrue('field name RefData' in str(err.exception))

        with self.assertRaises(AttributeError) as err:
            with flatbuffers.Builder().create(fbs_test.Composite) as c:
                c.add('ref_data', [1, 2])
        self.assertTrue('CompositeAddRefData' in str(err.exception))
        self.assertTrue('field name RefData' in str(err.exception))
Exemplo n.º 2
0
    def test_multiple_finalize(self):

        with flatbuffers.Builder().create(fbs_test.Composite) as c:
            c.add('Name', 'abc')

        r0 = c.output()  # calls c._finalize()
        r1 = c.output()
        r2 = c.output()

        self.assertEqual(
            fbs_test.Composite.Composite.GetRootAsComposite(r1, 0).Name(),
            'abc')
        self.assertEqual(
            fbs_test.Composite.Composite.GetRootAsComposite(r2, 0).Name(),
            'abc')
        self.assertEqual(
            fbs_test.Composite.Composite.GetRootAsComposite(r0, 0).Name(),
            'abc')
Exemplo n.º 3
0
    def test_scalar_vectors(self):
        bldr = flatbuffers.Builder()

        # todo find a better way to create scalar vectors
        data = [1, 2, 3]
        fbs_test.Composite.CompositeStartBytesVector(bldr, len(data))
        for i in reversed(data):
            bldr.PrependByte(i)
        b = bldr.EndVector(len(data))

        with bldr.create(fbs_test.Composite) as c:
            c.add('Bytes', b)

        r = fbs_test.Composite.Composite.GetRootAsComposite(c.output(), 0)

        self.assertEqual(r.BytesLength(), 3)
        self.assertEqual(r.Bytes(0), 1)
        self.assertEqual(r.Bytes(1), 2)
        self.assertEqual(r.Bytes(2), 3)
Exemplo n.º 4
0
    def test_build_inline(self):
        bldr = flatbuffers.Builder()

        location = flatbuffers.build_inline(fbs_test.Location.CreateLocation,
                                            values=[5, 6])
        color = flatbuffers.build_inline(fbs_test.Color.CreateColor,
                                         values=[0.1, 0.2, 0.3])

        with bldr.create(fbs_test.Composite) as c:
            c.add('Loc', location)
            c.add('Shade', color)

        msg = c.output()
        r = fbs_test.Composite.Composite.GetRootAsComposite(msg, 0)

        self.assertAlmostEqual(r.Shade().Red(), 0.1)
        self.assertAlmostEqual(r.Shade().Green(), 0.2)
        self.assertAlmostEqual(r.Shade().Blue(), 0.3)

        self.assertEqual(r.Loc().X(), 5)
        self.assertEqual(r.Loc().Y(), 6)
Exemplo n.º 5
0
    def test_create_target(self):

        bldr = flatbuffers.Builder()
        ref = [
            bldr.create(fbs_test.Identity.Identity, {
                'Id': 1,
                'Key': '2'
            }),
            bldr.create(fbs_test.Identity.Identity, {
                'Id': 3,
                'Key': '4'
            })
        ]

        enc = bldr.create(fbs_test.Composite.Composite, {
            'Loc': bldr.create(fbs_test.Location, [1, 2]),
            'RefData': ref
        })

        def _check(msg):
            r = fbs_test.Composite.Composite.GetRootAsComposite(msg, 0)
            self.assertEqual(r.Loc().X(), 1)
            self.assertEqual(r.Loc().Y(), 2)

            self.assertEqual(r.RefDataLength(), 2)
            self.assertEqual(r.RefData(0).Id(), 1)
            self.assertEqual(r.RefData(1).Id(), 3)
            self.assertEqual(r.RefData(0).Key(), '2')
            self.assertEqual(r.RefData(1).Key(), '4')

        _check(bldr.finish(enc).Output())

        #--------------------------------------------------

        from fbs_test.Identity import Identity as IdentityCls
        from fbs_test.Composite import Composite as CompositeCls

        bldr = flatbuffers.Builder()
        ref = [
            bldr.create(IdentityCls, {
                'Id': 1,
                'Key': '2'
            }),
            bldr.create(IdentityCls, {
                'Id': 3,
                'Key': '4'
            })
        ]
        enc = bldr.create(CompositeCls, {
            'Loc': bldr.create(fbs_test.Location, [1, 2]),
            'RefData': ref
        })
        _check(bldr.finish(enc).Output())

        #--------------------------------------------------

        import fbs_test.Identity as IdentityModule
        import fbs_test.Composite as CompositeModule

        bldr = flatbuffers.Builder()
        ref = [
            bldr.create(IdentityModule, {
                'Id': 1,
                'Key': '2'
            }),
            bldr.create(IdentityModule, {
                'Id': 3,
                'Key': '4'
            })
        ]

        enc = bldr.create(CompositeModule, {
            'Loc': bldr.create(fbs_test.Location, [1, 2]),
            'RefData': ref
        })
        _check(bldr.finish(enc).Output())
Exemplo n.º 6
0
    def test_free_order(self):

        #---------------------------------------------

        def _create_records(builder):
            return [
                builder.create(fbs_test.Identity, {
                    'Id': 1,
                    'Key': 'abc'
                }),
                builder.create(fbs_test.Identity, {
                    'Id': 9,
                    'Key': 'unknown'
                })
            ]

        rgb = [120.0, 250.0, 64.0]
        xy = [42, -42]

        def _check(msg):
            r = fbs_test.Composite.Composite.GetRootAsComposite(msg, 0)

            self.assertEqual(r.Name(), 'utest')

            self.assertEqual(r.Loc().X(), 42)
            self.assertEqual(r.Loc().Y(), -42)

            self.assertAlmostEqual(r.Shade().Red(), 120.0)
            self.assertAlmostEqual(r.Shade().Green(), 250.0)
            self.assertAlmostEqual(r.Shade().Blue(), 64.0)

            self.assertEqual(r.RefDataLength(), 2)
            self.assertEqual(r.RefData(0).Id(), 1)
            self.assertEqual(r.RefData(1).Id(), 9)
            self.assertEqual(r.RefData(0).Key(), 'abc')
            self.assertEqual(r.RefData(1).Key(), 'unknown')

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        records = _create_records(bldr)
        color = bldr.create(fbs_test.Color, rgb)
        location = bldr.create(fbs_test.Location, xy)

        with bldr.create(fbs_test.Composite) as c:
            c.add('Shade', color)
            c.add('Name', 'utest')
            c.add('Loc', location)
            c.add('RefData', records)
        _check(c.output())

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        with bldr.create(fbs_test.Composite) as c:
            c.add('Shade', bldr.create(fbs_test.Color, rgb))
            c.add('Name', 'utest')
            c.add('Loc', bldr.create(fbs_test.Location, xy))
            c.add('RefData', _create_records(bldr))
        _check(c.output())

        #----------------------------------------------
        bldr = flatbuffers.Builder()
        with bldr.create(fbs_test.Composite) as c:
            c.add('Loc', bldr.create(fbs_test.Location, xy))
            c.add('Shade', bldr.create(fbs_test.Color, rgb))
            c.add('Name', 'utest')
            c.add('RefData', _create_records(bldr))
        _check(c.output())

        #----------------------------------------------
        bldr = flatbuffers.Builder()
        with bldr.create(fbs_test.Composite) as c:
            c.add('RefData', _create_records(bldr))
            c.add('Name', 'utest')
            c.add('Loc', bldr.create(fbs_test.Location, xy))
            c.add('Shade', bldr.create(fbs_test.Color, rgb))
        _check(c.output())
Exemplo n.º 7
0
    def test_free_order(self):
        def _create_records(builder):
            return [
                builder.create(fbs_test.Identity, {
                    'Id': 1,
                    'Key': 'abc'
                }),
                builder.create(fbs_test.Identity, {
                    'Id': 9,
                    'Key': 'unknown'
                })
            ]

        rgb = [120.0, 250.0, 64.0]
        xy = [42, -42]

        def _check(msg):
            r = fbs_test.Composite.Composite.GetRootAsComposite(msg, 0)

            self.assertEqual(r.Name(), 'utest')

            self.assertEqual(r.Loc().X(), 42)
            self.assertEqual(r.Loc().Y(), -42)

            self.assertAlmostEqual(r.Shade().Red(), 120.0)
            self.assertAlmostEqual(r.Shade().Green(), 250.0)
            self.assertAlmostEqual(r.Shade().Blue(), 64.0)

            self.assertEqual(r.RefDataLength(), 2)
            self.assertEqual(r.RefData(0).Id(), 1)
            self.assertEqual(r.RefData(1).Id(), 9)
            self.assertEqual(r.RefData(0).Key(), 'abc')
            self.assertEqual(r.RefData(1).Key(), 'unknown')

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        records = _create_records(bldr)
        color = bldr.create(fbs_test.Color, rgb)
        location = bldr.create(fbs_test.Location, xy)

        enc = bldr.create(fbs_test.Composite,
                          properties={
                              'Shade': color,
                              'Name': 'utest',
                              'Loc': location,
                              'RefData': records
                          })
        _check(bldr.finish(enc).Output())

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        records = _create_records(bldr)
        enc = bldr.create(fbs_test.Composite,
                          properties=[
                              ('Shade', bldr.create(fbs_test.Color, rgb)),
                              ('Name', 'utest'),
                              ('Loc', bldr.create(fbs_test.Location, xy)),
                              ('RefData', records)
                          ])
        _check(bldr.finish(enc).Output())

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        records = _create_records(bldr)
        enc = bldr.create(fbs_test.Composite,
                          properties=[
                              ('Loc', bldr.create(fbs_test.Location, xy)),
                              ('Shade', bldr.create(fbs_test.Color, rgb)),
                              ('Name', 'utest'), ('RefData', records)
                          ])
        _check(bldr.finish(enc).Output())

        #---------------------------------------------
        bldr = flatbuffers.Builder()
        records = _create_records(bldr)
        enc = bldr.create(fbs_test.Composite,
                          properties=[
                              ('Name', 'utest'), ('RefData', records),
                              ('Loc', bldr.create(fbs_test.Location, xy)),
                              ('Shade', bldr.create(fbs_test.Color, rgb))
                          ])
        _check(bldr.finish(enc).Output())
Exemplo n.º 8
0
def main():

    # -------------------------------------------------------------------------

    bldr = flatbuffers.Builder()
    with bldr.create(MyGame.Sample.Monster) as orc:
        orc.add('Name', 'Orc')

        sword = bldr.create(MyGame.Sample.Weapon, {
            'Name': 'Sword',
            'Damage': 3
        })
        axe = bldr.create(MyGame.Sample.Weapon, {'Name': 'Axe', 'Damage': 5})
        orc.add('Weapons', [sword, axe])

        orc.add('EquippedType', MyGame.Sample.Equipment.Equipment.Weapon)
        orc.add('Equipped', axe)

        pos = bldr.create(MyGame.Sample.Vec3, [1.0, 2.0, 3.0])
        orc.add('Pos', pos)
        orc.add('Hp', 300)
        orc.add('Color', MyGame.Sample.Color.Color.Red)

        MyGame.Sample.Monster.MonsterStartInventoryVector(bldr, 10)
        for i in reversed(range(0, 10)):
            bldr.PrependByte(i)
        inv = bldr.EndVector(10)

        orc.add('Inventory', inv)

    buf = orc.output()

    # -------------------------------------------------------------------------

    # copy and paste from flatbuffer's tutorial
    #     builder = flatbuffers.Builder(0)
    #
    #     # Create some weapons for our Monster ('Sword' and 'Axe').
    #     weapon_one = builder.CreateString('Sword')
    #     weapon_two = builder.CreateString('Axe')
    #
    #     MyGame.Sample.Weapon.WeaponStart(builder)
    #     MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one)
    #     MyGame.Sample.Weapon.WeaponAddDamage(builder, 3)
    #     sword = MyGame.Sample.Weapon.WeaponEnd(builder)
    #
    #     MyGame.Sample.Weapon.WeaponStart(builder)
    #     MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two)
    #     MyGame.Sample.Weapon.WeaponAddDamage(builder, 5)
    #     axe = MyGame.Sample.Weapon.WeaponEnd(builder)
    #
    #     # Serialize the FlatBuffer data.
    #     name = builder.CreateString('Orc')
    #
    #     MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10)
    #     # Note: Since we prepend the bytes, this loop iterates in reverse order.
    #     for i in reversed(range(0, 10)):
    #         builder.PrependByte(i)
    #     inv = builder.EndVector(10)
    #
    #     MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
    #     # Note: Since we prepend the data, prepend the weapons in reverse order.
    #     builder.PrependUOffsetTRelative(axe)
    #     builder.PrependUOffsetTRelative(sword)
    #     weapons = builder.EndVector(2)
    #
    #     pos = MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)
    #
    #     MyGame.Sample.Monster.MonsterStart(builder)
    #     MyGame.Sample.Monster.MonsterAddPos(builder, pos)
    #     MyGame.Sample.Monster.MonsterAddHp(builder, 300)
    #     MyGame.Sample.Monster.MonsterAddName(builder, name)
    #
    #     MyGame.Sample.Monster.MonsterAddInventory(builder, inv)
    #
    #     MyGame.Sample.Monster.MonsterAddColor(builder,
    #                                           MyGame.Sample.Color.Color().Red)
    #     MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons)
    #     MyGame.Sample.Monster.MonsterAddEquippedType(
    #         builder, MyGame.Sample.Equipment.Equipment().Weapon)
    #     MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)
    #     orc = MyGame.Sample.Monster.MonsterEnd(builder)
    #
    #     builder.Finish(orc)
    #
    #     # We now have a FlatBuffer that we could store on disk or send over a network.
    #
    #     # ...Saving to file or sending over a network code goes here...
    #
    #     # Instead, we are going to access this buffer right away (as if we just
    #     # received it).
    #     buf = builder.Output()

    # Note: We use `0` for the offset here, since we got the data using the
    # `builder.Output()` method. This simulates the data you would store/receive
    # in your FlatBuffer. If you wanted to read from the `builder.Bytes` directly,
    # you would need to pass in the offset of `builder.Head()`, as the builder
    # actually constructs the buffer backwards.
    monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0)

    # Note: We did not set the `Mana` field explicitly, so we get a default value.
    assert monster.Mana() == 150
    assert monster.Hp() == 300
    assert monster.Name() == 'Orc'
    assert monster.Color() == MyGame.Sample.Color.Color.Red
    assert monster.Pos().X() == 1.0
    assert monster.Pos().Y() == 2.0
    assert monster.Pos().Z() == 3.0

    # Get and test the `inventory` FlatBuffer `vector`.
    for i in xrange(monster.InventoryLength()):
        assert monster.Inventory(i) == i, "Inventory: {} != {}".format(
            monster.Inventory(i), i)

    # Get and test the `weapons` FlatBuffer `vector` of `table`s.
    expected_weapon_names = ['Sword', 'Axe']
    expected_weapon_damages = [3, 5]
    for i in xrange(monster.WeaponsLength()):
        assert monster.Weapons(i).Name() == expected_weapon_names[i]
        assert monster.Weapons(i).Damage() == expected_weapon_damages[i]

    # Get and test the `equipped` FlatBuffer `union`.
    assert monster.EquippedType() == MyGame.Sample.Equipment.Equipment.Weapon

    # An example of how you can appropriately convert the table depending on the
    # FlatBuffer `union` type. You could add `elif` and `else` clauses to handle
    # the other FlatBuffer `union` types for this field.
    if monster.EquippedType() == MyGame.Sample.Equipment.Equipment.Weapon:
        # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used
        # to initialize a `MyGame.Sample.Weapon.Weapon()`, in this case.
        union_weapon = MyGame.Sample.Weapon.Weapon()
        union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)

        assert union_weapon.Name() == "Axe"
        assert union_weapon.Damage() == 5

    print 'The FlatBuffer was successfully created and verified!'