def test_validation_error_message(self): with self.assertRaises(ValidationError) as e: validators.validate(12, {"type": "string"}) self.assertRegexpMatches( str(e.exception), "(?s)Failed validating u?'.*' in schema.*On instance", )
def post(self, *args, **kwargs): body_json = json.loads(self.request.body) try: validate(body_json, user_register_schema) username = body_json.get('username') random_key = cache.get('{}_registerkey'.format(username)) if random_key is None: return json_response(error='Invalid user register') password = decrypt(body_json.get('password'), random_key) salt = bcrypt.gensalt() email = body_json.get('email') if not validate_email(email): return json_response(error='Invalid email') fullname = body_json.get('fullname') if not validate_fullname(fullname): return json_response(error='Invalid fullname') user = insert_user({ 'username': username, 'email': email, 'fullname': fullname, 'salt': salt, 'salted_password': hasher(password, salt) }) if user is None: return json_response(error='Register user unsuccessful') return json_response(data={'msg': 'User registered'}) except ValidationError as exception: return json_response(error=exception.message)
def test_draft4_validator_is_the_default(self): with mock.patch.object( validators.Draft4Validator, "check_schema", ) as chk_schema: validators.validate({}, {}) chk_schema.assert_called_once_with({})
def test_schema_error_message(self): with self.assertRaises(SchemaError) as e: validators.validate(12, {"type": 12}) self.assertRegexpMatches( str(e.exception), "(?s)Failed validating u?'.*' in metaschema.*On schema", )
def test_draft6_validator_is_the_default(self): with mock.patch.object( validators.Draft6Validator, "check_schema", ) as chk_schema: validators.validate({}, {}) chk_schema.assert_called_once_with({})
def test_should_get_captcha_src( self, mock_captcha, mock_thread, mock_quit): expected_json_schema = { 'type': 'object', 'properties': { 'captcha_src': { 'type': 'string', 'pattern': '^data:image/png;base64,.+' } }, 'required': ['captcha_src'], 'additionalProperties': False } mock_captcha.return_value = 'data:image/png;base64,asdkjdlasdsd=' # There is no need to really start the threaded web driver mock_thread.return_value = None mock_quit.return_value = None nfe_key = '1' * 44 request = self._make_authenticated_request_object( '18273319832', nfe_key) response = views._get_nfe(request, nfe_key) try: validate(response.data, expected_json_schema) except ValidationError as e: self.fail(e.message)
def check_schema(schema): """ Check a given schema to make sure it is valid YAML schema. """ validators.validate(schema, load_schema( 'http://stsci.edu/schemas/yaml-schema/draft-01', mresolver.default_url_mapping))
def decorated(*args, **kwargs): try: validate(request.json, schema) except ValidationError as e: return {'error': e.message}, 400 return f(*args, **kwargs)
def post(self, *args, **kwargs): body_json = json.loads(self.request.body) try: validate(body_json, user_login_schema) username = body_json.get('username') encrypted_password = body_json.get('password') user_key = cache.get('{}_key'.format(username)) if user_key is None: log.info(user_key) return json_response(error='Invalid login operator') cache.delete('{}_key'.format(username)) password = decrypt(encrypted_password, user_key) user, is_valid = validate_user(username, password) if not is_valid: return json_response( error='Username does not exist or wrong password') token = string_generator(TOKEN_LENGTH) cache.set(token, { 'id': user['id'], 'role': get_user_role(user['id']), 'username': user['username'] }, time=SESSION_TIMEOUT) return json_response(data={'token': token, 'user_id': user['id']}) except ValidationError: return json_response(error='Input validation error')
def validate(self, packaging=False): if self.afu_json == {}: return False try: validators.validate(self.afu_json, afu_schema) except exceptions.ValidationError as ve: print("JSON schema error at {0}: {1}".format( str(list(ve.path)), str(ve.message))) return False # If emitting a GBS file do some extra validation beyond the schema. if packaging: # User clocks can be "auto" in the source JSON in order to # set the frequency to the actual achieved speed. When # creating the GBS, the frequencies must be numbers. for clock in ['clock-frequency-high', 'clock-frequency-low']: if clock in self.afu_json['afu-image']: f = self.afu_json['afu-image'][clock] if not isinstance(f, (int, float)): print("JSON schema error at {0}: {1}").format( "afu-image/" + clock, "expected number") raise Exception("Accelerator description file " + "failed validation!") return True
def test_draft4_validator_is_chosen(self): schema = {"$schema": "http://json-schema.org/draft-04/schema#"} with mock.patch.object( validators.Draft4Validator, "check_schema", ) as chk_schema: validators.validate({}, schema) chk_schema.assert_called_once_with(schema)
def test_tuple_is_array(self): schema = {"type": "array", "items": {"type": "number"}, "minItems": 1, "maxItems": 3, "uniqueItems": True} validate((1, 2, 3), schema, Validator) self.assertRaises(ValidationError, validate, tuple(), schema, Validator) self.assertRaises(ValidationError, validate, (1, 2, 3, 4), schema, Validator) # Temporary solution to use list instead of tuple, cause tuples cause # errors in unique items validator self.assertRaises(ValidationError, validate, [1, 1], schema, Validator)
def is_correct_json(in_json): if is_json(in_json): try: validate(json_object, schema) return json_object except jsonschema.exceptions.ValidationError as ve: raise Exception(ve.message) raise Exception("Incorrect format of Json")
def test_draft6_validator_is_chosen(self): schema = {"$schema": "http://json-schema.org/draft-06/schema#"} with mock.patch.object( validators.Draft6Validator, "check_schema", ) as chk_schema: validators.validate({}, schema) chk_schema.assert_called_once_with(schema)
def _valid_har(self, resp): resp.raise_for_status() json = resp.json() validate( json, { "$ref": "https://raw.githubusercontent.com/undera/har-jsonschema/master/har-schema.json" }) return json
def methodExecutor(*args, **kwargs): itemData = kwargs.get('itemData') if itemData is None: itemData = args[argIndex] try: validate(itemData, itemSchema) except ValidationError, err: raise ApiErrorException().jsonValidationFailed(err)
def test_draft3_validator_is_chosen(self): schema = {"$schema": "http://json-schema.org/draft-03/schema#"} with mock.patch.object(Draft3Validator, "check_schema") as chk_schema: validate({}, schema) chk_schema.assert_called_once_with(schema) # Make sure it works without the empty fragment schema = {"$schema": "http://json-schema.org/draft-03/schema"} with mock.patch.object(Draft3Validator, "check_schema") as chk_schema: validate({}, schema) chk_schema.assert_called_once_with(schema)
def test_draft3_validator_is_chosen(self): schema = {"$schema" : "http://json-schema.org/draft-03/schema#"} with mock.patch.object(Draft3Validator, "check_schema") as chk_schema: validate({}, schema) chk_schema.assert_called_once_with(schema) # Make sure it works without the empty fragment schema = {"$schema" : "http://json-schema.org/draft-03/schema"} with mock.patch.object(Draft3Validator, "check_schema") as chk_schema: validate({}, schema) chk_schema.assert_called_once_with(schema)
def post(self, *args, **kwargs): body_json = json.loads(self.request.body) try: validate(body_json, user_logout_schema) if validate_token_func(body_json["token"], body_json["user_id"]): cache.delete(body_json["token"]) return json_response(data={'msg': 'logged out'}) return json_response(error='Bad request') except ValidationError: return json_response(error='Bad request')
def patch(self, *args, **kwargs): event_id = int(self.kwargs.get('event_id')) body_json = json.loads(self.request.body) try: validate(body_json, event_patch_schema) event = update_event(event_id, body_json) if event is None: return json_response(error='update failed') return json_response(event) except ValidationError: return json_response(error='Invalid input')
def test_invalid_schema_multiple_errors_pretty_output(self): schema = {"type": 12, "items": 57} with self.assertRaises(SchemaError) as e: validate(schema=schema, instance="") error = str(e.exception) self.assertOutputs( files=dict(some_schema=json.dumps(schema)), argv=["--output", "pretty", "some_schema"], exit_code=1, stderr=("===[SchemaError]===(some_schema)===\n\n" + str(error) + "\n-----------------------------\n"), )
def jsonschema_validate_data(instance, schema, *, return_with_default: bool = False): assert "$schema" not in schema, "assumes always latest json-schema" # nosec if return_with_default: out = deepcopy(instance) _EXTENDED_VALIDATOR(schema).validate(out) else: out = instance validators.validate(out, schema, cls=None) return out
def _ValidateYaml(parsed_yaml, schema_path): """Validate yaml against schema. Args: parsed_yaml: yaml to validate schema_path: Path to schema, relative to schemas directory. Raises: ValidationError: if the template doesn't obey the schema. SchemaError: if the schema is invalid. """ schema = yaml.load( pkg_resources.GetResourceFromFile(os.path.join(SCHEMA_DIR, schema_path))) validators.validate(parsed_yaml, schema)
def test_custom_error_format_applies_to_schema_errors(self): instance, schema = 13, {"type": 12, "minimum": 30} with self.assertRaises(SchemaError): validate(schema=schema, instance=instance) self.assertOutputs( files=dict(some_schema=json.dumps(schema)), argv=[ "--error-format", ":{error.message}._-_.{error.instance}:", "some_schema", ], exit_code=1, stderr=":12 is not valid under any of the given schemas._-_.12:", )
def validate_settings(): status_msg = "SublimeLinter - Settings invalid. Details in console." schema_file = "resources/settings-schema.json" schema = util.load_json(schema_file, from_sl_dir=True) good = True for name, settings in get_settings_objects(): try: validate(settings, schema) except ValidationError as ve: ve_msg = ve.message.split("\n")[0] # reduce verbosity util.printf("Settings in '{}' invalid:\n{}".format(name, ve_msg)) sublime.active_window().status_message(status_msg) good = False return good
def test_invalid_schema_with_invalid_instance_pretty_output(self): instance, schema = 13, {"type": 12, "minimum": 30} with self.assertRaises(SchemaError) as e: validate(schema=schema, instance=instance) error = str(e.exception) self.assertOutputs( files=dict( some_schema=json.dumps(schema), some_instance=json.dumps(instance), ), argv=["--output", "pretty", "-i", "some_instance", "some_schema"], exit_code=1, stderr=("===[SchemaError]===(some_schema)===\n\n" + str(error) + "\n-----------------------------\n"), )
def post(self, *args, **kwargs): body_json = json.loads(self.request.body) try: validate(body_json, event_schema) current_timestamp = int(time.time()) body_json["create_time"] = current_timestamp body_json["update_time"] = current_timestamp event = insert_event(body_json) if event is None: return json_response(error='missing data field or wrong data type') for channel in body_json["channels"]: insert_event_channel(event_id=event.id, channel_id=channel['id']) return json_response(data=event) except ValidationError: return json_response(error='missing data field or wrong data type')
def test_tuple_is_array(self): schema = { 'type': 'array', 'items': { 'type': 'number' }, 'minItems': 1, 'maxItems': 3, 'uniqueItems': True, } validate((1, 2, 3), schema, Validator) self.assertRaises(ValidationError, validate, tuple(), schema, Validator) self.assertRaises(ValidationError, validate, (1, 2, 3, 4), schema, Validator) # Temporary solution to use list instead of tuple, cause tuples cause # errors in unique items validator self.assertRaises(ValidationError, validate, [1, 1], schema, Validator)
def validate_settings(): status_msg = "SublimeLinter - Settings invalid!" schema_file = "resources/settings-schema.json" schema = util.load_json(schema_file, from_sl_dir=True) window = sublime.active_window() util.clear_message() good = True for name, settings in get_settings_objects(): try: validate(settings, schema) except ValidationError as error: good = False error_msg = error.message.split("\n")[0] # reduce verbosity full_msg = "Invalid settings in '{}':\n{}".format(name, error_msg) logger.error(full_msg) window.status_message(status_msg) return good
def enum(validator, enums, instance, schema): ok = False error = None if instance in enums: ok = True else: error = ValidationError("%r is not one of %r" % (instance, enums)) if not ok: from jsonschema.validators import validate for e in enums: if isinstance(e, dict): try: validate(instance, e) ok = True break except Exception as ex: error = ex if not ok: yield error
def run(self, test): out = self.fetchOutput(test) print(colored("Testing:", 'white', 'on_cyan') + " " + colored(test.nmea, 'cyan'), end='') try: out = json.loads(out) if self.verbose: print( colored( json.dumps(out, sort_keys=True, indent=4, separators=(',', ': ')), 'blue')) try: validate(out, self.schema) except jsonschema.exceptions.RefResolutionError as e: if self.verbose: print( colored( "Schema reference resolution error (are you connected?) - continuing...", 'yellow')) test.validateOutput(out) print(" " + colored("PASS", 'white', 'on_green')) return True except ValueError as e: print(" " + colored("FAIL", 'white', 'on_red')) print(colored(out, 'magenta')) print(colored("Error parsing JSON: {}.".format(e), 'red')) return False except jsonschema.exceptions.ValidationError as e: print(" " + colored("FAIL", 'white', 'on_red')) print(colored(out, 'magenta')) print( colored("Error: JSON does not validate signalk specification", 'red')) print(colored(e.message, 'red')) return False
def validate(cls, schema: str, json_) -> dict: if isinstance(json_, str): json_ = json.loads(json_) elif not isinstance(json_, dict): raise ValueError() try: validators.validate(json_, schema) except exceptions.ValidationError as e: errors = [{ "message": error.message for error in e.validator.iter_errors(json_) }] result = {"valid": False, "errors": errors} except exceptions.SchemaError as e: # TODO investigate what this error looks like and improve errors errors = [{"message": f'Invalid schema: {str(e.cause)}'}] result = {"valid": False, "errors": errors} else: result = {"valid": True} return result
def test_empty_object(self): validate({}, EMPTY_OBJECT) self.assertRaises(ValidationError, validate, {'key': 'value'}, EMPTY_OBJECT)
def test_non_existent_properties_are_ignored(self): instance, my_property, my_value = mock.Mock(), mock.Mock(), mock.Mock() validate(instance=instance, schema={my_property: my_value})
def message_for(self, instance, schema, *args, **kwargs): kwargs.setdefault("cls", Draft3Validator) with self.assertRaises(ValidationError) as e: validate(instance, schema, *args, **kwargs) return e.exception.message
def results_validator(results): validate(instance=results, schema=ResultsSchemas.results_schema)
def test_non_existent_properties_are_ignored(self): instance, my_property, my_value = mock.Mock(), mock.Mock(), mock.Mock() validate(instance=instance, schema={my_property : my_value})
def scenario_validator(scenario_repr): validate(instance=scenario_repr, schema=ScenarioSchemas.scenario_schema)
def test_empty_array(self): validate([], EMPTY_ARRAY) self.assertRaises(ValidationError, validate, [1], EMPTY_ARRAY)
def test_empty_object(self): validate({}, EMPTY_OBJECT) self.assertRaises(ValidationError, validate, {"key": "value"}, EMPTY_OBJECT)