def update_goal_by_id(goal_id): schema = Kanpai.Object({'status': Kanpai.String().required()}) validation_result = schema.validate(request.json) if validation_result.get('success', False) is False: abort(400) if request.json['status'] is not None: status_mapping = dict((item.value, item) for item in GoalStatus) if request.json['status'] not in status_mapping: abort(400) goal = GoalRequest(job_id=None, position_x=None, position_y=None, position_z=None, orientation_x=None, orientation_y=None, orientation_z=None, orientation_w=None, status=request.json['status']) try: goal_service.update_goal(goal_id, goal) return jsonify(message='success') except ValueError as e: abort(400) except Exception as e: print(e) abort(500)
def get_author(author_id): try: schema = Kanpai.Object({ 'author_id': Kanpai.Number(error="'author_id' must be a number").required( error="'author_id' is required") }) validation = schema.validate({"author_id": author_id}) if validation.get('error') != None: error = list(validation.get('error').values())[0] raise ValidationError(error) return authorService.get_author(author_id) except ValidationError as err: print_error(err) return set_response(status='BAD_REQUEST', success=False, error=str(err)) except Exception as err: print_error(err) return set_response(status='SERVER_ERROR', success=False, error='An error occurred')
def test_error_when_data_is_not_dict_type(): schema = Kanpai.Object({ 'name': Kanpai.String() }) result = schema.validate(['its not a dict']) assert result.get('success') is False assert result.get('error').get('data') is not None
def post(self, *args, **kwargs): data = request.get_json() username = data.get("username", "") roledesc = data.get("roledesc", "") status = data.get("status", "") schema = Kanpai.Object({ "username": (Kanpai.String(error="user name should be string").trim().required( error="user name should required").max( 32, error="should not be more than 32 characters")), "roledesc": (Kanpai.String(error="role desc should be string").trim().required( error="role desc should required").max( 32, error="should not be more than 32 characters")), "status": (Kanpai.String(error="role desc should be string").trim().required( error="role desc should required").max( 32, error="should not be more than 32 characters")) }) validation_results = schema.validate(data) Validations.validate_error(obj=validation_results) check_username_indb = session.query(UserDB).filter_by( username=username).first() check_roledesc_indb = session.query(RoleDB).filter_by( roledesc=roledesc).first() if not check_username_indb: return jsonify({ "status": "error", "errors": f"user {check_username_indb} not present in db" }) if not check_roledesc_indb: return jsonify({ "status": "error", "errors": f"role description {check_roledesc_indb} not present in db" }) if data: userrole = UserRoleDB(userid=check_username_indb.id, roleid=check_roledesc_indb.id, status=status) db.add(userrole) db.commit() return jsonify({ "status": "success", "data": validation_results["data"] })
def post(self) -> Response: schema = Kanpai.Object({ 'medicineID': Kanpai.String().required(), 'name': Kanpai.String().required(), 'amount': Kanpai.String().required(), 'lot_num': Kanpai.String().required(), 'MFG': Kanpai.String().required(), 'EXP': Kanpai.String().required(), 'price': Kanpai.String().required(), 'create_at': Kanpai.String().required(), 'update_at': Kanpai.String().required() }) body = request.get_json() today = date.today() key = uuid.uuid4().int data = { 'medicineID': str(key)[0:6], 'name': body['name'], 'amount': body['amount'], 'lot_num': body['lot_num'], 'MFG': body['MFG'], 'EXP': body['EXP'], 'price': body['price'], 'create_at': str(datetime.utcnow()), 'update_at': str(datetime.utcnow()) } validate_result = schema.validate(data) if validate_result.get('success', False) is False: print(data) response = jsonify({ "data": data, "message": "Error", "status": 400 }) response.status_code = 400 return response try: Medicine(**data).save() response = jsonify({ "data": data, "message": "success", "status": 201 }) response.status_code = 201 return response except NotUniqueError: response = jsonify({ "data": None, "message": "Already have Medicine ID", "status": 400 }) response.status_code = 400 return response
def post(self, *args, **kwargs): data = request.get_json() bankname = data.get("bankname", '') universalbranchcode = data.get("universalbranchcode", "") schema = Kanpai.Object({ "bankname": (Kanpai.String().required().max(32)), "universalbranchcode": (Kanpai.String().required()) }) validation_results = schema.validate(data) Validations.validate_error(validation_results) if data: bankcode = BankCodeDB(bankname=bankname, universalbranchcode=universalbranchcode) db.add(bankcode) db.commit() return jsonify({ "status": "success", "data": validation_results["data"] })
def create_author(payload): try: schema = Kanpai.Object({ 'first_name': Kanpai.String( error="'first_name' must be a string").trim().required( error="'first_name' is required"), 'last_name': Kanpai.String( error="'last_name' must be a string").trim().required( error="'last_name' is required") }) validation = schema.validate(payload) if validation.get('error') != None: error = list(validation.get('error').values())[0] raise ValidationError(error) return authorService.create_author(payload) except ValidationError as err: print_error(err) return set_response(status='BAD_REQUEST', success=False, error=str(err)) except Exception as err: print_error(err) return set_response(status='SERVER_ERROR', success=False, error='An error occurred')
def post(self, *args, **kwargs): schema = Kanpai.Object({ 'name': (Kanpai.String( error="Description should be string").trim().required( error="Description should required").max( 64, error="Should not be more than 64 characters")), 'idnumber': (Kanpai.String( error="Description should be string").trim().required( error="Description should required").max( 64, error="Should not be more than 64 characters")) }) data = request.get_json() validation_result = schema.validate(data) if validation_result.get('success', False) is False: return jsonify({ "status": "error", "errors": validation_result.get('error') }) if data: idtype = IdTypeDB(name=data['name'], idnumber=data['idnumber']) db.add(idtype) db.commit() return jsonify({ "status": "success", "result": validation_result['data'] })
def test_success_if_value_is_present_when_required(): schema = Kanpai.Object({ 'name': Kanpai.String() }).required() result = schema.validate({'name': 'kanpai'}) assert result.get('success') is True
def test_error_if_value_is_none_when_required(): schema = Kanpai.Object({ 'name': Kanpai.String() }).required() result = schema.validate(None) assert result.get('success') is False
def test_success_when_element_validation_on_none_data(): schema = Kanpai.Array().of( Kanpai.Object({ 'name': Kanpai.String().trim().required(), 'age': Kanpai.Number().integer() })) result = schema.validate(None) assert result.get('success') is True
def test_no_exception_with_equal_validator_when_data_is_none(): schema = Kanpai.Object({ 'name': Kanpai.String().required(), 'password': Kanpai.String().trim().required(), 'confirm_password': Kanpai.String().trim().required() }).assert_equal_field('password', 'confirm_password') result = schema.validate(None) assert result.get('success') is True assert result.get('error') is None
def test_error_when_required_inner_object_none(): SCHEMA = Kanpai.Object({ 'phone': Kanpai.Object({ 'country_code': Kanpai.String().trim().required().max(3), 'phone_number': Kanpai.String().trim().required().max(10) }).required("Please provide phone number.") }) result = SCHEMA.validate({ }) assert result.get('success') is False assert result.get('error').get('phone') is not None assert result.get('error').get('phone') == 'Please provide phone number.'
def test_success_when_optional_inner_object_none(): SCHEMA = Kanpai.Object({ 'name': Kanpai.String().required(), 'phone': Kanpai.Object({ 'country_code': Kanpai.String().trim().required().max(3), 'phone_number': Kanpai.String().trim().required().max(10) }) }) result = SCHEMA.validate({ 'name': 'Kanpai' }) assert result.get('success') is True assert result.get('error') is None
def test_success_when_fields_are_equal(): schema = Kanpai.Object({ 'name': Kanpai.String().required(), 'password': Kanpai.String().trim().required(), 'confirm_password': Kanpai.String().trim().required() }).assert_equal_field('password', 'confirm_password') result = schema.validate({ 'name': 'Kanpai', 'password': '******', 'confirm_password': '******' }) assert result.get('success') is True assert result.get('error') is None
def test_must_validate_all_invalid_data(): schema = Kanpai.Object({ 'name': Kanpai.String().required(), 'password': Kanpai.String().trim().required(), 'confirm_password': Kanpai.String().trim().required() }).assert_equal_field('password', 'confirm_password') result = schema.validate({}) assert result.get('success') is False assert result.get('error') == { 'name': 'Value is required', 'password': '******', 'confirm_password': '******' }
def post(self, *args, **kwargs): data = request.get_json() accountnumber = data.get('accountnumber', "") accountname = data.get('accountname', "") schema = Kanpai.Object({ "accountnumber": Kanpai.String().required(), "accountname": Kanpai.String().required() }) validation_results = schema.validate(data) Validations.validate_error(obj=validation_results) is_accountnumber = session.query(CorperateAccountDB).filter_by( accountnumber=accountnumber).first() is_accountname = session.query(CorperateAccountDB).filter_by( accountname=accountname).first() if is_accountnumber: return jsonify({ "status": "error", "errors": f"account number {is_accountnumber} already present" }) if is_accountname: return jsonify({ "status": "error", "errors": f"account name {is_accountname} already present" }) if data: corpaccount = CorperateAccountDB(accountnumber=accountnumber, accountname=accountname) db.add(corpaccount) db.commit() return jsonify({ "status": "success", "data": validation_results["data"] })
def test_successful_validation(): schema = Kanpai.Object({ 'name': Kanpai.String(), 'permissions': Kanpai.Array().of(Kanpai.UUID()).required() }).required() result = schema.validate({ 'permissions': ['a7e459b9-0ec9-41f6-8c78-149ad76c943d'] }) assert result == { 'success': True, 'data': { 'permissions': [UUID('a7e459b9-0ec9-41f6-8c78-149ad76c943d')], 'name': None }, 'error': None}
def test_error_when_element_validation_error(): schema = Kanpai.Array().of( Kanpai.Object({ 'name': Kanpai.String().trim().required(), 'age': Kanpai.Number().integer() })).required() result = schema.validate([{ 'name': ' Rpose ion ', 'age': 46 }, { 'age': '98' }]) assert result.get('success') is False assert result.get('error').get(1, None) is not None
def test_success_when_element_validation_success(): schema = Kanpai.Array().of( Kanpai.Object({ 'name': Kanpai.String().trim().required(), 'age': Kanpai.Number().integer() })).required() result = schema.validate([{ 'name': ' Rpose ion ', 'age': 46 }, { 'age': '98', 'name': 'Mert rt' }]) assert result.get('success') is True
def test_handle(): schema = Kanpai.String(error="Field must be a text.").max( 5, error="Maximum allowed value is 5").min( 2, error="Minimum required value is 2") result = schema.validate('asdasdasdasdas dasd a sdadsad') assert result['success'] is False assert result['error'] is not None assert result['error'] == "Maximum allowed value is 5"
def post(self, *args, **kwargs): schema = Kanpai.Object({ "username": (Kanpai.String( error='User first name must be string.').trim().required( error='Please provide user first name.').max( 32, error='Maximum allowed length is 32')), "email": (Kanpai.Email(error='User email must be proper.').trim().required( error='Please provide user email.').max( 32, error='Maximum allowed length is 32')), "phone": (Kanpai.String( error='User phone number must be string.').trim().required( error='Please provide user phone number.').max( 13, error='Maximum allowed length is 13')), "gender": (Kanpai.String().trim()), "firstname": Kanpai.String(error='User phone number must be string.'), "surename": Kanpai.String(error='User phone number must be string.'), "DOB": (Kanpai.String().trim()), "idname": Kanpai.String(error="It's not required") }) data = request.get_json() validation_result = schema.validate(data) if validation_result.get('success', False) is False: return jsonify({ "status": "Error", "errors": validation_result.get("error") }) if data: idtypeid = session.query(IdTypeDB).filter_by( name=data['idname']).first() user = UserDB( username=data['username'], email=data['email'] if data['email'] else '*****@*****.**', phone=data['phone'], gender=data['gender'], firstname=data['firstname'], surename=data['surename'], DOB=data['DOB'], idnumber=idtypeid.id) db.add(user) db.commit() return jsonify({ "statu": "success", "data": validation_result["data"] })
def test_default_error_when_fields_not_equal(): schema = Kanpai.Object({ 'name': Kanpai.String().required(), 'password': Kanpai.String().trim().required(), 'confirm_password': Kanpai.String().trim().required() }).assert_equal_field('password', 'confirm_password') result = schema.validate({ 'name': 'Kanpai', 'password': '******', 'confirm_password': '******' }) assert result.get('success') is False assert result.get('error') == { 'confirm_password': '******' }
def validateAudiobook(requestBody): schema = Kanpai.Object({ "audiotype": Kanpai.String(error="audio type must be a string").required( error="audiotype is required"), "metadata": Kanpai.Object({ "title": Kanpai.String(error="audiobook title must be a string").max( 100).required(error="title is required"), "author": Kanpai.String( error="author must be a string").max(100).required( error="author is required"), "narrator": Kanpai.String( error="narrator must be a string").max(100).required( error="narrator is required"), "duration": Kanpai.Number(error="duration must be an int").required( error="duration is required") }).required(error="metadata is required") }).required(error="Invalid request body passed") valid_result = schema.validate(requestBody) return valid_result
def post(self) -> Response: schema = Kanpai.Object({ 'bookingID': Kanpai.String().required(), 'staffID': Kanpai.String().required(), 'patentID': Kanpai.String().required(), 'detail': Kanpai.String().required(), 'dateBooking': Kanpai.String().required(), 'status': Kanpai.String().required(), 'create_at': Kanpai.String().required(), 'update_at': Kanpai.String().required() }) body = request.get_json() key = uuid.uuid4().int data = { 'bookingID': str(key)[0:6], 'staffID': body['staffID'], 'patentID': body['patentID'], 'detail': body['detail'], 'dateBooking': body['dateBooking'], 'status': "กำลังรอคิว", 'create_at': str(datetime.utcnow()), 'update_at': str(datetime.utcnow()) } validate_result = schema.validate(data) if validate_result.get('success', False) is False: response = jsonify({"data":None,"message":"error","status":400}) response.status_code = 400 return response patent = Patients.objects(patentID=body['patentID']) if len(patent) > 0: try: Bookings(**data).save() response = jsonify({"data":data,"message":"success","status":201}) response.status_code = 201 return response except NotUniqueError: response = jsonify({"data":None,"message":"ID already exit.","status":400}) response.status_code = 400 return response else: response = jsonify({"data":None,"message":"error","status":204}) response.status_code = 204 return response
def test_user_defined_error_when_fields_not_equal(): schema = Kanpai.Object({ 'name': Kanpai.String().required(), 'password': Kanpai.String().trim().required(), 'confirm_password': Kanpai.String().trim().required() }).assert_equal_field('password', 'confirm_password', error="Please re-type password correctly.") result = schema.validate({ 'name': 'Kanpai', 'password': '******', 'confirm_password': '******' }) assert result.get('success') is False assert result.get('error') == { 'confirm_password': '******' }
def post(self, *args, **kwargs): data = request.get_json() schema = Kanpai.Object({ "rolecode": (Kanpai.Number().integer().between(1, 10)), "roledesc": (Kanpai.String(error="Role desc should be String").trim().required( error="Role code is required")), "status": (Kanpai.String( error="Role desc should be active, deactive").trim().required( error="Role code is required")) }) validation_results = schema.validate(data) if validation_results.get('success', False) is False: return jsonify({ "status": "error", "errors": validation_results.get('error') }) is_role_duplcate = session.query(RoleDB).filter_by( rolecode=data['rolecode']).first() if is_role_duplcate: return jsonify({ "status": "error", "errors": f"role code {is_role_duplcate.rolecode} already present" }) if data: role = RoleDB(rolecode=data['rolecode'], roledesc=data['roledesc'], status=data['status']) db.add(role) db.commit() return jsonify({ "status": "success", "data": validation_results["data"] })
def validateSong(requestBody): schema = Kanpai.Object({ "audiotype": Kanpai.String(error="audio type must be a string").required( error="audiotype is required"), "metadata": Kanpai.Object({ "name": Kanpai.String( error="Song name must be a string").max(100).required( error="name is required"), "duration": Kanpai.Number(error="duration must be an int").min(0).required( error="duration is required") }).required(error="metadata is required") }).required(error="Invalid request body passed") valid_result = schema.validate(requestBody) return valid_result
def test_should_validate_properly(): schema = Kanpai.Object({ 'name': (Kanpai.String('User name must be string') .trim() .required('Please provide user name')), 'company': (Kanpai.String('Company must be string') .trim() .required('Please provide company name')) }) result = schema.validate({ 'name': ' Chandrakanta ', 'company': 'kanpai ' }) assert result.get('success') is True assert result.get('data') is not None assert result.get('data').get('name') == 'Chandrakanta' assert result.get('data').get('company') == 'kanpai'
def test_success_on_extra_key_if_ignore_true(): schema = Kanpai.Object({ 'name': (Kanpai.String('User name must be string') .trim() .required('Please provide user name')), 'company': (Kanpai.String('Company must be string') .trim() .required('Please provide company name')) }, ignore_extra_key=True) result = schema.validate({ 'name': ' Chandrakanta ', 'company': 'kanpai ', 'age': 32 }) assert result.get('success') is True assert result.get('error') is None assert result.get('data').get('age') == 32