Python marshmallow.ValidationError() Examples

The following are 30 code examples of marshmallow.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module marshmallow , or try the search function .
Example #1
Source File: parameters.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def validate_patch_structure(self, data):
        """
        Common validation of PATCH structure

        Provide check that 'value' present in all operations expect it.

        Provide check if 'path' is present. 'path' can be absent if provided
        without '/' at the start. Supposed that if 'path' is present than it
        is prepended with '/'.
        Removing '/' in the beginning to simplify usage in resource.
        """
        if data['op'] not in self.NO_VALUE_OPERATIONS and 'value' not in data:
            raise ValidationError('value is required')

        if 'path' not in data:
            raise ValidationError('Path is required and must always begin with /')
        else:
            data['field_name'] = data['path'][1:] 
Example #2
Source File: add_shortcut.py    From cartography with Apache License 2.0 6 votes vote down vote up
def run_add_shortcut(config):
    """
    Runs add_shortcut from the command line. Does error handling.

    :type config: Config Object
    :param config: Config of adding shortcut
    :return:
    """
    if not valid_directory(config.query_directory):
        logger.error("Invalid Drift Detection Directory")
        return
    try:
        add_shortcut(FileSystem, ShortcutSchema(), config.query_directory, config.shortcut, config.filename)
    except ValidationError as err:
        msg = "Could not load shortcut file from json file {} in query directory {}.".format(
            err.messages,
            config.query_directory,
        )
        logger.exception(msg) 
Example #3
Source File: connection_endpoint.py    From airflow with Apache License 2.0 6 votes vote down vote up
def post_connection(session):
    """
    Create connection entry
    """
    body = request.json
    try:
        result = connection_schema.load(body)
    except ValidationError as err:
        raise BadRequest(detail=str(err.messages))
    data = result.data
    conn_id = data['conn_id']
    query = session.query(Connection)
    connection = query.filter_by(conn_id=conn_id).first()
    if not connection:
        connection = Connection(**data)
        session.add(connection)
        session.commit()
        return connection_schema.dump(connection)
    raise AlreadyExists("Connection already exist. ID: %s" % conn_id) 
Example #4
Source File: patron_loan_extension_actions.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def validate_action(self, data=None, **kwargs):
        """Validate action."""
        no_payload = data is None
        if no_payload:
            # marshmallow needs a default empty payload
            data = {}
        record = self.context["record"]
        ext_status = validate_statuses(record)
        if ext_status == "PENDING":
            raise ValidationError(
                "An extension for this interlibrary loan has already been "
                "requested."
            )
        elif ext_status == "DECLINED":
            raise ValidationError(
                "Cannot request an extension for this interlibrary loan "
                "because the most recent extension request has been declined."
            )
        return data 
Example #5
Source File: patron_loan_extension_actions.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def validate_statuses(record):
    """Validate that the extension action can be performed."""
    if record["status"] != "ON_LOAN":
        raise ValidationError(
            "This interlibrary loan is currently not on loan."
        )

    ext_status = (
        record.get("patron_loan", {}).get("extension", {}).get("status")
    )
    # status = None is valid, no extension requested yet
    has_status = ext_status is not None
    is_valid = ext_status in BorrowingRequest.EXTENSION_STATUSES
    if has_status and not is_valid:
        # should never happen, a status that is not in the valid ones
        raise ValidationError(
            "The current extension status ({}) is invalid.".format(ext_status)
        )
    return ext_status 
Example #6
Source File: variable_endpoint.py    From airflow with Apache License 2.0 6 votes vote down vote up
def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) -> Response:
    """
    Update a variable by key
    """
    try:
        var = variable_schema.load(request.json)
    except ValidationError as err:
        raise BadRequest("Invalid Variable schema", detail=str(err.messages))

    if var.data["key"] != variable_key:
        raise BadRequest("Invalid post body", detail="key from request body doesn't match uri parameter")

    if update_mask:
        if "key" in update_mask:
            raise BadRequest("key is a ready only field")
        if "value" not in update_mask:
            raise BadRequest("No field to update")

    Variable.set(var.data["key"], var.data["val"])
    return Response(status=204) 
Example #7
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_sha256(self):
        non_sha256s = [
            "####",
            "abcd123",
            "________________________________________________________________",
            "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",
        ]
        for non_sha256 in non_sha256s:
            with self.assertRaises(ValidationError):
                SHA256["validate"](non_sha256)

        SHA256["validate"](
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        )
        SHA256["validate"](
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
        ) 
Example #8
Source File: connection_invitation.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def validate_fields(self, data, **kwargs):
        """
        Validate schema fields.

        Args:
            data: The data to validate

        Raises:
            ValidationError: If any of the fields do not validate

        """
        if data.get("did"):
            if data.get("recipient_keys"):
                raise ValidationError(
                    "Fields are incompatible", ("did", "recipientKeys")
                )
            if data.get("endpoint"):
                raise ValidationError(
                    "Fields are incompatible", ("did", "serviceEndpoint")
                )
        elif not data.get("recipient_keys") or not data.get("endpoint"):
            raise ValidationError(
                "Missing required field(s)", ("did", "recipientKeys", "serviceEndpoint")
            ) 
Example #9
Source File: invitation.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def validate_fields(self, data, **kwargs):
        """
        Validate schema fields.

        Args:
            data: The data to validate
        Raises:
            ValidationError: If any of the fields do not validate
        """
        handshake_protocols = data.get("handshake_protocols")
        request_attach = data.get("request_attach")
        if not (
            (handshake_protocols and len(handshake_protocols) > 0)
            or (request_attach and len(request_attach) > 0)
        ):
            raise ValidationError(
                "Model must include non-empty "
                + "handshake_protocols or request_attach or both"
            )

        # service = data.get("service")
        # if not ((service and len(service) > 0)):
        #     raise ValidationError(
        #         "Model must include non-empty service array"
        #     ) 
Example #10
Source File: base.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def deserialize(cls, obj):
        """
        Convert from JSON representation to a model instance.

        Args:
            obj: The dict to load into a model instance

        Returns:
            A model instance for this data

        """
        schema = cls._get_schema_class()(unknown=EXCLUDE)
        try:
            return schema.loads(obj) if isinstance(obj, str) else schema.load(obj)
        except ValidationError as e:
            LOGGER.exception(f"{cls.__name__} message validation error:")
            raise BaseModelError(f"{cls.__name__} schema validation failed") from e 
Example #11
Source File: base.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def serialize(self, as_string=False) -> dict:
        """
        Create a JSON-compatible dict representation of the model instance.

        Args:
            as_string: Return a string of JSON instead of a dict

        Returns:
            A dict representation of this model, or a JSON string if as_string is True

        """
        schema = self.Schema(unknown=EXCLUDE)
        try:
            return schema.dumps(self) if as_string else schema.dump(self)
        except ValidationError as e:
            LOGGER.exception(f"{self.__class__.__name__} message serialization error:")
            raise BaseModelError(
                f"{self.__class__.__name__} schema validation failed"
            ) from e 
Example #12
Source File: views.py    From Flask-SQLALchemy-RESTFUL-API with MIT License 6 votes vote down vote up
def post(self):
        raw_dict = request.get_json(force=True)
        try:
                schema.validate(raw_dict)
                user_dict = raw_dict['data']['attributes']
                user = Users(user_dict['email'], user_dict['name'],user_dict['is_active'])
                user.add(user)            
                query = Users.query.get(user.id)
                results = schema.dump(query).data                
                return results, 201
            
        except ValidationError as err:
                resp = jsonify({"error": err.messages})
                resp.status_code = 403
                return resp               
                
        except SQLAlchemyError as e:
                db.session.rollback()
                resp = jsonify({"error": str(e)})
                resp.status_code = 403
                return resp 
Example #13
Source File: parameters.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def perform_patch(cls, operations, obj, state=None):
        """
        Performs all necessary operations by calling class methods with
        corresponding names.
        """
        if state is None:
            state = {}
        for operation in operations:
            if not cls._process_patch_operation(operation, obj=obj, state=state):
                log.info(
                    "%s patching has been stopped because of unknown operation %s",
                    obj.__class__.__name__,
                    operation
                )
                raise ValidationError(
                    "Failed to update %s details. Operation %s could not succeed." % (
                        obj.__class__.__name__,
                        operation
                    )
                )
        return True 
Example #14
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_indy_date(self):
        non_datetimes = [
            "nope",
            "2020-01-01",
            "2020-01-01:00:00:00Z",
            "2020.01.01 00:00:00Z",
            "2020-01-01T00:00.123456+00:00",
            "2020-01-01T00:00:00.123456+0:00",
        ]
        for non_datetime in non_datetimes:
            with self.assertRaises(ValidationError):
                INDY_ISO8601_DATETIME["validate"](non_datetime)

        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00Z")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01T00:00:00Z")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01T00:00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00+00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00-00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00-00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00.1-00:00")
        INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00.123456-00:00") 
Example #15
Source File: decorators.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def requires_identity(f):
    """Wrapper which indicates that route requires user identification."""
    # noqa
    @wraps(f)
    def decorated_function(*args, **kws):
        """Represents decorated function."""
        try:
            user = UserIdentityHeaders().load(request.headers)
        except (ValidationError, KeyError):
            err_message = 'user identification is incorrect or missing'
            return jsonify(
                error={
                    'code': INVALID_HEADERS_ERROR_CODE,
                    'reason': err_message
                }
            )

        return f(user, *args, **kws)

    return decorated_function 
Example #16
Source File: decorators.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def handle_validation_except(f):
    """Wrapper which handles marshmallow `ValidationError`."""
    # noqa
    @wraps(f)
    def decorated_function(*args, **kwargs):
        """Represents decorated function."""
        try:
            return f(*args, **kwargs)
        except ValidationError as e:
            return jsonify(
                error={
                    'code': INVALID_PARAMS_ERROR_CODE,
                    'reason': e.messages,
                }
            )

    return decorated_function 
Example #17
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_endpoint(self):
        non_endpoints = [
            "123",
            "",
            "/path/only",
            "https://1.2.3.4?query=true&url=false",
            "http://no_tld/bad",
            "no-proto:8080/my/path",
            "smtp:8080/my/path#fragment",
        ]

        for non_endpoint in non_endpoints:
            with self.assertRaises(ValidationError):
                ENDPOINT["validate"](non_endpoint)

        ENDPOINT["validate"]("http://github.com")
        ENDPOINT["validate"]("https://localhost:8080")
        ENDPOINT["validate"]("newproto://myhost.ca:8080/path")
        ENDPOINT["validate"]("ftp://10.10.100.90:8021")
        ENDPOINT["validate"]("zzzp://someplace.ca:9999/path") 
Example #18
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_schema_id(self):
        non_schema_ids = [
            "Q4zqM7aXqm7gDQkUVLng9h:3:bc-reg:1.0",
            "Q4zqM7aXqm7gDQkUVLng9h::bc-reg:1.0",
            "Q4zqM7aXqm7gDQkUVLng9h:bc-reg:1.0",
            "Q4zqM7aXqm7gDQkUVLng9h:2:1.0",
            "Q4zqM7aXqm7gDQkUVLng9h:2::1.0",
            "Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:",
            "Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0a",
            "Q4zqM7aXqm7gDQkUVLng9I:2:bc-reg:1.0",  # I is not in base58
        ]
        for non_schema_id in non_schema_ids:
            with self.assertRaises(ValidationError):
                INDY_SCHEMA_ID["validate"](non_schema_id)

        INDY_SCHEMA_ID["validate"]("Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0") 
Example #19
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_jws_header_kid(self):
        non_kids = [
            "http://not-this.one",
            "did:sov:i",  # too short
            "did:key:Q4zqM7aXqm7gDQkUVLng9h"  # missing leading z
            "did:key:zI4zqM7aXqm7gDQkUVLng9h",  # 'I' not a base58 char
        ]
        for non_kid in non_kids:
            with self.assertRaises(ValidationError):
                JWS_HEADER_KID["validate"](non_kid)

        JWS_HEADER_KID["validate"]("did:key:zQ4zqM7aXqm7gDQkUVLng9h")
        JWS_HEADER_KID["validate"]("did:sov:Q4zqM7aXqm7gDQkUVLng9h#abc-123")
        JWS_HEADER_KID["validate"](
            "did:sov:Q4zqM7aXqm7gDQkUVLng9h?version-time=1234567890#abc-123"
        )
        JWS_HEADER_KID["validate"](
            "did:sov:Q4zqM7aXqm7gDQkUVLng9h?version-time=1234567890&a=b#abc-123"
        )
        JWS_HEADER_KID["validate"](
            "did:sov:Q4zqM7aXqm7gDQkUVLng9h;foo:bar=low;a=b?version-id=1&a=b#abc-123"
        ) 
Example #20
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_cred_def_id(self):
        non_cred_def_ids = [
            "Q4zqM7aXqm7gDQkUVLng9h:4:CL:18:0",
            "Q4zqM7aXqm7gDQkUVLng9h::CL:18:0",
            "Q4zqM7aXqm7gDQkUVLng9I:3:CL:18:tag",
            "Q4zqM7aXqm7gDQkUVLng9h:3::18:tag",
            "Q4zqM7aXqm7gDQkUVLng9h:3:18:tag",
        ]
        for non_cred_def_id in non_cred_def_ids:
            with self.assertRaises(ValidationError):
                INDY_CRED_DEF_ID["validate"](non_cred_def_id)

        INDY_CRED_DEF_ID["validate"]("Q4zqM7aXqm7gDQkUVLng9h:3:CL:18:tag")  # short
        INDY_CRED_DEF_ID["validate"](
            "Q4zqM7aXqm7gDQkUVLng9h:3:CL:Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0:tag"
        )  # long 
Example #21
Source File: schema.py    From packit-service with MIT License 5 votes vote down vote up
def _deserialize(
        self,
        value: typing.Any,
        attr: typing.Optional[str],
        data: typing.Optional[typing.Mapping[str, typing.Any]],
        **kwargs,
    ) -> Deployment:

        if not isinstance(value, str):
            raise ValidationError("Invalid data provided. str required")

        return Deployment(value) 
Example #22
Source File: datasets.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def check_filters(self, data, **kwargs):
        """Check filters."""
        include_filter = data.get('include_filters')
        exclude_filter = data.get('exclude_filters')

        if not include_filter and not exclude_filter:
            raise marshmallow.ValidationError(
                'one of the filters must be specified'
            )

        return data 
Example #23
Source File: headers.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def extract_token(self, data):
        """Extract token."""
        value = data.get('authorization', '')
        components = value.split(' ')

        rfc_compliant = value.lower().startswith('bearer')
        rfc_compliant &= len(components) == 2

        if not rfc_compliant:
            raise ValidationError('authorization value contains invalid value')

        return components[-1] 
Example #24
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_indy_base58_sha256_hash(self):
        non_base58_sha256_hashes = [
            "Q4zqM7aXqm7gDQkUVLng9JQ4zqM7aXqm7gDQkUVLng9I",  # 'I' not a base58 char
            "Q4zqM7aXqm7gDQkUVLng",  # too short
            "Q4zqM7aXqm7gDQkUVLngZZZZZZZZZZZZZZZZZZZZZZZZZ",  # too long
        ]
        for non_base58_sha256_hash in non_base58_sha256_hashes:
            with self.assertRaises(ValidationError):
                BASE58_SHA256_HASH["validate"](non_base58_sha256_hash)

        BASE58_SHA256_HASH["validate"]("Q4zqM7aXqm7gDQkUVLng9hQ4zqM7aXqm7gDQkUVLng9h") 
Example #25
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_uuid4(self):
        non_uuid4s = [
            "123",
            "",
            "----",
            "3fa85f6-5717-4562-b3fc-2c963f66afa6",  # short a hex digit
            "3fa85f645-5717-4562-b3fc-2c963f66afa6",  # extra hex digit
            "3fa85f64-5717-f562-b3fc-2c963f66afa6",  # 13th hex digit is not 4
        ]
        for non_uuid4 in non_uuid4s:
            with self.assertRaises(ValidationError):
                UUID4["validate"](non_uuid4)

        UUID4["validate"]("3fa85f64-5717-4562-b3fc-2c963f66afa6")
        UUID4["validate"]("3FA85F64-5717-4562-B3FC-2C963F66AFA6")  # upper case OK 
Example #26
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_indy_extra_wql(self):
        non_xwqls = [
            "nope",
            "[a, b, c]",
            "{1, 2, 3}",
            set(),
            '"Hello World"',
            None,
            "null",
            "true",
            False,
            "{}",
            '{"no": "referent"}',
            '{"no": "referent", "another": "non-referent"}',
            '{"uuid": {"too many: "braces"}}}',
        ]
        for non_xwql in non_xwqls:
            with self.assertRaises(ValidationError):
                INDY_EXTRA_WQL["validate"](non_xwql)

        INDY_EXTRA_WQL["validate"](json.dumps({"uuid0": {"name::ident::marker": "1"}}))
        INDY_EXTRA_WQL["validate"](
            json.dumps(
                {
                    "uuid0": {"attr::ident::marker": "1"},
                    "uuid1": {"attr::member::value": "655321"},
                    "uuid2": {"attr::code::value": {"$in": ["abc", "def", "ghi"]}},
                    "uuid3": {"attr::score::value": {"$neq": "0"}},
                }
            )
        ) 
Example #27
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_predicate(self):
        non_predicates = [">>", "", " >= ", "<<<=", "==", "=", "!="]
        for non_predicate in non_predicates:
            with self.assertRaises(ValidationError):
                INDY_PREDICATE["validate"](non_predicate)

        INDY_PREDICATE["validate"]("<")
        INDY_PREDICATE["validate"]("<=")
        INDY_PREDICATE["validate"](">=")
        INDY_PREDICATE["validate"](">") 
Example #28
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_version(self):
        non_versions = ["-1", "", "3_5", "3.5a"]
        for non_version in non_versions:
            with self.assertRaises(ValidationError):
                INDY_VERSION["validate"](non_version)

        INDY_VERSION["validate"]("1.0")
        INDY_VERSION["validate"](".05")
        INDY_VERSION["validate"]("1.2.3")
        INDY_VERSION["validate"]("..")  # perverse but technically OK 
Example #29
Source File: test_valid.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_cred_rev_id(self):
        non_cred_rev_ids = ["Wg", "0", "-5", "3.14"]
        for non_cred_rev_id in non_cred_rev_ids:
            with self.assertRaises(ValidationError):
                INDY_CRED_REV_ID["validate"](non_cred_rev_id)

        INDY_CRED_REV_ID["validate"]("1")
        INDY_CRED_REV_ID["validate"]("99999999") 
Example #30
Source File: test_schemas.py    From notifications-api with MIT License 5 votes vote down vote up
def test_user_update_schema_rejects_invalid_attribute_pairs(user_attribute, user_value):
    from app.schemas import user_update_schema_load_json
    update_dict = {
        user_attribute: user_value
    }

    with pytest.raises(ValidationError):
        data, errors = user_update_schema_load_json.load(update_dict)