def make_error(uploaded_file, er=None, id_=None): if er is None: er = ServerError(source='{}', detail="Internal Server Error") istr = 'File %s' % uploaded_file if id_ is not None: istr = '%s, ID %s' % (istr, id_) if hasattr(er, 'title'): er.title = '%s, %s' % (istr, er.title) if not hasattr(er, 'status') or not er.status: er.status = 500 return er
def test_errors(self): """Method to test the status code of all errors""" with app.test_request_context(): # Forbidden Error forbidden_error = ForbiddenError({'source': ''}, 'Super admin access is required') self.assertEqual(forbidden_error.status, 403) # Not Found Error not_found_error = NotFoundError({'source': ''}, 'Object not found.') self.assertEqual(not_found_error.status, 404) # Server Error server_error = ServerError({'source': ''}, 'Internal Server Error') self.assertEqual(server_error.status, 500) # UnprocessableEntity Error unprocessable_entity_error = UnprocessableEntityError( {'source': ''}, 'Entity cannot be processed') self.assertEqual(unprocessable_entity_error.status, 422) # Bad Request Error bad_request_error = BadRequestError({'source': ''}, 'Request cannot be served') self.assertEqual(bad_request_error.status, 400)
def test_exceptions(self): """Method to test all exceptions.""" # Unprocessable Entity Exception with self.assertRaises(UnprocessableEntityError): raise UnprocessableEntityError( {'pointer': '/data/attributes/min-quantity'}, "min-quantity should be less than max-quantity", ) # Conflict Exception with self.assertRaises(ConflictError): raise ConflictError({'pointer': '/data/attributes/email'}, "Email already exists") # Forbidden Exception with self.assertRaises(ForbiddenError): raise ForbiddenError({'source': ''}, "Access Forbidden") # Not Found Error with self.assertRaises(NotFoundError): raise NotFoundError({'source': ''}, "Not Found") # Server Error with self.assertRaises(ServerError): raise ServerError({'source': ''}, "Internal Server Error") # Bad Request Error with self.assertRaises(BadRequestError): raise BadRequestError({'source': ''}, "Bad Request") # Method Not Allowed Exception with self.assertRaises(MethodNotAllowed): raise MethodNotAllowed({'source': ''}, "Method Not Allowed")
def test_errors(): """Method to test the status code of all errors""" forbidden_error = ForbiddenError({'source': ''}, 'Super admin access is required') assert forbidden_error.status == 403 not_found_error = NotFoundError({'source': ''}, 'Object not found.') assert not_found_error.status == 404 server_error = ServerError({'source': ''}, 'Internal Server Error') assert server_error.status == 500 unprocessable_entity_error = UnprocessableEntityError( {'source': ''}, 'Entity cannot be processed') assert unprocessable_entity_error.status == 422 bad_request_error = BadRequestError({'source': ''}, 'Request cannot be served') assert bad_request_error.status == 400
def test_errors(self): """Check ErrorsHelper: errors codes""" with app.test_request_context(): # Base error base_error = ErrorResponse({'source': ''}, 'Internal Server Error.', title='Internal Server Error.', status=500) self.assertEqual(base_error.status, 500) # Forbidden Error forbidden_error = ForbiddenError({'source': ''}, 'Super admin access is required') self.assertEqual(forbidden_error.status, 403) # Not Found Error not_found_error = NotFoundError({'source': ''}, 'Object not found.') self.assertEqual(not_found_error.status, 404) # Not Found Error internal_server_error = ServerError({'source': ''}, 'Internal Server Error.') self.assertEqual(internal_server_error.status, 500)
def import_event_json(task_handle, zip_path, creator_id): """ Imports and creates event from json zip """ global CUR_ID, UPLOAD_QUEUE UPLOAD_QUEUE = [] update_state(task_handle, 'Started') with app.app_context(): path = app.config['BASE_DIR'] + '/static/uploads/import_event' # delete existing files if os.path.isdir(path): shutil.rmtree(path, ignore_errors=True) # extract files from zip with zipfile.ZipFile(zip_path, "r") as z: z.extractall(path) # create event try: update_state(task_handle, 'Importing event core') data = json.loads(open(path + '/event', 'r').read()) _, data = _trim_id(data) srv = ('event', Event) data = _delete_fields(srv, data) new_event = Event(**data) save_to_db(new_event) role = Role.query.filter_by(name=OWNER).first() user = User.query.filter_by(id=creator_id).first() uer = UsersEventsRoles(user_id=user.id, event_id=new_event.id, role_id=role.id) save_to_db(uer, 'Event Saved') write_file( path + '/social_links', json.dumps(data.get('social_links', [])).encode('utf-8') ) # save social_links _upload_media_queue(srv, new_event) except Exception as e: raise make_error('event', er=e) # create other services try: service_ids = {} for item in IMPORT_SERIES: item[1].is_importing = True data = open(path + '/%s' % item[0], 'r').read() dic = json.loads(data) changed_ids = create_service_from_json( task_handle, dic, item, new_event.id, service_ids) service_ids[item[0]] = changed_ids.copy() CUR_ID = None item[1].is_importing = False except IOError: db.session.delete(new_event) db.session.commit() raise NotFoundError('File %s missing in event zip' % item[0]) except ValueError: db.session.delete(new_event) db.session.commit() raise make_error(item[0], er=ServerError(source='Zip Upload', detail='Invalid json')) except Exception: print(traceback.format_exc()) db.session.delete(new_event) db.session.commit() raise make_error(item[0], id_=CUR_ID) # run uploads _upload_media(task_handle, new_event.id, path) # return return new_event
def server_error(e): if request_wants_json(): error = ServerError() return json.dumps(error.to_dict()), getattr(error, 'code', 500) return render_template('gentelella/errors/500.html'), 500
def test_make_error(self): """Method to test make_error function""" # When er is None and _id is None expected_response_title = 'File event, Internal Server Error' expected_response_status = 500 actual_response = make_error('event') self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er is not None, _id is None, er doesen't have title and status error = ServerError(source='Zip Upload', detail='Invalid json') expected_response_title = 'File event, Internal Server Error' expected_response_status = 500 actual_response = make_error('event', er=error) self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er is not None, _id is None, er have title but not status error = ServerError(source='Zip Upload', detail='Invalid json', title="Error while uploading.") expected_response_title = 'File event, Error while uploading.' expected_response_status = 500 actual_response = make_error('event', er=error) self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er is not None, _id is None, er doesn't have title but has status error = ServerError(source='Zip Upload', detail='Invalid json', status=404) expected_response_title = 'File event, Internal Server Error' expected_response_status = 404 actual_response = make_error('event', er=error) self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er is not None, _id is None, er have title and status error = ServerError( source='Zip Upload', detail='Invalid json', title="Error while uploading.", status=403, ) expected_response_title = 'File event, Error while uploading.' expected_response_status = 403 actual_response = make_error('event', er=error) self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er and _id are not None error = ServerError(source='{}', detail='Internal Server Error', title='Internal Server Error') expected_response_title = 'File event, ID ERR_255, Internal Server Error' expected_response_status = 500 actual_response = make_error('event', er=error, id_='ERR_255') self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError) # When er is None and _id is not None actual_response = make_error('event', id_='ERR_255') expected_response_title = 'File event, ID ERR_255, Internal Server Error' expected_response_status = 500 self.assertEqual(expected_response_status, actual_response.status) self.assertEqual(expected_response_title, actual_response.title) self.assertIsInstance(actual_response, ServerError)