Python jsonschema.exceptions() Examples

The following are code examples for showing how to use jsonschema.exceptions(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: notifiers   Author: notifiers   File: core.py    MIT License 6 votes vote down vote up
def _validate_data(self, data: dict):
        """
        Validates data against provider schema. Raises :class:`~notifiers.exceptions.BadArguments` if relevant

        :param data: Data to validate
        :raises: :class:`~notifiers.exceptions.BadArguments`
        """
        log.debug("validating provided data")
        e = best_match(self.validator.iter_errors(data))
        if e:
            custom_error_key = f"error_{e.validator}"
            msg = (
                e.schema[custom_error_key]
                if e.schema.get(custom_error_key)
                else e.message
            )
            raise BadArguments(validation_error=msg, provider=self.name, data=data) 
Example 2
Project: notifiers   Author: notifiers   File: core.py    MIT License 6 votes vote down vote up
def notify(self, raise_on_errors: bool = False, **kwargs) -> Response:
        """
        The main method to send notifications. Prepares the data via the
        :meth:`~notifiers.core.SchemaResource._prepare_data` method and then sends the notification
        via the :meth:`~notifiers.core.Provider._send_notification` method

        :param kwargs: Notification data
        :param raise_on_errors: Should the :meth:`~notifiers.core.Response.raise_on_errors` be invoked immediately
        :return: A :class:`~notifiers.core.Response` object
        :raises: :class:`~notifiers.exceptions.NotificationError` if ``raise_on_errors`` is set to True and response
         contained errors
        """
        data = self._process_data(**kwargs)
        rsp = self._send_notification(data)
        if raise_on_errors:
            rsp.raise_on_errors()
        return rsp 
Example 3
Project: cis   Author: mozilla-iam   File: test_profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_profile_validation(self):
        from cis_profile import profile
        import jsonschema.exceptions

        u = profile.User()
        u.validate()

        u.user_id.value = {"invalid": "test"}
        try:
            u.validate()
            raise Exception("ValidationFailure", "Should have failed validation, did not")
        except jsonschema.exceptions.ValidationError:
            pass
        else:
            raise Exception("ValidationFailure", "Should have failed validation, did not") 
Example 4
Project: cis   Author: mozilla-iam   File: test_profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_full_profile_signing_wrong_publisher(self):
        u = profile.User()
        u.fun_title.value = "test title"
        u.fun_title.signature.publisher.name = "wrong"
        try:
            u.sign_all(publisher_name="ldap")
        except cis_profile.exceptions.SignatureRefused:
            pass
        else:
            raise Exception("ValidationFailure", "Should have failed validation, did not") 
Example 5
Project: cis   Author: mozilla-iam   File: test_profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_single_attribute_signing(self):
        u = profile.User(user_id="test")
        u.sign_attribute("user_id", publisher_name="ldap")
        assert u.user_id.signature.publisher.value is not None
        assert len(u.user_id.signature.publisher.value) > 0

        # Empty attributes should be signed in this case since it's directly requested to be signed
        # (empty but not None)
        u.fun_title.value = ""
        u.sign_attribute("fun_title", publisher_name="ldap")
        assert u.fun_title.signature.publisher.value is not None
        assert len(u.fun_title.signature.publisher.value) > 0

        # test for subitems
        u.access_information.ldap.values = {"test": None}
        u.sign_attribute("access_information.ldap", publisher_name="ldap")
        assert u.access_information.ldap.signature.publisher.value is not None
        assert len(u.access_information.ldap.signature.publisher.value) > 0

        # test for NULL values
        try:
            u.active.value = None
            u.sign_attribute("active", publisher_name="ldap")
            raise Exception("ValidationFailure", "Should have failed validation, did not")
        except cis_profile.exceptions.SignatureRefused:
            pass
        else:
            raise Exception("ValidationFailure", "Should have failed validation, did not") 
Example 6
Project: cis   Author: mozilla-iam   File: test_profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_single_attribute_signing_verification(self):
        u = profile.User(user_id="test")
        u.sign_attribute("user_id", publisher_name="ldap")
        ret = u.verify_attribute_signature("user_id")
        assert ret is not None
        with pytest.raises(cis_profile.exceptions.SignatureVerificationFailure):
            u.verify_attribute_signature("fun_title")  # Unsigned, so should raise and fail 
Example 7
Project: cis   Author: mozilla-iam   File: test_profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_verify_can_publish(self):
        u_old = profile.User(user_id="test")
        u_new = copy.deepcopy(u_old)

        u_new.first_name["signature"]["publisher"]["name"] = "failure"
        u_new.first_name["value"] = "failure"
        with pytest.raises(cis_profile.exceptions.PublisherVerificationFailure):
            u_new.verify_can_publish(u_new.first_name, "first_name", previous_attribute=u_old.first_name) is True

        assert u_new.verify_can_publish(u_new.user_id, "user_id", previous_attribute=u_old.user_id) 
Example 8
Project: cloudformation-cli   Author: aws-cloudformation   File: test_data_loaders.py    Apache License 2.0 5 votes vote down vote up
def test_make_validator_handlers_time_out():
    from time import sleep

    @Request.application
    def application(request):  # pylint: disable=unused-argument
        sleep(3)
        return Response("true", mimetype="application/json")

    with wsgi_serve(application) as server:
        with pytest.raises(jsonschema.exceptions.RefResolutionError) as excinfo:
            validator = make_validator(
                {"$ref": server.url}, base_uri="http://localhost/", timeout=0.5
            )
            validator.validate(True)
    assert "Read timed out" in str(excinfo.value) 
Example 9
Project: routemaster   Author: thread   File: loader.py    MIT License 5 votes vote down vote up
def _schema_validate(config: Yaml) -> None:
    # Load schema from package resources
    schema_raw = pkg_resources.resource_string(
        'routemaster.config',
        'schema.yaml',
    ).decode('utf-8')
    schema_yaml = yaml.load(schema_raw)

    try:
        jsonschema.validate(config, schema_yaml)
    except jsonschema.exceptions.ValidationError:
        raise ConfigError("Could not validate config file against schema.") 
Example 10
Project: notifiers   Author: notifiers   File: core.py    MIT License 5 votes vote down vote up
def raise_on_errors(self):
        """
        Raises a :class:`~notifiers.exceptions.NotificationError` if response hold errors

        :raises: :class:`~notifiers.exceptions.NotificationError`: If response has errors
        """
        if self.errors:
            raise NotificationError(
                provider=self.provider,
                data=self.data,
                errors=self.errors,
                response=self.response,
            ) 
Example 11
Project: notifiers   Author: notifiers   File: core.py    MIT License 5 votes vote down vote up
def _validate_schema(self):
        """
        Validates provider schema for syntax issues. Raises :class:`~notifiers.exceptions.SchemaError` if relevant

        :raises: :class:`~notifiers.exceptions.SchemaError`
        """
        try:
            log.debug("validating provider schema")
            self.validator.check_schema(self.schema)
        except jsonschema.SchemaError as e:
            raise SchemaError(
                schema_error=e.message, provider=self.name, data=self.schema
            ) 
Example 12
Project: notifiers   Author: notifiers   File: core.py    MIT License 5 votes vote down vote up
def _validate_data_dependencies(self, data: dict) -> dict:
        """
        Validates specific dependencies based on the content of the data, as opposed to its structure which can be
        verified on the schema level

        :param data: Data to validate
        :return: Return data if its valid
        :raises: :class:`~notifiers.exceptions.NotifierException`
        """
        return data