예제 #1
0
def check_syntax(config, double_validate=True):
    """
    check the given configuration against the schema definition
    :param config:
    :param double_validate: validate invalid syntax a second time with raising exception
    :return: True if the syntax is valid, False otherwise
    """
    try:
        with open(ROOT_SCHEMA, 'r') as f:
            schema = json.load(f)
    except FileNotFoundError as fnfe:
        factory_logger.error(
            'JSON root schema could not be found: {}'.format(ROOT_SCHEMA_NAME))
        factory_logger.error(fnfe)
        sys.exit()
    except Exception as e:
        factory_logger.error(e)
        sys.exit()

    # resolver: reference sub-schemas from relative URIs
    # -> https://github.com/Julian/jsonschema/issues/313
    resolver = RefResolver(base_uri=ROOT_SCHEMA_BASE_URI, referrer=schema)
    validator = Validator(schema, resolver=resolver)
    is_valid = validator.is_valid(config)

    if not is_valid and double_validate:
        # if configuration is invalid, run validate to get error message
        try:
            validator.validate(config)
        except jsonschema.exceptions.ValidationError as err:
            factory_logger.error(err)

    return is_valid
예제 #2
0
    def load(self, filename: str, use=None, encoding="utf-8"):
        path = Path(filename)

        if use is not None:
            load = use
        else:
            if path.suffix[1:] not in self.formats:
                print(path.suffix[1:])
                raise ValueError(
                    "Don't know how to load this file extension: {!r}".format(
                        path.suffix))
            else:
                load = self.formats[path.suffix[1:]]

        with path.open(encoding=encoding) as fp:
            instance = load(fp)

        resolver = RefResolver(
            self.id,
            self.definition,
            {sch.id: sch.definition
             for sch in self.directory.schemas()},
        )
        validator = Validator(self.definition, resolver=resolver)
        validator.validate(instance)

        return instance
예제 #3
0
def _validate(validator: jsonschema.Draft7Validator,
              entity: Mapping[str, Any]) -> bool:
    """
    Determine whether a given entity is valid based on its JSON schema.

    :param input: A dict representing a PyBEL entity.
    :return: if the input is valid
    """
    try:
        validator.validate(entity)
        return True
    except jsonschema.exceptions.ValidationError as err:
        logger.info(err)
        return False
예제 #4
0
def run_test(val: Draft7Validator, test: TestSchema):
    logger.info(test.description)
    print()
    expected = test.valid

    try:
        val.validate(test.data)
        if expected is False:
            logger.error("Test passed when it shouldn't")
        else:
            logger.success("Test succeeded")
    except Exception as e:
        if expected is True:
            logger.error("Test didn't pass when it should")
            logger.exception(e)
        else:
            logger.success("Test succeeded")
예제 #5
0
def test_tuple(validator: Draft7Validator):
    validator.validate({'type': 'tuple', 'element_types': [{'type': 'float'}]})
예제 #6
0
def test_files(validator: Draft7Validator):
    # Valid Schemas
    validator.validate({'type': 'file'})
    validator.validate({'type': 'file', 'file_types': ['text/csv']})
    validator.validate({'type': 'list', 'item_type': {'type': 'file'}})
    validator.validate({
        'type': 'list',
        'item_type': {
            'type': 'file',
            'file_types': ['test/csv']
        }
    })
    validator.validate({
        'type':
        'tuple',
        'element_types': [{
            'type': 'file',
            'file_types': ['test/csv']
        }, {
            'type': 'list',
            'item_type': {
                'type': 'file'
            }
        }]
    })

    # Invalid schema: List of list of files
    with pytest.raises(ValidationError):
        validator.validate({
            'type': 'list',
            'item_type': {
                'type': 'list',
                'item_type': {
                    'type': 'file'
                }
            }
        })

    # Invalid schema: Non-list collection of files
    with pytest.raises(ValidationError):
        validator.validate({
            'type': 'dict',
            'properties': {
                "a": {
                    'type': 'files'
                }
            }
        })