Add custom OVO field type for MAC address

Partial-Bug: #1541928
Co-Authored-By: Ihar Hrachyshka <ihrachys@redhat.com>
Change-Id: If791b25aa673dde32b41c799fad9dc36efc87d04
This commit is contained in:
Martin Hickey 2016-03-16 14:52:25 +00:00 committed by Ihar Hrachyshka
parent acb7ff8d11
commit b8cd05273f
3 changed files with 51 additions and 0 deletions

View File

@ -11,6 +11,7 @@
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from oslo_versionedobjects import fields as obj_fields
import six
@ -145,3 +146,27 @@ class EtherTypeEnumField(obj_fields.AutoTypedField):
class IpProtocolEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=list(constants.IP_PROTOCOL_MAP.keys()))
class MACAddress(obj_fields.FieldType):
"""MACAddress custom field.
This custom field is different from the one provided by
oslo.versionedobjects library: it uses netaddr.EUI type instead of strings.
"""
def _validate_value(self, value):
if not isinstance(value, netaddr.EUI):
msg = _("Field value %s is not a netaddr.EUI") % value
raise ValueError(msg)
def coerce(self, obj, attr, value):
self._validate_value(value)
return super(MACAddress, self).coerce(obj, attr, value)
def stringify(self, value):
self._validate_value(value)
return super(MACAddress, self).stringify(value)
class MACAddressField(obj_fields.AutoTypedField):
AUTO_TYPE = MACAddress()

View File

@ -260,6 +260,10 @@ def get_random_mac():
return ':'.join(map(lambda x: "%02x" % x, mac))
def get_random_EUI():
return netaddr.EUI(get_random_mac())
def get_random_ip_network(version=4):
return netaddr.IPNetwork(get_random_cidr(version=version))

View File

@ -16,6 +16,7 @@ import abc
from neutron.common import constants
from neutron.objects import common_types
from neutron.tests import base as test_base
from neutron.tests import tools
class TestField(object):
@ -95,6 +96,27 @@ class IPNetworkPrefixLenFieldTest(test_base.BaseTestCase, TestField):
self.assertEqual("%s" % in_val, self.field.stringify(in_val))
class MACAddressFieldTest(test_base.BaseTestCase, TestField):
def setUp(self):
super(MACAddressFieldTest, self).setUp()
self.field = common_types.MACAddressField()
mac1 = tools.get_random_EUI()
mac2 = tools.get_random_EUI()
self.coerce_good_values = [(mac1, mac1), (mac2, mac2)]
self.coerce_bad_values = [
'XXXX', 'ypp', 'g3:vvv',
# the field type is strict and does not allow to pass strings, even
# if they represent a valid MAC address
tools.get_random_mac(),
]
self.to_primitive_values = self.coerce_good_values
self.from_primitive_values = self.coerce_good_values
def test_stringify(self):
for in_val, out_val in self.coerce_good_values:
self.assertEqual('%s' % in_val, self.field.stringify(in_val))
class IPVersionEnumFieldTest(test_base.BaseTestCase, TestField):
def setUp(self):
super(IPVersionEnumFieldTest, self).setUp()