Example #1
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if len(self._options) == 0:
            raise ValidationError(
                "No options",
                reason=
                'no options given in options verifier, matching not possible',
                object=obj)

        exceptions = {}

        for i, option in enumerate(self._options):
            try:
                obj = option.verify(obj)
                return obj
            except ValidationError as exc:
                exceptions['option_%d' % (i + 1)] = exc.params['reason']

        raise ValidationError(
            "Object did not match any of a set of options",
            reason=
            "object did not match any given option (first failure = '%s')" %
            exceptions['option_1'],
            **exceptions)
Example #2
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Returns:
            bytes or byterray: The decoded byte buffer

        Raises:
            ValidationError: If there is a problem verifying the object, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if self.encoding == 'none' and not isinstance(obj, (bytes, bytearray)):
            raise ValidationError(
                'Byte object was not either bytes or a bytearray',
                type=obj.__class__.__name__)
        elif self.encoding == 'base64':
            try:
                data = base64.b64decode(obj)
                return data
            except TypeError:
                raise ValidationError("Could not decode base64 encoded bytes",
                                      obj=obj)
        elif self.encoding == 'hex':
            try:
                data = binascii.unhexlify(obj)
                return data
            except TypeError:
                raise ValidationError("Could not decode hex encoded bytes",
                                      obj=obj)

        return obj
Example #3
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if isinstance(obj, basestring):
            raise ValidationError(
                "Object was not a list",
                reason="a string was passed instead of a list",
                object=obj)

        out_obj = []
        if self._min_length is not None and len(obj) < self._min_length:
            raise ValidationError(
                "List was too short",
                reason="list length %d was less than the minimum %d" %
                (len(obj), self._min_length),
                min_length=self._min_length,
                actual_length=len(obj))

        if self._max_length is not None and len(obj) > self._max_length:
            raise ValidationError(
                "List was too long",
                reason="list length %d was greater than the maximum %d" %
                (len(obj), self._max_length),
                min_length=self._max_length,
                actual_length=len(obj))

        for val in obj:
            out_obj.append(self._verifier.verify(val))

        return out_obj
Example #4
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if not isinstance(obj, bool):
            raise ValidationError("Object is not a bool",
                                  reason='object is not a bool',
                                  object=obj)

        if self._require_value is not None and obj != self._require_value:
            raise ValidationError("Boolean is not equal to specified literal",
                                  reason='boolean value %s should be %s' %
                                  (str(obj), str(self._require_value)))

        return obj
Example #5
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema.

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if not isinstance(obj, float):
            raise ValidationError("Object is not a float", reason='object is not a float', object=obj)

        return obj
Example #6
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if obj != self._literal:
            raise ValidationError("Object is not equal to literal", reason='%s is not equal to %s' % (str(obj), str(self._literal)), object=obj)

        return obj
Example #7
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema.

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the object, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        if obj not in self.options:
            raise ValidationError(
                "Object is not in list of enumerated options",
                reason='not in list of enumerated options',
                object=obj,
                options=self.options)

        return obj
Example #8
0
    def dump_trace(self, encoding):
        """Dump all received tracing data currently received from the device to stdout

        The data is encoded per the encoding parmeter which must be either
        the string 'hex' or 'raw'.  If hex is passed, the data is printed as hex digits,
        if raw is passed, the data is printed as received from the device.
        """

        if encoding not in ['raw', 'hex']:
            raise ValidationError(
                "Unknown encoding type specified in dump trace",
                encoding=encoding,
                known_encodings=['hex', 'raw'])

        if self._trace_queue is None:
            return ""

        self._accumulate_trace()

        if encoding == 'raw':
            return bytes(self._trace_data)

        return binascii.hexlify(self._trace_data).decode('utf-8')
Example #9
0
    def verify(self, obj):
        """Verify that the object conforms to this verifier's schema

        Args:
            obj (object): A python object to verify

        Raises:
            ValidationError: If there is a problem verifying the dictionary, a
                ValidationError is thrown with at least the reason key set indicating
                the reason for the lack of validation.
        """

        out_obj = {}

        if not isinstance(obj, dict):
            raise ValidationError("Invalid dictionary",
                                  reason="object is not a dictionary")

        if self._fixed_length is not None and len(obj) != self._fixed_length:
            raise ValidationError("Dictionary did not have the correct length",
                                  expected_length=self._fixed_length,
                                  actual_length=self._fixed_length)

        unmatched_keys = set(obj.keys())
        required_keys = set(self._required_keys.keys())

        # First check and make sure that all required keys are included and verify them
        for key in required_keys:
            if key not in unmatched_keys:
                raise ValidationError("Required key not found in dictionary",
                                      reason="required key %s not found" % key,
                                      key=key)

            out_obj[key] = self._required_keys[key].verify(obj[key])
            unmatched_keys.remove(key)

        # Now check and see if any of the keys in the dictionary are optional and check them
        to_remove = set()
        for key in unmatched_keys:
            if key not in self._optional_keys:
                continue

            out_obj[key] = self._optional_keys[key].verify(obj[key])
            to_remove.add(key)

        unmatched_keys -= to_remove

        # If there are additional keys, they need to match at least one of the additional key rules
        if len(unmatched_keys) > 0:
            if len(self._additional_key_rules) == 0:
                raise ValidationError(
                    "Extra key found in dictionary that does not allow extra keys",
                    reason="extra keys found that were not expected",
                    keys=unmatched_keys)

            to_remove = set()
            for key in unmatched_keys:
                for key_match, rule in self._additional_key_rules:
                    if key_match is None or key_match.matches(key):
                        out_obj[key] = rule.verify(obj[key])
                        to_remove.add(key)
                        break

            unmatched_keys -= to_remove

            if len(unmatched_keys) > 0:
                raise ValidationError(
                    "Extra key found in dictionary that did not match any extra key rule",
                    reason="extra keys found that did not match any rule",
                    keys=unmatched_keys)

        return out_obj