示例#1
0
    def test_validate_dict_without_constraints(self):
        msg = validators.validate_dict({})
        self.assertIsNone(msg)

        # Validate a dictionary without constraints.
        msg = validators.validate_dict({'key': 'value'})
        self.assertIsNone(msg)
示例#2
0
    def test_validate_dict_without_constraints(self):
        msg = validators.validate_dict({})
        self.assertIsNone(msg)

        # Validate a dictionary without constraints.
        msg = validators.validate_dict({'key': 'value'})
        self.assertIsNone(msg)
示例#3
0
    def test_subdictionary(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key3']['k4']
        dictionary['key3']['k5'] = 'a string value'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)
示例#4
0
    def test_subdictionary(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key3']['k4']
        dictionary['key3']['k5'] = 'a string value'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)
示例#5
0
def validate_gwdevice_list(data, valid_values=None):
    """Validate the list of devices."""

    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg

    if len(data) > 1:
        # The number of devices must be exactly one
        msg = _("Exactly one device must be specified to create a gateway")
        return msg

    try:
        for device in data:
            err_msg = validators.validate_dict(device, None)
            if err_msg:
                return err_msg

            device_id = device.get('device_id')
            if not device_id:
                msg = _("Cannot create a gateway with an empty device_id")
                return msg

            # Don't accept any interface.  However, when supporting HW VTEPs
            # this must be supported.
            # TODO(RYU): Allow setting segmentation ID in some way
            if device.get('interfaces'):
                msg = _("Interfaces are not allowed in MidoNet L2GW")
                return msg
            device['interfaces'] = []
    except TypeError:
        return (_("%s: provided data are not iterable") %
                validate_gwdevice_list.__name__)
    return None
示例#6
0
def _validate_device_list(data, valid_values=None):
    """Validate the list of service definitions."""
    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg
    try:
        for device in data:
            key_specs = {DEVICE_ID_ATTR:
                         {'type:regex': constants.UUID_PATTERN,
                          'required': True},
                         IFACE_NAME_ATTR:
                         {'type:string': None,
                          'required': False}}
            err_msg = validators.validate_dict(
                device, key_specs=key_specs)
            if err_msg:
                return err_msg
            unexpected_keys = [key for key in device if key not in key_specs]
            if unexpected_keys:
                err_msg = (_("Unexpected keys found in device description:%s")
                           % ",".join(unexpected_keys))
                return err_msg
    except TypeError:
        return (_("%s: provided data are not iterable") %
                _validate_device_list.__name__)
示例#7
0
def _validate_device_list(data, valid_values=None):
    """Validate the list of service definitions."""
    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg
    try:
        for device in data:
            key_specs = {
                DEVICE_ID_ATTR: {
                    'type:regex': constants.UUID_PATTERN,
                    'required': True
                },
                IFACE_NAME_ATTR: {
                    'type:string': None,
                    'required': False
                }
            }
            err_msg = validators.validate_dict(device, key_specs=key_specs)
            if err_msg:
                return err_msg
            unexpected_keys = [key for key in device if key not in key_specs]
            if unexpected_keys:
                err_msg = (
                    _("Unexpected keys found in device description:%s") %
                    ",".join(unexpected_keys))
                return err_msg
    except TypeError:
        return (_("%s: provided data are not iterable") %
                _validate_device_list.__name__)
示例#8
0
    def test_validate_dict_not_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key2']
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Field that was not required by the specs was'
                               'required by the validator.')
示例#9
0
    def test_validate_dict_not_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key2']
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Field that was not required by the specs was'
                               'required by the validator.')
示例#10
0
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    """Validates a list of allowed address pair dicts.

    Validation herein requires the caller to have registered the
    max_allowed_address_pair oslo config option in the global CONF prior
    to having this validator used.

    :param address_pairs: A list of address pair dicts to validate.
    :param valid_values: Not used.
    :returns: None
    :raises: AllowedAddressPairExhausted if the address pairs requested
    exceeds cfg.CONF.max_allowed_address_pair. AllowedAddressPairsMissingIP
    if any address pair dicts are missing and IP address.
    DuplicateAddressPairInRequest if duplicated IPs are in the list of
    address pair dicts. Otherwise a HTTPBadRequest is raised if any of
    the address pairs are invalid.
    """
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise exc.HTTPBadRequest(_("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise exceptions.AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise exceptions.AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise exceptions.DuplicateAddressPairInRequest(
                mac_address=mac, ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(
            ['mac_address', 'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") % ', '.join(
                set(address_pair.keys()) - set(['mac_address', 'ip_address'])))
            raise exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise exc.HTTPBadRequest(msg)
示例#11
0
def _validate_extra_dhcp_opt(data, key_specs=None):
    if data is not None:
        if not isinstance(data, list):
            raise ExtraDhcpOptBadData(data=data)
        for d in data:
            if d['opt_name'] in VALID_BLANK_EXTRA_DHCP_OPTS:
                msg = validators.validate_string_or_none(
                    d['opt_value'], DHCP_OPT_VALUE_MAX_LEN)
            else:
                msg = validators.validate_dict(d, key_specs)
            if msg:
                raise ExtraDhcpOptBadData(data=msg)
示例#12
0
def _validate_extra_dhcp_opt(data, key_specs=None):
    if data is not None:
        if not isinstance(data, list):
            raise ExtraDhcpOptBadData(data=data)
        for d in data:
            if d['opt_name'] in VALID_BLANK_EXTRA_DHCP_OPTS:
                msg = validators.validate_string_or_none(
                    d['opt_value'], DHCP_OPT_VALUE_MAX_LEN)
            else:
                msg = validators.validate_dict(d, key_specs)
            if msg:
                raise ExtraDhcpOptBadData(data=msg)
示例#13
0
    def test_validate_dict_convert_boolean(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key_bool'] = {
            'type:boolean': None,
            'required': False,
            'convert_to': converters.convert_to_boolean}
        dictionary['key_bool'] = 'true'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg)
        # Explicitly comparing with literal 'True' as assertTrue
        # succeeds also for 'true'
        self.assertIs(True, dictionary['key_bool'])
示例#14
0
    def test_validate_dict_convert_boolean(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key_bool'] = {
            'type:boolean': None,
            'required': False,
            'convert_to': converters.convert_to_boolean}
        dictionary['key_bool'] = 'true'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg)
        # Explicitly comparing with literal 'True' as assertTrue
        # succeeds also for 'true'
        self.assertIs(True, dictionary['key_bool'])
示例#15
0
def validate_gwdevice_list(data, valid_values=None):
    """Validate the list of devices."""
    if not data:
        # Devices must be provided
        msg = _("Cannot create a gateway with an empty device list")
        return msg
    try:
        for device in data:
            interface_data = device.get(constants.IFACE_NAME_ATTR)
            device_name = device.get(constants.DEVICE_ID_ATTR)
            if not device_name:
                msg = _("Cannot create a gateway with an empty device_name")
                return msg
            if not interface_data:
                msg = _("Cannot create a gateway with an empty interfaces")
                return msg
            if not isinstance(interface_data, list):
                msg = _("interfaces format is not a type list of dicts")
                return msg
            for int_dict in interface_data:
                if not isinstance(int_dict, dict):
                    msg = _("interfaces format is not a type dict")
                    return msg
                err_msg = validators.validate_dict(int_dict, None)
                if not int_dict.get('name'):
                    msg = _("Cannot create a gateway with an empty "
                            "interface name")
                    return msg
                if constants.SEG_ID in int_dict:
                    seg_id_list = int_dict.get(constants.SEG_ID)
                    if seg_id_list and type(seg_id_list) is not list:
                        msg = _("segmentation_id type should be of list type ")
                        return msg
                    if not seg_id_list:
                        msg = _("segmentation_id_list should not be empty")
                        return msg
                    for seg_id in seg_id_list:
                        is_valid_vlan_id(seg_id)
                    if err_msg:
                        return err_msg
    except TypeError:
        return (_("%s: provided data are not iterable") %
                validate_gwdevice_list.__name__)
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise webob.exc.HTTPBadRequest(
            _("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise webob.exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise DuplicateAddressPairInRequest(mac_address=mac,
                                                ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(['mac_address',
                                                        'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") %
                   ', '.join(set(address_pair.keys()) -
                             set(['mac_address', 'ip_address'])))
            raise webob.exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise webob.exc.HTTPBadRequest(msg)
示例#17
0
def _validate_allowed_address_pairs(address_pairs, valid_values=None):
    unique_check = {}
    if not isinstance(address_pairs, list):
        raise webob.exc.HTTPBadRequest(
            _("Allowed address pairs must be a list."))
    if len(address_pairs) > cfg.CONF.max_allowed_address_pair:
        raise AllowedAddressPairExhausted(
            quota=cfg.CONF.max_allowed_address_pair)

    for address_pair in address_pairs:
        msg = validators.validate_dict(address_pair)
        if msg:
            return msg
        # mac_address is optional, if not set we use the mac on the port
        if 'mac_address' in address_pair:
            msg = validators.validate_mac_address(address_pair['mac_address'])
            if msg:
                raise webob.exc.HTTPBadRequest(msg)
        if 'ip_address' not in address_pair:
            raise AllowedAddressPairsMissingIP()

        mac = address_pair.get('mac_address')
        ip_address = address_pair['ip_address']
        if (mac, ip_address) not in unique_check:
            unique_check[(mac, ip_address)] = None
        else:
            raise DuplicateAddressPairInRequest(mac_address=mac,
                                                ip_address=ip_address)

        invalid_attrs = set(address_pair.keys()) - set(
            ['mac_address', 'ip_address'])
        if invalid_attrs:
            msg = (_("Unrecognized attribute(s) '%s'") % ', '.join(
                set(address_pair.keys()) - set(['mac_address', 'ip_address'])))
            raise webob.exc.HTTPBadRequest(msg)

        if '/' in ip_address:
            msg = validators.validate_subnet(ip_address)
        else:
            msg = validators.validate_ip_address(ip_address)
        if msg:
            raise webob.exc.HTTPBadRequest(msg)
示例#18
0
    def test_validate_dict_wrong_values(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        dictionary['key1'] = 'UNSUPPORTED'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNotNone(msg)
示例#19
0
    def test_validate_dict_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key1']
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)
示例#20
0
    def test_validate_dict_with_invalid_validator(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key1'] = {'type:unsupported': None, 'required': True}
        msg = validators.validate_dict(dictionary, constraints)
        self.assertEqual("Validator 'type:unsupported' does not exist.", msg)
示例#21
0
    def test_validate_a_valid_dict_with_constraints(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
示例#22
0
 def test_validate_dict_type(self):
     for value in (None, True, '1', []):
         self.assertEqual("'%s' is not a dictionary" % value,
                          validators.validate_dict(value))
示例#23
0
    def test_validate_dict_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key1']
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)
示例#24
0
    def test_validate_a_valid_dict_with_constraints(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
示例#25
0
    def test_validate_dict_unexpected_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        dictionary['unexpected_key'] = 'val'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Unexpected keys supplied:', msg)
示例#26
0
    def test_validate_dict_unexpected_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        dictionary['unexpected_key'] = 'val'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIn('Unexpected keys supplied:', msg)
示例#27
0
 def test_validate_dict_type(self):
     for value in (None, True, '1', []):
         self.assertEqual("'%s' is not a dictionary" % value,
                          validators.validate_dict(value))
示例#28
0
    def test_validate_dict_wrong_values(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        dictionary['key1'] = 'UNSUPPORTED'
        msg = validators.validate_dict(dictionary, constraints)
        self.assertIsNotNone(msg)
示例#29
0
    def test_validate_dict_with_invalid_validator(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key1'] = {'type:unsupported': None, 'required': True}
        msg = validators.validate_dict(dictionary, constraints)
        self.assertEqual("Validator 'type:unsupported' does not exist.", msg)