Add unique_key_packed to UniqueKey mixin

This allows client libraries to get a binary representation of the
unique_key.

Change-Id: Ia8523286c74b2545b72bab7448f138105ac34c83
This commit is contained in:
Omer Anson 2018-06-21 09:49:11 +03:00
parent ce7abc0fd0
commit c82fb18b14
2 changed files with 65 additions and 0 deletions

View File

@ -9,6 +9,8 @@
# 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 struct
from jsonmodels import fields
import dragonflow.db.model_framework as mf
@ -57,3 +59,10 @@ class UniqueKey(mf.MixinBase):
from dragonflow.db import api_nb
nb_api = api_nb.NbApi.get_instance()
self.unique_key = nb_api.driver.allocate_unique_key(self.table_name)
@property
def unique_key_packed(self):
unique_key = self.unique_key
if unique_key is None:
return None
return struct.pack('!I', self.unique_key)

View File

@ -0,0 +1,56 @@
# 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 six
from dragonflow import conf as cfg
from dragonflow.db import api_nb
from dragonflow.db import model_framework as mf
from dragonflow.db.models import mixins
from dragonflow.tests import base as tests_base
@mf.register_model
@mf.construct_nb_db_model
class ModelWithUniqueKey(mf.ModelBase, mixins.BasicEvents, mixins.UniqueKey):
table_name = 'model_with_unique_key1'
def _bytes(*args):
"""
Returns a byte array (bytes in py3, str in py2) of chr(b) for
each b in args
"""
if six.PY2:
return "".join(chr(c) for c in args)
# else: Python 3
return bytes(args)
class TestUniqueKeyMixin(tests_base.BaseTestCase):
def setUp(self):
cfg.CONF.set_override('nb_db_class', '_dummy_nb_db_driver', group='df')
super(TestUniqueKeyMixin, self).setUp()
def test_allocate_unique_id(self):
nb_api = api_nb.NbApi.get_instance()
instance1 = ModelWithUniqueKey(id='instance1')
nb_api.create(instance1)
self.assertIsNotNone(instance1.unique_key)
def test_unique_id_packed(self):
instance = ModelWithUniqueKey(id='instance', unique_key=13)
self.assertEqual(_bytes(0, 0, 0, 13),
instance.unique_key_packed)
instance.unique_key = 0x12345678
self.assertEqual(_bytes(0x12, 0x34, 0x56, 0x78),
instance.unique_key_packed)