def test_3_json_schema(self): _schema = generate_schema() f_out = open(os.path.join(Test_Resource_Dir, "../../../", "schema/resources.json"), "w") json.dump(obj=_schema, fp=f_out, sort_keys=True, indent=4) f_out.close() Draft4Validator.check_schema(_schema)
def __new__(mcs, cls_name, superclasses, attributes): """ Return a new class by the given name with the given attributes and subclasses. This will validate the body and params schemas declared on a resource and raise a ValidationError if the schema is invalid. Args: mcs (type): the metaclass cls_name (str): the name of the new class superclasses (list[type]): list of the classes superclasses attributes (dict): a mapping from attribute name to attribute value on the new class """ if hasattr(attributes, '__body__'): # Check that the body schema is valid try: Draft4Validator.check_schema(attributes['__body__']) except jsonschema.ValidationError: raise jsonschema.ValidationError( f'Invalid body schema declared for resource {cls_name}') if hasattr(attributes, '__params__'): # Check that the params schema is valid try: Draft4Validator.check_schema(attributes['__params__']) except jsonschema.ValidationError: raise jsonschema.ValidationError( f'Invalid params schema declared for resource {cls_name}') # Create the class return super(ResourceMeta, mcs).__new__(mcs, cls_name, superclasses, attributes)
def __init__(self, json_data, strict=False, live_schema=None): self.live_schema = live_schema if not hasattr(json_data, '__getitem__'): raise TypeError('json_data must be a dict.') if (not self.schema) and (live_schema is None): raise NotImplementedError('schema not implemented!') if live_schema is not None: if not self.schema: self.schema = live_schema else: self.schema['properties'].update(live_schema['properties']) if "required" in self.schema and "required" in live_schema: self.schema['required'] = list( set(self.schema['required']) | set(live_schema["required"]) ) Draft4Validator.check_schema(self.schema) self.data = {} if not strict: self._filter_data(json_data, self.schema['properties'], self.data) else: self.data = json_data self.validator = Draft4Validator(self.schema) self.errors = None
def validate_schema_file(schema_file): """ Validate a JSON schema given the schema file. :param schema_file: the string the the schema file location :return: True """ Draft4Validator.check_schema(schema_file) return True
def test_json_schema(self): """This test will actually generate the schema for all classes in the transformation module""" _schema = generate_schema() f_out = open(os.path.join(Test_Resource_Dir, "../../../", "schema/transformation.json"), "w") json.dump(obj=_schema, fp=f_out, sort_keys=True, indent=4) f_out.close() Draft4Validator.check_schema(_schema)
def response(schema, description=""): schema = { "$schema": "http://json-schema.org/schema#", "type": "object", "properties": schema } Draft4Validator.check_schema(schema) return {"description": description, "schema": schema}
def validate_output(self): """ Validates the output of the merge :return: """ for schema in self.output['schemas']: try: Draft4Validator.check_schema(self.output['schemas'][schema]) except Exception as e: if schema not in self.errors: self.errors[schema] = [] self.errors[schema].append(str(e))
def body_parameter(schema, description=""): schema = { "$schema": "http://json-schema.org/schema#", "type": "object", "properties": schema } Draft4Validator.check_schema(schema) return { "name": "body", "in": "body", "required": True, "description": description, "schema": schema }
def __init__(self, json_data, live_schema=None): if not hasattr(json_data, '__getitem__'): raise TypeError('json_data must be a dict.') if not self.schema: raise NotImplementedError('schema not implemented!') if live_schema is not None: self.live_schema = live_schema self.schema['properties'].update(live_schema['properties']) if "required" in self.schema and "required" in live_schema: self.schema['required'] = list(set(self.schema['required']) | set(live_schema["required"])) Draft4Validator.check_schema(self.schema) self.data = {} self._filter_data(json_data, self.schema['properties'], self.data) self.validator = Draft4Validator(self.schema) self.errors = None
def validate_schema(self, user_input): """ Validate a schema against its draft using Draft4Validator :param user_input: a schema URL :type user_input: basestring :return: a string that give information on whether the schema is valid or not (should return a boolean or a dict containing both variables) """ try: validation = Draft4Validator.check_schema( json.loads(requests.get(user_input).text)) if validation is not None: return json.dumps(validation, indent=4) else: return json.dumps("You schema is valid") except Exception: return json.dumps("Problem loading the schema " + user_input)
def validate_network(self, user_input): """ Resolves a network and validates all of its schemas using Draft4Validator :param user_input: a schema URL :type user_input: basestring :return: a dictionary of all schemas with a string that give information on whether the schema is valid or not """ validation = {} schema_url = user_input resolved_network = fast_resolver(schema_url) for schema in resolved_network.keys(): local_validation = Draft4Validator.check_schema( resolved_network[schema]) if local_validation is not None: validation[schema] = local_validation else: validation[schema] = "This schema is valid" return json.dumps(validation, indent=4)
def generate_models(self, files, generate_schema: bool = False, cmake: bool = False): loader = JmgLoader() for file_path in (f for fileGlob in files for f in glob.glob(fileGlob)): if generate_schema: # # Generate the a JSON Schema file from the given JSON file # schema = genson.Schema() with open(file_path) as f: json_sample = json.load(f) schema.add_object(json_sample) schema_base_name = os.path.basename(file_path) schema_root_name, schema_ext = os.path.splitext(schema_base_name) schema_file_path = os.path.join(self.outdir, schema_root_name + '.schema' + schema_ext) with open(schema_file_path, 'w') as s_f: s_f.write(schema.to_json()) else: schema_file_path = file_path if self.root_name: scope = [self.root_name] else: base_name = os.path.basename(schema_file_path) base_uri = os.path.splitext(base_name)[0] base_uri = base_uri.replace('.schema', '') scope = [base_uri] with open(schema_file_path) as jsonFile: # root_schema = json.load(jsonFile) # base_uri = 'file://' + os.path.split(os.path.realpath(f))[0] base_uri = 'file://' + os.path.realpath(schema_file_path) root_schema = jsonref.load(jsonFile, base_uri=base_uri, jsonschema=True, loader=loader) if self.validate: # TODO: Add exception handling try: Draft4Validator.check_schema(root_schema) except SchemaError as e: print(e) assert isinstance(root_schema, dict) if JsonSchema2Model.SCHEMA_URI not in root_schema: root_schema[JsonSchema2Model.SCHEMA_URI] = schema_file_path self.create_model(root_schema, scope) if not cmake: self.render_models() self.copy_static_files() if self.include_dependencies: self.copy_dependencies() else: self.print_for_cmake()
def test_settings_schema_is_valid_schema(settings_schema): with settings_schema.open("r") as handle: s = json.load(handle) Draft4Validator.check_schema(s)
def validate_schema(schema): Draft4Validator.check_schema(schema)
def __init__(self): Draft4Validator.check_schema(self.request) self.request_validator = Draft4Validator(self.request) Draft4Validator.check_schema(self.response) self.response_validator = Draft4Validator(self.response)