Python jsonschema.exceptions.RefResolutionError() Examples

The following are code examples for showing how to use jsonschema.exceptions.RefResolutionError(). 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: invenio-deposit   Author: inveniosoftware   File: test_api.py    MIT License 6 votes vote down vote up
def test_schemas(app, fake_schemas, location):
    """Test schema URL transformations."""
    deposit = Deposit.create({})
    assert 'http://localhost/schemas/deposits/deposit-v1.0.0.json' == \
        deposit['$schema']

    assert 'http://localhost/schemas/deposit-v1.0.0.json' == \
        deposit.record_schema

    assert 'http://localhost/schemas/deposits/test-v1.0.0.json' == \
        deposit.build_deposit_schema({
            '$schema': 'http://localhost/schemas/test-v1.0.0.json',
        })

    with pytest.raises(RefResolutionError):
        Deposit.create({
            '$schema': 'http://localhost/schemas/deposits/invalid.json',
        }) 
Example 2
Project: python-ngoschema   Author: numengo   File: jsonschema.py    GNU General Public License v3.0 6 votes vote down vote up
def ref_ngo_draft2(validator, ref, instance, schema):
    # override reference with schema defined in instance
    if isinstance(instance, collections.Iterable) and "__schema__" in instance:
        ref = instance["__schema__"]

    resolve = getattr(validator.resolver, "resolve", None)
    if resolve is None:
        with validator.resolver.resolving(ref) as resolved:
            for error in validator.descend(instance, resolved):
                yield error
    else:
        try:
            scope, resolved = validator.resolver.resolve(ref)
            validator.resolver.push_scope(scope)
        except RefResolutionError as error:
            yield ValidationError("%s. Resolution scope=%s" %
                                  (error, validator.resolver.resolution_scope))
            return

        try:
            for error in validator.descend(instance, resolved):
                yield error
        finally:
            # pass
            validator.resolver.pop_scope() 
Example 3
Project: misp42splunk   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 4
Project: misp42splunk   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 5
Project: misp42splunk   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 6
Project: git_for_splunk   Author: ChrisYounger   File: validators.py    Apache License 2.0 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 7
Project: git_for_splunk   Author: ChrisYounger   File: validators.py    Apache License 2.0 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 8
Project: git_for_splunk   Author: ChrisYounger   File: validators.py    Apache License 2.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 9
Project: pyblish-rpc   Author: pyblish   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolving(self, ref):
        """
        Context manager which resolves a JSON ``ref`` and enters the
        resolution scope of this ref.

        :argument str ref: reference to resolve

        """

        full_uri = urljoin(self.resolution_scope, ref)
        uri, fragment = urldefrag(full_uri)
        if not uri:
            uri = self.base_uri

        if uri in self.store:
            document = self.store[uri]
        else:
            try:
                document = self.resolve_remote(uri)
            except Exception as exc:
                raise RefResolutionError(exc)

        old_base_uri, self.base_uri = self.base_uri, uri
        try:
            with self.in_scope(uri):
                yield self.resolve_fragment(document, fragment)
        finally:
            self.base_uri = old_base_uri 
Example 10
Project: pyblish-rpc   Author: pyblish   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 11
Project: python-ngoschema   Author: numengo   File: jsonschema.py    GNU General Public License v3.0 5 votes vote down vote up
def extends_ngo_draft1(validator, extends, instance, schema):
    if validator.is_type(extends, "array"):
        for ref in extends:
            try:
                _format_checker(validator).check(ref, "uri-reference")
                scope, resolved = validator.resolver.resolve(ref)
            except FormatError as er:
                yield ValidationError(str(er), cause=er.cause)
            except RefResolutionError as er:
                yield ValidationError(str(er)) 
Example 12
Project: pastebin2misp   Author: renzejongman   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`"
            ) 
Example 13
Project: pastebin2misp   Author: renzejongman   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 14
Project: pastebin2misp   Author: renzejongman   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        Arguments:

            document:

                The referrant document

            fragment (str):

                a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 15
Project: TA-thehive   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 16
Project: TA-thehive   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 17
Project: TA-thehive   Author: remg427   File: validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 18
Project: accelerated-data-lake   Author: aws-samples   File: validators.py    Apache License 2.0 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`"
            ) 
Example 19
Project: accelerated-data-lake   Author: aws-samples   File: validators.py    Apache License 2.0 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 20
Project: accelerated-data-lake   Author: aws-samples   File: validators.py    Apache License 2.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        Arguments:

            document:

                The referrant document

            fragment (str):

                a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 21
Project: TA-intezer   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 22
Project: TA-intezer   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 23
Project: TA-intezer   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 24
Project: Requester   Author: kylebebak   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`"
            ) 
Example 25
Project: Requester   Author: kylebebak   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 26
Project: Requester   Author: kylebebak   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        Arguments:

            document:

                The referrant document

            fragment (str):

                a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 27
Project: TA-securitytrails   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 28
Project: TA-securitytrails   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 29
Project: TA-securitytrails   Author: secops4thewin   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 30
Project: Pizza-or-Not-a-Pizza   Author: mraza007   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 31
Project: Pizza-or-Not-a-Pizza   Author: mraza007   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 32
Project: Pizza-or-Not-a-Pizza   Author: mraza007   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 33
Project: TA-bigfix   Author: jimmyatSplunk   File: validators.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 34
Project: TA-bigfix   Author: jimmyatSplunk   File: validators.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 35
Project: TA-bigfix   Author: jimmyatSplunk   File: validators.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 36
Project: cloudformation-cli   Author: aws-cloudformation   File: data_loaders.py    Apache License 2.0 5 votes vote down vote up
def load_resource_spec(resource_spec_file):
    """Load a resource provider definition from a file, and validate it."""
    try:
        resource_spec = json.load(resource_spec_file)
    except ValueError as e:
        LOG.debug("Resource spec decode failed", exc_info=True)
        raise SpecValidationError(str(e)) from e

    validator = make_resource_validator()
    try:
        validator.validate(resource_spec)
    except ValidationError as e:
        LOG.debug("Resource spec validation failed", exc_info=True)
        raise SpecValidationError(str(e)) from e

    # TODO: more general validation framework
    if "remote" in resource_spec:
        raise SpecValidationError(
            "Property 'remote' is reserved for CloudFormation use"
        )

    base_uri = get_file_base_uri(resource_spec_file)

    inliner = RefInliner(base_uri, resource_spec)
    try:
        inlined = inliner.inline()
    except RefResolutionError as e:
        LOG.debug("Resource spec validation failed", exc_info=True)
        raise SpecValidationError(str(e)) from e

    try:
        validator.validate(inlined)
    except ValidationError as e:
        LOG.debug("Inlined schema is no longer valid", exc_info=True)
        raise InternalError() from e

    return inlined 
Example 37
Project: cloudformation-cli   Author: aws-cloudformation   File: test_data_loaders.py    Apache License 2.0 5 votes vote down vote up
def test_load_resource_spec_invalid_ref():
    copy = json.loads(json.dumps(BASIC_SCHEMA))
    copy["properties"]["foo"] = {"$ref": "#/bar"}
    with pytest.raises(SpecValidationError) as excinfo:
        load_resource_spec(json_s(copy))

    cause = excinfo.value.__cause__
    assert cause
    assert isinstance(cause, RefResolutionError)
    assert "bar" in str(cause) 
Example 38
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 39
Project: StupidSimplePatchServer   Author: brysontyrrell   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`"
            ) 
Example 40
Project: StupidSimplePatchServer   Author: brysontyrrell   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 41
Project: StupidSimplePatchServer   Author: brysontyrrell   File: validators.py    MIT License 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        Arguments:

            document:

                The referrant document

            fragment (str):

                a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 42
Project: StupidSimplePatchServer   Author: brysontyrrell   File: validators.py    MIT License 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`"
            ) 
Example 43
Project: StupidSimplePatchServer   Author: brysontyrrell   File: validators.py    MIT License 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 44
Project: SA-ctf_scoreboard   Author: splunk   File: validators.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def pop_scope(self):
        try:
            self._scopes_stack.pop()
        except IndexError:
            raise RefResolutionError(
                "Failed to pop the scope from an empty stack. "
                "`pop_scope()` should only be called once for every "
                "`push_scope()`",
            ) 
Example 45
Project: SA-ctf_scoreboard   Author: splunk   File: validators.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def resolve_from_url(self, url):
        url, fragment = urldefrag(url)
        try:
            document = self.store[url]
        except KeyError:
            try:
                document = self.resolve_remote(url)
            except Exception as exc:
                raise RefResolutionError(exc)

        return self.resolve_fragment(document, fragment) 
Example 46
Project: SA-ctf_scoreboard   Author: splunk   File: validators.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def resolve_fragment(self, document, fragment):
        """
        Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it

        """

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document 
Example 47
Project: openapi3-validator   Author: usabilla   File: validator.py    MIT License 4 votes vote down vote up
def validate(url):
    counter = 0

    try:
        handler = UrlHandler('http', 'https', 'file')

        if not urlparse(url).scheme:
            url = 'file://' + path.join(getcwd(), url)

        spec = handler(url)

        for i in openapi_v3_spec_validator.iter_errors(spec, spec_url=url):
            counter += 1
            print_error(
                counter,
                ':'.join(i.absolute_path),
                i.message,
                i.instance
            )

    except RefResolutionError as e:
        counter += 1
        print_error(
            counter,
            '',
            f'Unable to resolve {e.__context__.args[0]} in {e.args[0]}',
            ''
        )
    except BaseException:
        counter += 1
        print_error(counter, '', sys.exc_info()[0], '')
    finally:
        if counter > 0:
            print()
            print(
                color(
                    ' [FAIL] %d errors found ' % counter,
                    fg='white',
                    bg='red',
                    style='bold'
                )
            )
            return 1
        else:
            print(
                color(
                    ' [PASS] No errors found ',
                    fg='white',
                    bg='green',
                    style='bold'
                )
            )
            return 0 
Example 48
Project: cti-stix-validator   Author: oasis-open   File: validator.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'):
    """Get a generator for validating against the schema for the given object type.

    Args:
        type (str): The object type to find the schema for.
        obj: The object to be validated.
        schema_dir (str): The path in which to search for schemas.
        version (str): The version of the STIX specification to validate
            against. Only used to find base schemas when schema_dir is None.
        default (str): If the schema for the given type cannot be found, use
            the one with this name instead.

    Returns:
        A generator for errors found when validating the object against the
        appropriate schema, or None if schema_dir is None and the schema
        cannot be found.
    """
    # If no schema directory given, use default for the given STIX version,
    # which comes bundled with this package
    if schema_dir is None:
        schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-'
                                     + version + '/')

    try:
        schema_path = find_schema(schema_dir, type)
        schema = load_schema(schema_path)
    except (KeyError, TypeError):
        # Assume a custom object with no schema
        try:
            schema_path = find_schema(schema_dir, default)
            schema = load_schema(schema_path)
        except (KeyError, TypeError):
            # Only raise an error when checking against default schemas, not custom
            if schema_dir is not None:
                return None
            raise SchemaInvalidError("Cannot locate a schema for the object's "
                                     "type, nor the base schema ({}.json).".format(default))

    if type == 'observed-data' and schema_dir is None:
        # Validate against schemas for specific observed data object types later.
        # If schema_dir is not None the schema is custom and won't need to be modified.
        schema['allOf'][1]['properties']['objects'] = {
            "objects": {
                "type": "object",
                "minProperties": 1
            }
        }

    # Don't use custom validator; only check schemas, no additional checks
    validator = load_validator(schema_path, schema)
    try:
        error_gen = validator.iter_errors(obj)
    except schema_exceptions.RefResolutionError:
        raise SchemaInvalidError('Invalid JSON schema: a JSON '
                                 'reference failed to resolve')
    return error_gen