Python jsonschema.exceptions.ValidationError() Examples

The following are code examples for showing how to use jsonschema.exceptions.ValidationError(). 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: signals   Author: Amsterdam   File: mixin.py    Mozilla Public License 2.0 7 votes vote down vote up
def get_interval_type(value):
    """
    Determine intended interval parametrization using JSON Schema.
    """
    # Note: we raise a Django validation error if the data does not match one
    # of interval JSON Schemas.
    for interval_type, schema in SCHEMAS.items():
        try:
            validate(instance=value, schema=schema)
        except JSONSchemaValidationError:
            continue
        else:
            return interval_type
    else:
        msg = 'Export parameters do not match schema.'
        raise DjangoValidationError(msg) 
Example 2
Project: invenio-openaire   Author: inveniosoftware   File: test_resolvers.py    MIT License 6 votes vote down vote up
def test_funder_schema_ep_resolving(app, db):
    """Test schema validation using entry-point registered schemas."""
    json_valid = {
        '$schema': (
            'http://inveniosoftware.org/schemas/funders/funder-v1.0.0.json'),
        'doi': '10.13039/001',
        'alternateIdentifiers': [],
        'title': 'Foobar',
        'acronyms': ['FB', 'Foo'],
        'country': 'PL',
        'type': 'org',
        'subtype': 'organization',
        'parent': {'$ref': 'http://dx.doi.org/10.13039/002'},
    }
    json_invalid = dict(json_valid)
    json_invalid['acronyms'] = 'not_a_list'
    # Should not raise validation errors
    R.create(json_valid)
    # Should raise validation error beucase of the field 'acronyms'
    with pytest.raises(ValidationError) as exc_info:
        R.create(json_invalid)
    assert exc_info.value.instance == 'not_a_list' 
Example 3
Project: drydock   Author: airshipit   File: test_schema_validation.py    Apache License 2.0 6 votes vote down vote up
def _test_validate(self, schema, expect_failure, input_files, input):
        """validates input yaml against schema.

        :param schema: schema yaml file
        :param expect_failure: should the validation pass or fail.
        :param input_files: pytest fixture used to access the test input files
        :param input: test input yaml doc filename"""
        schema_dir = pkg_resources.resource_filename('drydock_provisioner',
                                                     'schemas')
        schema_filename = os.path.join(schema_dir, schema)
        schema_file = open(schema_filename, 'r')
        schema = yaml.safe_load(schema_file)

        input_file = input_files.join(input)
        instance_file = open(str(input_file), 'r')
        instance = yaml.safe_load(instance_file)

        if expect_failure:
            with pytest.raises(ValidationError):
                jsonschema.validate(instance['spec'], schema['data'])
        else:
            jsonschema.validate(instance['spec'], schema['data']) 
Example 4
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 6 votes vote down vote up
def test_publishers(document_schema, minimal_document_record):
    """Test publishers for jsonschema."""
    minimal_document_record['publishers'] = [
        {
            'name': ['Editions de la Centrale'],
            'place': ['Martigny']
        }
    ]

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['publishers'][0]['name'][0] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['publishers'][0]['place'][0] = [2]
        validate(minimal_document_record, document_schema) 
Example 5
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: validators.py    Apache License 2.0 6 votes vote down vote up
def validate(self, *args, **kwargs):
        try:
            self.validator.validate(*args, **kwargs)
        except jsonschema.ValidationError as ex:
            if isinstance(ex.cause, exception.InvalidName):
                detail = ex.cause.format_message()
            elif len(ex.path) > 0:
                # NOTE: For whole OpenStack message consistency, this error
                #       message has been written as the similar format of WSME.
                detail = _("Invalid input for field/attribute %(path)s."
                           " Value: %(value)s. %(message)s") % {
                               'path': ex.path.pop(), 'value': ex.instance,
                               'message': ex.message
                           }
            else:
                detail = ex.message
            raise exception.ValidationError(detail=detail)
        except TypeError as ex:
            # NOTE: If passing non string value to patternProperties parameter,
            #       TypeError happens. Here is for catching the TypeError.
            detail = six.text_type(ex)
            raise exception.ValidationError(detail=detail) 
Example 6
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def additionalItems(validator, aI, instance, schema):
    if (
        not validator.is_type(instance, "array") or
        validator.is_type(schema.get("items", {}), "object")
    ):
        return

    len_items = len(schema.get("items", []))
    if validator.is_type(aI, "object"):
        for index, item in enumerate(instance[len_items:], start=len_items):
            for error in validator.descend(item, aI, path=index):
                yield error
    elif not aI and len(instance) > len(schema.get("items", [])):
        error = "Additional items are not allowed (%s %s unexpected)"
        yield ValidationError(
            error %
            _utils.extras_msg(instance[len(schema.get("items", [])):])
        ) 
Example 7
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def dependencies(validator, dependencies, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, dependency in iteritems(dependencies):
        if property not in instance:
            continue

        if validator.is_type(dependency, "object"):
            for error in validator.descend(
                instance, dependency, schema_path=property,
            ):
                yield error
        else:
            dependencies = _utils.ensure_list(dependency)
            for dependency in dependencies:
                if dependency not in instance:
                    yield ValidationError(
                        "%r is a dependency of %r" % (dependency, property)
                    ) 
Example 8
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def type_draft3(validator, types, instance, schema):
    types = _utils.ensure_list(types)

    all_errors = []
    for index, type in enumerate(types):
        if type == "any":
            return
        if validator.is_type(type, "object"):
            errors = list(validator.descend(instance, type, schema_path=index))
            if not errors:
                return
            all_errors.extend(errors)
        else:
            if validator.is_type(instance, type):
                return
    else:
        yield ValidationError(
            _utils.types_msg(instance, types), context=all_errors,
        ) 
Example 9
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def properties_draft3(validator, properties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, subschema in iteritems(properties):
        if property in instance:
            for error in validator.descend(
                instance[property],
                subschema,
                path=property,
                schema_path=property,
            ):
                yield error
        elif subschema.get("required", False):
            error = ValidationError("%r is a required property" % property)
            error._set(
                validator="required",
                validator_value=subschema["required"],
                instance=instance,
                schema=schema,
            )
            error.path.appendleft(property)
            error.schema_path.extend([property, "required"])
            yield error 
Example 10
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def oneOf_draft4(validator, oneOf, instance, schema):
    subschemas = enumerate(oneOf)
    all_errors = []
    for index, subschema in subschemas:
        errs = list(validator.descend(instance, subschema, schema_path=index))
        if not errs:
            first_valid = subschema
            break
        all_errors.extend(errs)
    else:
        yield ValidationError(
            "%r is not valid under any of the given schemas" % (instance,),
            context=all_errors,
        )

    more_valid = [s for i, s in subschemas if validator.is_valid(instance, s)]
    if more_valid:
        more_valid.append(first_valid)
        reprs = ", ".join(repr(schema) for schema in more_valid)
        yield ValidationError(
            "%r is valid under each of %s" % (instance, reprs)
        ) 
Example 11
Project: invenio-openaire   Author: inveniosoftware   File: test_resolvers.py    MIT License 5 votes vote down vote up
def test_grant_schema_ep_resolving(app, db):
    """Test schema validation using entry-point registered schemas."""
    json_valid = {
        '$schema': (
            'http://inveniosoftware.org/schemas/grants/grant-v1.0.0.json'),
        'internal_id': '10.13039/001::0001',
        'identifiers': {
            'oai_id': 'oai_id00001',
            'eurepo': '/eurepo/id00001',
        },
        'code': '0001',
        'title': 'Grant Foobar',
        'acronym': 'GF',
        'startdate': 'startdate',
        'enddate': 'startdate',
        'funder': {'$ref': 'http://dx.doi.org/10.13039/001'},
    }
    # Should not raise validation errors
    R.create(json_valid)

    # Should raise validation error because of the field 'acronyms'
    json_invalid = dict(json_valid)
    json_invalid['identifiers'] = 'not_an_object'
    with pytest.raises(ValidationError) as exc_info:
        R.create(json_invalid)
    assert exc_info.value.instance == 'not_an_object' 
Example 12
Project: reroils-data-legacy   Author: rero   File: test_locations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(location_schema, minimal_location_record):
    """Test required for location jsonschema."""
    validate(minimal_location_record, location_schema)

    with pytest.raises(ValidationError):
        validate({}, location_schema)
        validate(minimal_location_record, location_schema) 
Example 13
Project: reroils-data-legacy   Author: rero   File: test_locations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pid(location_schema, minimal_location_record):
    """Test pid for location jsonschema."""
    validate(minimal_location_record, location_schema)

    with pytest.raises(ValidationError):
        minimal_location_record['pid'] = 25
        validate(minimal_location_record, location_schema) 
Example 14
Project: reroils-data-legacy   Author: rero   File: test_locations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_name(location_schema, minimal_location_record):
    """Test name for location jsonschema."""
    validate(minimal_location_record, location_schema)

    with pytest.raises(ValidationError):
        minimal_location_record['name'] = 25
        validate(minimal_location_record, location_schema) 
Example 15
Project: reroils-data-legacy   Author: rero   File: test_organisations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(organisation_schema, minimal_organisation_record):
    """Test required for organisation jsonschema."""
    validate(minimal_organisation_record, organisation_schema)

    with pytest.raises(ValidationError):
        validate({}, organisation_schema)
        validate(minimal_organisation_record, organisation_schema) 
Example 16
Project: reroils-data-legacy   Author: rero   File: test_organisations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pid(organisation_schema, minimal_organisation_record):
    """Test pid for organisation jsonschema."""
    validate(minimal_organisation_record, organisation_schema)

    with pytest.raises(ValidationError):
        minimal_organisation_record['pid'] = 25
        validate(minimal_organisation_record, organisation_schema) 
Example 17
Project: reroils-data-legacy   Author: rero   File: test_organisations_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_address(organisation_schema,
                 minimal_organisation_record):
    """Test address for organisation jsonschema."""
    validate(minimal_organisation_record, organisation_schema)

    with pytest.raises(ValidationError):
        minimal_organisation_record['address'] = 25
        validate(minimal_organisation_record, organisation_schema) 
Example 18
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(document_schema, minimal_document_record):
    """Test required for jsonschema."""
    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        validate({}, document_schema) 
Example 19
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pid(document_schema, minimal_document_record):
    """Test pid for jsonschema."""
    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['pid'] = 25
        validate(minimal_document_record, document_schema) 
Example 20
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_title(document_schema, minimal_document_record):
    """Test title for jsonschema."""
    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['title'] = 2
        validate(minimal_document_record, document_schema) 
Example 21
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_titlesProper(document_schema, minimal_document_record):
    """Test titlesProper for jsonschema."""
    minimal_document_record['titlesProper'] = ['RERO21 pour les nuls']

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['titlesProper'] = 'string is a bad type'
        validate(minimal_document_record, document_schema) 
Example 22
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_is_part_of(document_schema, minimal_document_record):
    """Test type for document jsonschema."""
    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['is_part_of'] = 2
        validate(minimal_document_record, document_schema) 
Example 23
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_languages(document_schema, minimal_document_record):
    """Test languages for jsonschema."""
    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['languages'][0]['language'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['languages'][0]['language'] = ['gre']
        validate(minimal_document_record, document_schema) 
Example 24
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_translatedFrom(document_schema, minimal_document_record):
    """Test translatedFrom for jsonschema."""
    minimal_document_record['translatedFrom'] = ['eng']

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['translatedFrom'] = [2]
        validate(minimal_document_record, document_schema) 
Example 25
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_authors(document_schema, minimal_document_record):
    """Test authors for jsonschema."""
    minimal_document_record['authors'] = [
        {
            'name': 'Dumont, Jean',
            'type': 'person',
            'date': '1954 -',
            'qualifier': 'Développeur'
        },
        {
            'type': 'organisation',
            'name': 'RERO'
        }
    ]

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][0]['name'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][0]['type'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][0]['date'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][0]['qualifier'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][1]['type'] = [2]
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['authors'][1]['name'] = [2]
        validate(minimal_document_record, document_schema) 
Example 26
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_freeFormedPublicationDate(document_schema, minimal_document_record):
    """Test freeFormedPublicationDate for jsonschema."""
    minimal_document_record['freeFormedPublicationDate'] = '2017'

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['freeFormedPublicationDate'] = [2]
        validate(minimal_document_record, document_schema) 
Example 27
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_extent(document_schema, minimal_document_record):
    """Test extent for jsonschema."""
    minimal_document_record['extent'] = '117'

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['extent'] = [2]
        validate(minimal_document_record, document_schema) 
Example 28
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_otherMaterialCharacteristics(
        document_schema, minimal_document_record):
    """Test otherMaterialCharacteristics for jsonschema."""
    minimal_document_record['otherMaterialCharacteristics'] = 'ill.'

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['otherMaterialCharacteristics'] = [2]
        validate(minimal_document_record, document_schema) 
Example 29
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_formats(document_schema, minimal_document_record):
    """Test formats for jsonschema."""
    minimal_document_record['formats'] = ['15 x 22 cm']

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['formats'] = 'string is a bad type'
        validate(minimal_document_record, document_schema) 
Example 30
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_additionalMaterials(document_schema, minimal_document_record):
    """Test additionalMaterials for jsonschema."""
    minimal_document_record['additionalMaterials'] = '1 CD-ROM'

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['additionalMaterials'] = 2
        validate(minimal_document_record, document_schema) 
Example 31
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_notes(document_schema, minimal_document_record):
    """Test notes for jsonschema."""
    minimal_document_record['notes'] = ["Photo de l'auteur sur le 4e de couv."]

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['notes'][0] = 2
        validate(minimal_document_record, document_schema) 
Example 32
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_abstracts(document_schema, minimal_document_record):
    """Test abstracts for jsonschema."""
    minimal_document_record['abstracts'] = ["This document is about..."]

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['abstracts'][0] = 2
        validate(minimal_document_record, document_schema) 
Example 33
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_identifiers(document_schema, minimal_document_record):
    """Test identifiers for jsonschema."""
    minimal_document_record['identifiers'] = {
        "reroID": "R004567655",
        "isbn": "9782082015769",
        "bnfID": "cb350330441"
    }

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['identifiers']['reroID'] = 2
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['identifiers']['isbn'] = 2
        validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['identifiers'] = {}
        validate(minimal_document_record, document_schema)

    minimal_document_record['identifiers'] = {
        "bnfID": "cb350330441"
    }

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['identifiers']['bnfID'] = 2
        validate(minimal_document_record, document_schema) 
Example 34
Project: reroils-data-legacy   Author: rero   File: test_documents_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_subjects(document_schema, minimal_document_record):
    """Test subjects for jsonschema."""
    minimal_document_record['subjects'] = [
        'ILS',
        'informatique',
        'bibliothèque'
    ]

    validate(minimal_document_record, document_schema)

    with pytest.raises(ValidationError):
        minimal_document_record['subjects'] = 2
        validate(minimal_document_record, document_schema) 
Example 35
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(patron_schema, minimal_patron_record):
    """Test required for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        validate({}, patron_schema)
        validate(minimal_patron_record, patron_schema) 
Example 36
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_first_name(patron_schema, minimal_patron_record):
    """Test first_name for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['first_name'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 37
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_last_name(patron_schema, minimal_patron_record):
    """Test last_name for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['last_name'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 38
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_street(patron_schema, minimal_patron_record):
    """Test street for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['street'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 39
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_postal_code(patron_schema, minimal_patron_record):
    """Test postal_code for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['postal_code'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 40
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_city(patron_schema, minimal_patron_record):
    """Test city for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['city'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 41
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_birth_date(patron_schema, minimal_patron_record):
    """Test birth date for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['birth_date'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 42
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_email(patron_schema, minimal_patron_record):
    """Test email for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['email'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 43
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_phone(patron_schema, minimal_patron_record):
    """Test phone for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['phone'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 44
Project: reroils-data-legacy   Author: rero   File: test_patrons_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_patron_type(patron_schema, minimal_patron_record):
    """Test patron_type for patron jsonschema."""
    validate(minimal_patron_record, patron_schema)

    with pytest.raises(ValidationError):
        minimal_patron_record['patron_type'] = 25
        validate(minimal_patron_record, patron_schema) 
Example 45
Project: reroils-data-legacy   Author: rero   File: test_members_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(member_schema, minimal_member_record):
    """Test required for member jsonschema."""
    validate(minimal_member_record, member_schema)

    with pytest.raises(ValidationError):
        validate({}, member_schema)
        validate(minimal_member_record, member_schema) 
Example 46
Project: reroils-data-legacy   Author: rero   File: test_members_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_name(member_schema, minimal_member_record):
    """Test name for member jsonschema."""
    validate(minimal_member_record, member_schema)

    with pytest.raises(ValidationError):
        minimal_member_record['name'] = 25
        validate(minimal_member_record, member_schema) 
Example 47
Project: reroils-data-legacy   Author: rero   File: test_members_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_address(member_schema,
                 minimal_member_record):
    """Test address for organisation jsonschema."""
    validate(minimal_member_record, member_schema)

    with pytest.raises(ValidationError):
        minimal_member_record['address'] = 25
        validate(minimal_member_record, member_schema) 
Example 48
Project: reroils-data-legacy   Author: rero   File: test_items_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_required(item_schema, minimal_item_record):
    """Test required for item jsonschema."""
    validate(minimal_item_record, item_schema)

    with pytest.raises(ValidationError):
        validate({}, item_schema) 
Example 49
Project: reroils-data-legacy   Author: rero   File: test_items_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pid(item_schema, minimal_item_record):
    """Test pid for item jsonschema."""
    validate(minimal_item_record, item_schema)

    with pytest.raises(ValidationError):
        minimal_item_record['pid'] = 25
        validate(minimal_item_record, item_schema) 
Example 50
Project: reroils-data-legacy   Author: rero   File: test_items_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_barcode(item_schema, minimal_item_record):
    """Test barcode for item jsonschema."""
    validate(minimal_item_record, item_schema)

    with pytest.raises(ValidationError):
        minimal_item_record['barcode'] = 2
        validate(minimal_item_record, item_schema) 
Example 51
Project: reroils-data-legacy   Author: rero   File: test_items_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_location(item_schema, minimal_item_record):
    """Test location for item jsonschema."""
    validate(minimal_item_record, item_schema)

    with pytest.raises(ValidationError):
        minimal_item_record['location'] = 25
        validate(minimal_item_record, item_schema) 
Example 52
Project: reroils-data-legacy   Author: rero   File: test_items_jsonschema.py    GNU General Public License v2.0 5 votes vote down vote up
def test_item_type(item_schema, minimal_item_record):
    """Test location for item jsonschema."""
    validate(minimal_item_record, item_schema)

    with pytest.raises(ValidationError):
        minimal_item_record['item_type'] = 25
        validate(minimal_item_record, item_schema) 
Example 53
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_legacy_v2_compatible_wrapper.py    Apache License 2.0 5 votes vote down vote up
def test_pattern_properties_with_invalid_property(self):
        validator = validators._SchemaValidator(
            self.schema_with_pattern).validator
        instance = {'foo': '1', 'b' * 300: 'extra'}
        gen = validators._soft_validate_additional_properties(
            validator, False, instance, self.schema_with_pattern)
        exc = next(gen)
        self.assertIsInstance(exc,
                              jsonschema_exc.ValidationError)
        self.assertIn('was', exc.message) 
Example 54
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_legacy_v2_compatible_wrapper.py    Apache License 2.0 5 votes vote down vote up
def test_pattern_properties_with_multiple_invalid_properties(self):
        validator = validators._SchemaValidator(
            self.schema_with_pattern).validator
        instance = {'foo': '1', 'b' * 300: 'extra', 'c' * 300: 'extra'}
        gen = validators._soft_validate_additional_properties(
            validator, False, instance, self.schema_with_pattern)
        exc = next(gen)
        self.assertIsInstance(exc,
                              jsonschema_exc.ValidationError)
        self.assertIn('were', exc.message) 
Example 55
Project: vod-converter   Author: umautobots   File: converter.py    MIT License 5 votes vote down vote up
def validate_image_detections(image_detections):
    for i, image_detection in enumerate(image_detections):
        try:
            validate_schema(image_detection, IMAGE_DETECTION_SCHEMA)
        except SchemaError as se:
            raise Exception(f"at index {i}") from se
        image = image_detection['image']
        for detection in image_detection['detections']:
            if detection['right'] >= image['width'] or detection['bottom'] >= image['height']:
                raise ValueError(f"Image {image} has out of bounds bounding box {detection}")
            if detection['right'] <= detection['left'] or detection['bottom'] <= detection['top']:
                raise ValueError(f"Image {image} has zero dimension bbox {detection}") 
Example 56
Project: cis   Author: mozilla-iam   File: exchange.py    Mozilla Public License 2.0 5 votes vote down vote up
def valid(self):
        """[Light validation prior to replicating to postgres in order to ensure no tampering.]

        Returns:
            [boolean] -- [Method returns status of pre-flight checks from the profile lib.]
        """
        self._load_cis_profile()
        try:
            self.cis_profile.validate()
            return True
        except ValidationError:
            return False 
Example 57
Project: signals   Author: Amsterdam   File: test_mixin.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_validate_schemas(self):
        """Check that our schemas are in fact JSONSchemas."""
        for interval_type, schema in SCHEMAS.items():
            try:
                Validator.check_schema(schema)
            except JSONValidationError:
                msg = f'JSON schema assoctiated with {interval_type} interval is incorrect.'
                self.fail(msg) 
Example 58
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def additionalProperties(validator, aP, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    extras = set(_utils.find_additional_properties(instance, schema))

    if validator.is_type(aP, "object"):
        for extra in extras:
            for error in validator.descend(instance[extra], aP, path=extra):
                yield error
    elif not aP and extras:
        error = "Additional properties are not allowed (%s %s unexpected)"
        yield ValidationError(error % _utils.extras_msg(extras)) 
Example 59
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def minimum(validator, minimum, instance, schema):
    if not validator.is_type(instance, "number"):
        return

    if schema.get("exclusiveMinimum", False):
        failed = instance <= minimum
        cmp = "less than or equal to"
    else:
        failed = instance < minimum
        cmp = "less than"

    if failed:
        yield ValidationError(
            "%r is %s the minimum of %r" % (instance, cmp, minimum)
        ) 
Example 60
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def maximum(validator, maximum, instance, schema):
    if not validator.is_type(instance, "number"):
        return

    if schema.get("exclusiveMaximum", False):
        failed = instance >= maximum
        cmp = "greater than or equal to"
    else:
        failed = instance > maximum
        cmp = "greater than"

    if failed:
        yield ValidationError(
            "%r is %s the maximum of %r" % (instance, cmp, maximum)
        ) 
Example 61
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def multipleOf(validator, dB, instance, schema):
    if not validator.is_type(instance, "number"):
        return

    if isinstance(dB, float):
        quotient = instance / dB
        failed = int(quotient) != quotient
    else:
        failed = instance % dB

    if failed:
        yield ValidationError("%r is not a multiple of %r" % (instance, dB)) 
Example 62
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def maxItems(validator, mI, instance, schema):
    if validator.is_type(instance, "array") and len(instance) > mI:
        yield ValidationError("%r is too long" % (instance,)) 
Example 63
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def uniqueItems(validator, uI, instance, schema):
    if (
        uI and
        validator.is_type(instance, "array") and
        not _utils.uniq(instance)
    ):
        yield ValidationError("%r has non-unique elements" % instance) 
Example 64
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pattern(validator, patrn, instance, schema):
    if (
        validator.is_type(instance, "string") and
        not re.search(patrn, instance)
    ):
        yield ValidationError("%r does not match %r" % (instance, patrn)) 
Example 65
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def format(validator, format, instance, schema):
    if validator.format_checker is not None:
        try:
            validator.format_checker.check(instance, format)
        except FormatError as error:
            yield ValidationError(error.message, cause=error.cause) 
Example 66
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def minLength(validator, mL, instance, schema):
    if validator.is_type(instance, "string") and len(instance) < mL:
        yield ValidationError("%r is too short" % (instance,)) 
Example 67
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def enum(validator, enums, instance, schema):
    if instance not in enums:
        yield ValidationError("%r is not one of %r" % (instance, enums)) 
Example 68
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def disallow_draft3(validator, disallow, instance, schema):
    for disallowed in _utils.ensure_list(disallow):
        if validator.is_valid(instance, {"type" : [disallowed]}):
            yield ValidationError(
                "%r is disallowed for %r" % (disallowed, instance)
            ) 
Example 69
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def required_draft4(validator, required, instance, schema):
    if not validator.is_type(instance, "object"):
        return
    for property in required:
        if property not in instance:
            yield ValidationError("%r is a required property" % property) 
Example 70
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def minProperties_draft4(validator, mP, instance, schema):
    if validator.is_type(instance, "object") and len(instance) < mP:
        yield ValidationError(
            "%r does not have enough properties" % (instance,)
        ) 
Example 71
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def maxProperties_draft4(validator, mP, instance, schema):
    if not validator.is_type(instance, "object"):
        return
    if validator.is_type(instance, "object") and len(instance) > mP:
        yield ValidationError("%r has too many properties" % (instance,)) 
Example 72
Project: misp42splunk   Author: remg427   File: _validators.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def anyOf_draft4(validator, anyOf, instance, schema):
    all_errors = []
    for index, subschema in enumerate(anyOf):
        errs = list(validator.descend(instance, subschema, schema_path=index))
        if not errs:
            break
        all_errors.extend(errs)
    else:
        yield ValidationError(
            "%r is not valid under any of the given schemas" % (instance,),
            context=all_errors,
        ) 
Example 73
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_short_paths_are_better_matches(self):
        shallow = exceptions.ValidationError("Oh no!", path=["baz"])
        deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])
        match = max([shallow, deep], key=exceptions.relevance)
        self.assertIs(match, shallow)

        match = max([deep, shallow], key=exceptions.relevance)
        self.assertIs(match, shallow) 
Example 74
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_global_errors_are_even_better_matches(self):
        shallow = exceptions.ValidationError("Oh no!", path=[])
        deep = exceptions.ValidationError("Oh yes!", path=["foo"])

        errors = sorted([shallow, deep], key=exceptions.relevance)
        self.assertEqual(
            [list(error.path) for error in errors],
            [["foo"], []],
        )

        errors = sorted([deep, shallow], key=exceptions.relevance)
        self.assertEqual(
            [list(error.path) for error in errors],
            [["foo"], []],
        ) 
Example 75
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_weak_validators_are_lower_priority(self):
        weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
        normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")

        best_match = exceptions.by_relevance(weak="a")

        match = max([weak, normal], key=best_match)
        self.assertIs(match, normal)

        match = max([normal, weak], key=best_match)
        self.assertIs(match, normal) 
Example 76
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_strong_validators_are_higher_priority(self):
        weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
        normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
        strong = exceptions.ValidationError("Oh fine!", path=[], validator="c")

        best_match = exceptions.by_relevance(weak="a", strong="c")

        match = max([weak, normal, strong], key=best_match)
        self.assertIs(match, strong)

        match = max([strong, normal, weak], key=best_match)
        self.assertIs(match, strong) 
Example 77
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_it_contains_an_item_if_the_item_had_an_error(self):
        errors = [exceptions.ValidationError("a message", path=["bar"])]
        tree = exceptions.ErrorTree(errors)
        self.assertIn("bar", tree) 
Example 78
Project: misp42splunk   Author: remg427   File: test_exceptions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_validators_that_failed_appear_in_errors_dict(self):
        error = exceptions.ValidationError("a message", validator="foo")
        tree = exceptions.ErrorTree([error])
        self.assertEqual(tree.errors, {"foo" : error}) 
Example 79
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: validators.py    Apache License 2.0 4 votes vote down vote up
def _soft_validate_additional_properties(validator,
                                         additional_properties_value,
                                         instance,
                                         schema):
    """This validator function is used for legacy v2 compatible mode in v2.1.
    This will skip all the additional properties checking but keep check the
    'patternProperties'. 'patternProperties' is used for metadata API.

    If there are not any properties on the instance that are not specified in
    the schema, this will return without any effect. If there are any such
    extra properties, they will be handled as follows:

    - if the validator passed to the method is not of type "object", this
      method will return without any effect.
    - if the 'additional_properties_value' parameter is True, this method will
      return without any effect.
    - if the schema has an additionalProperties value of True, the extra
      properties on the instance will not be touched.
    - if the schema has an additionalProperties value of False and there
      aren't patternProperties specified, the extra properties will be stripped
      from the instance.
    - if the schema has an additionalProperties value of False and there
      are patternProperties specified, the extra properties will not be
      touched and raise validation error if pattern doesn't match.
    """
    if (not validator.is_type(instance, "object") or
            additional_properties_value):
        return

    properties = schema.get("properties", {})
    patterns = "|".join(schema.get("patternProperties", {}))
    extra_properties = set()
    for prop in instance:
        if prop not in properties:
            if patterns:
                if not re.search(patterns, prop):
                    extra_properties.add(prop)
            else:
                extra_properties.add(prop)

    if not extra_properties:
        return

    if patterns:
        error = "Additional properties are not allowed (%s %s unexpected)"
        if len(extra_properties) == 1:
            verb = "was"
        else:
            verb = "were"
        yield jsonschema_exc.ValidationError(
            error % (", ".join(repr(extra) for extra in extra_properties),
                     verb))
    else:
        for prop in extra_properties:
            del instance[prop] 
Example 80
Project: signals   Author: Amsterdam   File: 0066_fix_datamodel_extra_properties.py    Mozilla Public License 2.0 4 votes vote down vote up
def migrate_data(apps, schema_editor):
    """
    Migrate the extra properties where lantarn numbers are in incorrect data format.
    """
    Signal = apps.get_model('signals', 'Signal')
    schema_validator = Draft7Validator(schema=SCHEMA_BAD_ENTRIES)

    straatverlichting = (
        Signal.objects.filter(
            category_assignment__category__slug='lantaarnpaal-straatverlichting'
        ).filter(
            extra_properties__isnull=False
        )
    )

    for signal in straatverlichting:
        mutated_properties = []  # will contain mutated copy of extra_properties
        selected_lights = []

        for qa_entry in signal.extra_properties:
            try:
                schema_validator.validate(qa_entry)
            except ValidationError:
                mutated_properties.append(qa_entry)
                continue

            if (qa_entry['category_url'] == STRAATVERLICHTING_URL and
                    qa_entry['id'] == RELEVANT_QUESTION_ID):
                for selected_light in qa_entry['answer']:
                    selected_lights.append(selected_light['label'])
            else:
                mutated_properties.append(qa_entry)
        else:
            if selected_lights:
                new_qa_entry = {
                    'id': RELEVANT_QUESTION_ID,
                    'category_url': STRAATVERLICHTING_URL,
                    'label': RELEVANT_QUESTION_LABEL,
                    'answer': selected_lights,
                }
                mutated_properties.append(new_qa_entry)

        signal.extra_properties = mutated_properties
        signal.save()