def get(self, session): """ Method will give all the db_connection_ids and db connection name. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that success), data and http status code. """ db_connection_detail = reqparse.RequestParser() db_connection_detail.add_argument('project_id', required=True, type=int, location='args') project_data = db_connection_detail.parse_args() project_obj = Project.query.filter( Project.project_id == project_data['project_id'], Project.is_deleted == False).first() if not project_obj: raise ResourceNotAvailableException("Project") check_permission(session.user, DB_CONNECTION_GET, project_obj.org_id, project_data["project_id"]) payload = get_db_connection(project_data['project_id']) return api_response(True, APIMessages.SUCCESS, STATUS_CREATED, payload)
def get(self, session): """ To execute and export the data for the given query id. Args: session: session(Object): session gives user ID of the owner who is execution the job Returns: Returns exported file via socket """ query_parser = reqparse.RequestParser() query_parser.add_argument('query_id', type=int, required=True, help=APIMessages.PARSER_MESSAGE, location='args') query_data = query_parser.parse_args() query_obj = Query.query.filter_by( query_id=query_data['query_id']).first() if not query_obj: return api_response(False, APIMessages.WRONG_QUERY_ID, STATUS_BAD_REQUEST) project_obj = Project.query.filter_by( project_id=query_obj.project_id).first() check_permission(session.user, list_of_permissions=["execute"], org_id=project_obj.org_id, project_id=project_obj.project_id) run_quer_analyser_by_id(query_obj.query_id, session.user_id, export=True)
def delete(self, session): """ DELETE call to delete organization details. Args: session(object): User session Returns: Standard API Response with HTTP status code """ projects = [] user_associated = [] get_org_parser = reqparse.RequestParser() get_org_parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int) get_org_data = get_org_parser.parse_args() org_obj = Organization.query.filter_by(org_id=get_org_data['org_id'], is_deleted=False).first() if not org_obj: return api_response(False, APIMessages.NO_RESOURCE.format('Organization'), STATUS_UNAUTHORIZED) check_permission(user_object=session.user, list_of_permissions=ORG_DELETE, org_id=get_org_data['org_id']) project_obj = Project.query.filter_by(org_id=get_org_data["org_id"], is_deleted=False).order_by( Project.project_id).all() user_org_role_obj = UserOrgRole.query.filter_by( org_id=get_org_data["org_id"]).distinct( UserOrgRole.user_id).with_entities(UserOrgRole.user_id).all() if not project_obj and not user_org_role_obj: org_obj.is_deleted = True org_obj.save_to_db() return api_response(True, APIMessages.ORG_DELETED, STATUS_OK) else: for each_obj in project_obj: projects.append({ "project_id": each_obj.project_id, "project_name": each_obj.project_name }) user_obj_list = User.query.filter( User.user_id.in_(user_org_role_obj)).order_by( User.user_id).all() for each_user in user_obj_list: user_associated.append({ "user_id": each_user.user_id, "email_id": each_user.email }) return api_response( False, APIMessages.DELETE_ORG_FALSE, STATUS_OK, { "org_id": get_org_data['org_id'], "project_name": org_obj.org_name, "associated_project": projects, "asociated_users": user_associated })
def post(self, session): """ Post call to create Project with name and organization Id. Args: session(object): User session Returns: Standard API Response with HTTP status code """ create_project_parser = reqparse.RequestParser(bundle_errors=True) create_project_parser.add_argument( 'project_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str, location='json') create_project_parser.add_argument( 'project_description', help=APIMessages.PARSER_MESSAGE, required=True, type=str, location='json') create_project_parser.add_argument( 'org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int, location='json') create_project_data = create_project_parser.parse_args() org_obj = Organization.query.filter_by( org_id=create_project_data['org_id'], is_deleted=False).first() if not org_obj: raise GenericBadRequestException(APIMessages.INVALID_ORG_ID) check_permission(user_object=session.user, list_of_permissions=PROJECT_POST, org_id=create_project_data["org_id"]) create_project_data['project_name'] = create_project_data[ 'project_name'].strip() list_of_args = [arg.name for arg in create_project_parser.args] request_data_validation = validate_empty_fields( create_project_data, list_of_args) if request_data_validation: return api_response(success=False, message=request_data_validation, http_status_code=STATUS_BAD_REQUEST, data={}) new_project = Project(create_project_data['project_name'], create_project_data['project_description'], create_project_data['org_id'], session.user_id) new_project.save_to_db() project_payload = {'project_name': new_project.project_name, 'project_id': new_project.project_id, 'project_description': new_project.project_description, 'org_id': new_project.org_id} return api_response(True, APIMessages.CREATE_RESOURCE.format('Project'), STATUS_CREATED, project_payload)
def put(self, session): """ PUT call to update project name. Args: session(object): User session Returns: Standard API Response with HTTP status code """ update_project_parser = reqparse.RequestParser(bundle_errors=True) update_project_parser.add_argument( 'project_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int) update_project_parser.add_argument( 'project_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str) update_project_parser.add_argument( 'project_description', help=APIMessages.PARSER_MESSAGE, required=True, type=str) update_project_data = update_project_parser.parse_args() current_project = Project.query.filter_by( project_id=update_project_data['project_id'], is_deleted=False).first() if not current_project: return api_response(False, APIMessages.PROJECT_NOT_EXIST, STATUS_BAD_REQUEST) check_permission(user_object=session.user, list_of_permissions=PROJECT_PUT, project_id=update_project_data["project_id"], org_id=current_project.org_id) update_project_data['project_name'] = update_project_data[ 'project_name'].strip() update_project_data['project_description'] = update_project_data[ 'project_description'].strip() list_of_args = [arg.name for arg in update_project_parser.args] request_data_validation = validate_empty_fields( update_project_data, list_of_args) if request_data_validation: return api_response(success=False, message=request_data_validation, http_status_code=STATUS_BAD_REQUEST, data={}) current_project.project_name = update_project_data['project_name'] current_project.project_description = update_project_data[ 'project_description'] current_project.save_to_db() return api_response(True, APIMessages.UPDATE_RESOURCE.format('Project'), STATUS_OK)
def get(self, session): """ API returns users present in given org. Args: session (object): Session Object Returns: API response with Users in org """ parser = reqparse.RequestParser() parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int, location='args') user_api_parser = parser.parse_args() check_valid_id_passed_by_user(org_id=user_api_parser['org_id']) # TODO: Add a check to verify user management permission check_permission(user_object=session.user, list_of_permissions=USER_API_GET, org_id=user_api_parser["org_id"]) user_project_role = UserProjectRole.query.filter( UserProjectRole.org_id == user_api_parser['org_id']).distinct( UserProjectRole.user_id).all() user_org_role = UserOrgRole.query.filter( UserOrgRole.org_id == user_api_parser['org_id']).distinct( UserOrgRole.user_id).all() user_id_list_in_project = [ each_user.user_id for each_user in user_project_role ] user_id_list_in_org = [ each_user.user_id for each_user in user_org_role ] user_id_list = [user_id_list_in_org, user_id_list_in_project] unique_user_id_list = set().union(*user_id_list) all_user_details = User.query.filter( User.user_id.in_(unique_user_id_list)).order_by( User.user_id).all() final_data = [] for each_user in all_user_details: temp_dict = dict() temp_dict['user_id'] = each_user.user_id temp_dict['first_name'] = each_user.first_name temp_dict['last_name'] = each_user.last_name temp_dict['email'] = each_user.email final_data.append(temp_dict) data = {"org_id": user_api_parser['org_id'], "users": final_data} return api_response(True, APIMessages.SUCCESS, STATUS_OK, data)
def delete(self, session): """ To delete the Test Case for the user provided test case id. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that Test Case Deleted Successfully) and http status code. """ delete_test_case_detail_parser = reqparse.RequestParser() delete_test_case_detail_parser.add_argument('test_case_id', required=True, type=int, location='args') test_case_data = delete_test_case_detail_parser.parse_args() test_case_obj = TestCase.query.filter( TestCase.test_case_id == test_case_data["test_case_id"], TestCase.is_deleted == False).first() if not test_case_obj: return api_response( False, APIMessages.TEST_CASE_NOT_IN_DB.format( test_case_data["test_case_id"]), STATUS_BAD_REQUEST) project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter(Project.is_deleted == False).join( TestSuite, Project.project_id == TestSuite.project_id).filter( TestSuite.test_suite_id == test_case_obj.test_suite_id, TestSuite.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_TEST_CASE, STATUS_BAD_REQUEST) check_permission(session.user, EDIT_TEST_CASE_DELETE, project_id_org_id[0], project_id_org_id[1]) test_case_obj.is_deleted = True test_case_obj.save_to_db() return api_response( True, APIMessages.TEST_CASE_DELETED.format( test_case_data["test_case_id"]), STATUS_CREATED)
def put(self, session): """ PUT call to Update Organization name. Args: session(object): User session Returns: Standard API Response with HTTP status code """ update_org_parser = reqparse.RequestParser(bundle_errors=True) update_org_parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int, location='json') update_org_parser.add_argument('org_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str, location='json') update_org_parser.add_argument('org_description', help=APIMessages.PARSER_MESSAGE, required=True, type=str, location='json') update_org_data = update_org_parser.parse_args() user_obj = User.query.filter_by(user_id=session.user_id, is_deleted=False).first() current_org = Organization.query.filter_by( org_id=update_org_data['org_id'], is_deleted=False).first() if not current_org: raise ResourceNotAvailableException("Organization") check_permission(user_obj, list_of_permissions=ORGANIZATION_API_PUT, org_id=current_org.org_id) current_org.org_name = update_org_data['org_name'] current_org.org_description = update_org_data['org_description'] current_org.save_to_db() return api_response(True, APIMessages.UPDATE_RESOURCE.format('Organization'), STATUS_OK)
def get(self, session): """ Method call will return the log of the Executed case based on its test_case_log_id Returns: return the log of the case_log_id """ user_id = session.user_id test_case_log = reqparse.RequestParser() test_case_log.add_argument('test_case_log_id', required=True, type=int, location='args') test_case_logid = test_case_log.parse_args() test_case_log_obj = TestCaseLog.query.filter_by( test_case_log_id=test_case_logid['test_case_log_id']).first() if not test_case_log_obj: raise ResourceNotAvailableException( APIMessages.TESTCASELOGID_NOT_IN_DB.format( test_case_logid['test_case_log_id'])) user_obj = User.query.filter_by(user_id=user_id).first() project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id ).filter(Project.is_deleted == False).join( TestSuite, Project.project_id == TestSuite.project_id ).filter(TestSuite.is_deleted == False).join( TestCase, TestSuite.test_suite_id == TestCase.test_suite_id).filter( TestCase.test_case_id == test_case_log_obj.test_case_id, TestCase.is_deleted == False).first() check_permission(user_obj, list_of_permissions=TEST_CASE_LOG_DETAIL_GET, org_id=project_id_org_id[1], project_id=project_id_org_id[0]) test_case_log = test_case_log.parse_args() log_data = { "test_case_log": return_all_log(test_case_log['test_case_log_id']), "success": True } return api_response(True, APIMessages.SUCCESS, STATUS_CREATED, log_data)
def delete(self, session): """ To delete the role for the user provided role id. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that Role Deleted Successfully) and http status code. """ delete_role_parser = reqparse.RequestParser() delete_role_parser.add_argument('role_id', required=True, type=int, location='json') deletedata = delete_role_parser.parse_args() role_obj = Role.query.filter( Role.role_id == deletedata["role_id"]).first() if not role_obj: return api_response(False, APIMessages.NO_RESOURCE.format("Role"), STATUS_BAD_REQUEST) check_permission(session.user, ROLE_API_DELETE, role_obj.org_id) user_org_role_object = UserOrgRole.query.filter_by( user_id=session.user_id, org_id=role_obj.org_id, role_id=deletedata["role_id"]).first() user_project_role_project = UserProjectRole.query.filter_by( user_id=session.user_id, org_id=role_obj.org_id, role_id=deletedata["role_id"]).first() if user_org_role_object or user_project_role_project: return api_response(False, "Role Cannot be deleted", STATUS_BAD_REQUEST) RolePermission.query.filter_by(org_id=role_obj.org_id, role_id=deletedata["role_id"]).delete() role_obj.delete_from_db() return api_response(True, APIMessages.ROLE_DELETED, STATUS_CREATED)
def post(self, session): """ Post call to create Organization with name. Args: session(object): User session Returns: Standard API Response with HTTP status code """ user_id = session.user_id user_obj = User.query.filter_by(user_id=user_id, is_deleted=False).first() create_org_parser = reqparse.RequestParser(bundle_errors=True) create_org_parser.add_argument('org_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str) create_org_parser.add_argument('org_description', help=APIMessages.PARSER_MESSAGE, required=True, type=str) create_org_data = create_org_parser.parse_args() check_permission(user_obj) create_organization = Organization(create_org_data['org_name'], create_org_data['org_description'], session.user_id) create_organization.save_to_db() organization_data = { 'org_id': create_organization.org_id, 'org_name': create_organization.org_name, 'org_description': create_organization.org_description } return api_response(True, APIMessages.CREATE_RESOURCE.format('Organization'), STATUS_CREATED, organization_data)
def get(self, session): """ Method will Export log to Excel based on the test_case_log_id of the executed job Returns: Export log to Excel based on the test_case_log_id of the executed job """ user_id = session.user_id test_case_log = reqparse.RequestParser() test_case_log.add_argument('test_case_log_id', required=False, type=int, location='args') test_case_log = test_case_log.parse_args() test_case_log_obj = TestCaseLog.query.filter_by( test_case_log_id=test_case_log['test_case_log_id']).first() if not test_case_log_obj: raise ResourceNotAvailableException( APIMessages.TESTCASELOGID_NOT_IN_DB.format( test_case_log['test_case_log_id'])) user_obj = User.query.filter_by(user_id=user_id).first() project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id ).filter(Project.is_deleted == False).join( TestSuite, Project.project_id == TestSuite.project_id ).filter(TestSuite.is_deleted == False).join( TestCase, TestSuite.test_suite_id == TestCase.test_suite_id).filter( TestCase.test_case_id == test_case_log_obj.test_case_id, TestCase.is_deleted == False).first() check_permission(user_obj, list_of_permissions=EXPORT_TEST_LOG_GET, org_id=project_id_org_id[1], project_id=project_id_org_id[0]) return export_test_case_log(test_case_log['test_case_log_id'])
def get(self, session): user_id = session.user_id test_case_detail = reqparse.RequestParser() test_case_detail.add_argument('test_case_id', required=False, type=int, location='args') test_case_detail = test_case_detail.parse_args() case_obj = TestCase.query.filter_by( test_case_id=test_case_detail['test_case_id']).first() if not case_obj: raise ResourceNotAvailableException( APIMessages.TEST_CASE_NOT_IN_DB.format( test_case_detail['test_case_id'])) user_obj = User.query.filter_by(user_id=user_id).first() suite_obj = TestSuite.query.filter_by( test_suite_id=case_obj.test_suite_id).first() project_obj = Project.query.filter_by( project_id=suite_obj.project_id).first() check_permission(user_obj, list_of_permissions=TEST_CASE_LOG_API_GET, org_id=project_obj.org_id, project_id=project_obj.project_id) return test_case_details(test_case_detail['test_case_id'])
def get(self, session): """ GET call to retrieve Menu details. Args: session(object): User session Returns: Standard API Response with HTTP status code """ get_menu_parser = reqparse.RequestParser(bundle_errors=True) get_menu_parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int) get_menu_data = get_menu_parser.parse_args() # Check if org id is valid valid_org = Organization.query.filter_by( org_id=get_menu_data['org_id']).first() if not valid_org: return api_response(False, APIMessages.NO_RESOURCE.format('Organization'), STATUS_BAD_REQUEST) # checking if user is authorized to make this call check_permission(session.user, org_id=get_menu_data['org_id']) # TODO: Check if user has permission to access the Menu Items result_dict = {'menu_items': []} get_menu_items = Menu.query.filter_by(is_active=True).order_by( Menu.menu_order).all() for each_menu in get_menu_items: result_dict['menu_items'].append({ 'menu_id': each_menu.menu_id, 'menu_name': each_menu.menu_name, 'menu_order': each_menu.menu_order }) return api_response(True, APIMessages.SUCCESS, STATUS_OK, result_dict)
def get(self, session): """ It returns all the test case details associated with the particular suite id provided in the args. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that success), data and http status code. """ suite_detail = reqparse.RequestParser() suite_detail.add_argument('suite_id', required=True, type=int, location='args') suite_data = suite_detail.parse_args() suite_obj = TestSuite.query.filter( TestSuite.test_suite_id == suite_data['suite_id'], TestSuite.is_deleted == False).first() if not suite_obj: raise ResourceNotAvailableException("test suite") else: project_obj = Project.query.filter( Project.project_id == suite_obj.project_id, Project.is_deleted == False).first() if not project_obj: return api_response( False, APIMessages.PROJECT_CONTAIN_SUITE_NOT_EXIST, STATUS_BAD_REQUEST) check_permission(session.user, CASE_DETAILS_GET, project_obj.org_id, suite_obj.project_id) payload = get_case_detail(suite_data['suite_id']) return api_response(True, APIMessages.SUCCESS, STATUS_CREATED, payload)
def post(self, session): """ Method will allow user to select connection for particular user Args: session (Obj): gives user_id of the user Returns:will allow user to select connection for particular user """ parser = reqparse.RequestParser() parser.add_argument('connection_reference', help=APIMessages.PARSER_MESSAGE, required=True) parser.add_argument('case_id_list', type=list, location="json", help=APIMessages.PARSER_MESSAGE) parser.add_argument('db_connection_id', help=APIMessages.PARSER_MESSAGE, required=True) data = parser.parse_args() user = session.user_id case_obj = TestCase.query.filter_by( test_case_id=data['case_id_list'][0]).first() suite_obj = TestSuite.query.filter_by( test_suite_id=case_obj.test_suite_id).first() project_obj = Project.query.filter_by( project_id=suite_obj.project_id).first() user_obj = User.query.filter_by(user_id=user).first() print(project_obj.org_id, project_obj.project_id) check_permission(user_obj, SELECT_CONNECTION_POST, org_id=project_obj.org_id, project_id=project_obj.project_id) select_connection(data, user) return api_response(True, APIMessages.CONNECTION_SETUP, STATUS_CREATED)
def post(self, session): """ It handles a POST API to add new test suite into database. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that test suite added successfully) and http status code. """ test_suite_parser = reqparse.RequestParser() test_suite_parser.add_argument('suite_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str) test_suite_parser.add_argument('project_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int) test_suite_parser.add_argument('test_case_detail', help=APIMessages.PARSER_MESSAGE, required=True, type=list, location='json') test_suite_data = test_suite_parser.parse_args() project_obj = Project.query.filter( Project.project_id == test_suite_data["project_id"], Project.is_deleted == False).first() if not project_obj: return api_response(False, APIMessages.PROJECT_NOT_EXIST, STATUS_BAD_REQUEST) check_permission(session.user, ADD_TEST_SUITE_MANUALLY_POST, project_obj.org_id, test_suite_data["project_id"]) # Check Test Suite name already exist in db or not test_suite_data["suite_name"] = test_suite_data["suite_name"].strip() temp_connection = TestSuite.query.filter( TestSuite.test_suite_name == test_suite_data["suite_name"], TestSuite.project_id == test_suite_data["project_id"], TestSuite.is_deleted == False).first() if temp_connection: return api_response(False, APIMessages.TEST_SUITE_NAME_ALREADY_PRESENT, STATUS_BAD_REQUEST) test_suite = TestSuite(project_id=test_suite_data["project_id"], owner_id=session.user_id, excel_name=None, test_suite_name=test_suite_data['suite_name']) test_suite.save_to_db() for each_test_case in test_suite_data['test_case_detail']: keys = [] for key in each_test_case: keys.append(key) if "test_case_class" not in keys: return api_response(False, APIMessages.PASS_TEST_CASE_CLASS, STATUS_BAD_REQUEST) if "test_description" not in keys: each_test_case["test_description"] = APIMessages.NO_NAME_DEFINE # if "source_table " and "target_table" not in keys: # return api_response(False, APIMessages.PASS_TABLES, # STATUS_BAD_REQUEST) if "source_db_existing_connection" in keys: source_db_existing_connection = each_test_case[ "source_db_existing_connection"] del each_test_case["source_db_existing_connection"] if "target_db_existing_connection" in keys: target_db_existing_connection = each_test_case[ "target_db_existing_connection"] del each_test_case["target_db_existing_connection"] for key, value in dict(each_test_case).items(): each_test_case[key] = value.strip() if "source_db_existing_connection" in keys: db_obj = DbConnection.query.filter( DbConnection.db_connection_id == source_db_existing_connection, DbConnection.is_deleted == False).first() if not db_obj: return api_response(False, APIMessages.DB_NOT_EXIST, STATUS_BAD_REQUEST) src_db_id = source_db_existing_connection if "target_db_existing_connection" in keys: db_obj = DbConnection.query.filter( DbConnection.db_connection_id == target_db_existing_connection, DbConnection.is_deleted == False).first() if not db_obj: return api_response(False, APIMessages.DB_NOT_EXIST, STATUS_BAD_REQUEST) target_db_id = target_db_existing_connection table = {} if "source_table" in keys: table[each_test_case["source_table"]] = each_test_case[ "target_table"] else: table[''] = each_test_case["target_table"] if "columns" not in keys: column = {} else: if each_test_case["columns"] == "": column = {} elif ";" and ":" in each_test_case["columns"]: column = {} user_columns = each_test_case["columns"].split(";") for columnpair in user_columns: if ":" in columnpair: singlecolumn = columnpair.split(":") column[singlecolumn[0]] = \ singlecolumn[1] else: column[columnpair] = columnpair elif ";" in each_test_case["columns"]: column = {} columns = each_test_case["columns"].split(";") for singlecolumn in columns: column[singlecolumn] = singlecolumn else: column = {} column[each_test_case["columns"]] = \ each_test_case["columns"] query = {} if "source_query" not in keys and "target_query" not in keys: query["sourceqry"] = "" query["targetqry"] = "" elif "source_query" not in keys: query["sourceqry"] = "" query["targetqry"] = each_test_case["target_query"] else: query["sourceqry"] = each_test_case["source_query"] query["targetqry"] = each_test_case["target_query"] jsondict = {} jsondict['column'] = column jsondict['table'] = table jsondict['query'] = query if "source_db_existing_connection" in keys: jsondict['src_db_id'] = src_db_id jsondict['target_db_id'] = target_db_id jsondict['test_desc'] = each_test_case["test_description"] test_case = TestCase( test_suite_id=test_suite.test_suite_id, owner_id=session.user_id, test_case_class=SupportedTestClass().get_test_class_id_by_name( each_test_case["test_case_class"]), test_case_detail=jsondict) test_case.save_to_db() return api_response(True, APIMessages.TEST_SUITE_ADDED, STATUS_CREATED)
def post(self, session): """ To create a new test suite from the given test case list. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that New Test Suite created),http status code. """ parser = reqparse.RequestParser() parser.add_argument('case_id_list', help=APIMessages.PARSER_MESSAGE, required=True, type=list, location='json') parser.add_argument('suite_name', help=APIMessages.PARSER_MESSAGE, required=False, type=str, location='json') test_suite_data = parser.parse_args() current_user = session.user_id # checking whether test cases passed by user are present in db or not for each_test_case_id in test_suite_data["case_id_list"]: test_case = TestCase.query.filter( TestCase.test_case_id == each_test_case_id, TestCase.is_deleted == False).first() if not test_case: return api_response(False, APIMessages.TEST_CASE_ABSENT, STATUS_BAD_REQUEST) project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter( Project.is_deleted == False).join( TestSuite, Project.project_id == TestSuite.project_id).filter( TestSuite.test_suite_id == test_case.test_suite_id, TestSuite.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_TEST_CASE, STATUS_BAD_REQUEST) check_permission(session.user, CREATE_NEW_TEST_SUITE_POST, project_id_org_id[0], project_id_org_id[1]) get_excel_name_and_project_id = return_excel_name_and_project_id( test_suite_data["case_id_list"][0]) # check whether test suite present in db or not if get_excel_name_and_project_id["user"][0]["test_suite_id"] == []: return api_response(False, APIMessages.TEST_SUITE_ABSENT, STATUS_BAD_REQUEST) project_id = \ get_excel_name_and_project_id["user"][0]["test_suite_id"][0][ "project_id"] excel_name = \ get_excel_name_and_project_id["user"][0]["test_suite_id"][0][ "excel_name"] if test_suite_data["suite_name"] == None or test_suite_data[ "suite_name"] == " ": now = datetime.now() date_time_now = now.strftime("%d/%m/%Y %H:%M:%S") test_suite_data[ "suite_name"] = APIMessages.QUALITY_SUITE + date_time_now new_test_suite = TestSuite( project_id=project_id, owner_id=current_user, excel_name=excel_name, test_suite_name=test_suite_data["suite_name"]) new_test_suite.save_to_db() for each_test_case_id in test_suite_data["case_id_list"]: test_case = TestCase.query.filter_by( test_case_id=each_test_case_id).first() new_test_case = TestCase( test_suite_id=new_test_suite.test_suite_id, owner_id=current_user, test_case_class=test_case.test_case_class, test_case_detail=test_case.test_case_detail) new_test_case.save_to_db() return api_response(True, APIMessages.NEW_TEST_SUITE_CREATED, STATUS_CREATED) else: # Check Test Suite name already exist in db or not test_suite_data["suite_name"] = test_suite_data[ "suite_name"].strip() temp_connection = TestSuite.query.filter( TestSuite.test_suite_name == test_suite_data["suite_name"], TestSuite.project_id == project_id, TestSuite.is_deleted == False).first() if temp_connection: return api_response( False, APIMessages.TEST_SUITE_NAME_ALREADY_PRESENT, STATUS_BAD_REQUEST) new_test_suite = TestSuite( project_id=project_id, owner_id=current_user, excel_name=excel_name, test_suite_name=test_suite_data["suite_name"]) new_test_suite.save_to_db() for each_test_case_id in test_suite_data["case_id_list"]: test_case = TestCase.query.filter_by( test_case_id=each_test_case_id).first() new_test_case = TestCase( test_suite_id=new_test_suite.test_suite_id, owner_id=current_user, test_case_class=test_case.test_case_class, test_case_detail=test_case.test_case_detail) new_test_case.save_to_db() return api_response(True, APIMessages.NEW_TEST_SUITE_CREATED, STATUS_CREATED)
def delete(self, session): """ DELETE call to delete UserProjectRole and UserOrgRole records. Args: session (object): User Session Returns: Standard API Response with HTTP status code """ parser = reqparse.RequestParser() parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int, location='args') parser.add_argument('user_id', help=APIMessages.PARSER_MESSAGE, required=False, type=int, location='args') parser.add_argument('email_id', help=APIMessages.PARSER_MESSAGE, required=False, type=str, location='args') delete_role_api_parser = parser.parse_args() result_dict = {} # Checking if User Id or Email Id is mandatorily passed if not delete_role_api_parser['user_id'] and \ not delete_role_api_parser['email_id']: return api_response(False, APIMessages.EMAIL_USER, STATUS_BAD_REQUEST) if delete_role_api_parser['user_id'] and delete_role_api_parser[ 'email_id']: raise GenericBadRequestException(APIMessages.ONLY_USER_OR_EMAIL) # Storing user id if user id is passed user_id = delete_role_api_parser['user_id'] \ if delete_role_api_parser['user_id'] else None # checking if User Id is valid if delete_role_api_parser['user_id']: check_valid_id_passed_by_user( org_id=delete_role_api_parser['org_id'], user_id=delete_role_api_parser['user_id']) check_permission(user_object=session.user, list_of_permissions=USER_ROLE_API_DELETE, org_id=delete_role_api_parser["org_id"]) # Get user Id based on email Id passed if delete_role_api_parser['email_id'] and \ not delete_role_api_parser['user_id']: check_valid_id_passed_by_user( org_id=delete_role_api_parser['org_id']) user_record = User.query.filter( User.email.ilike(delete_role_api_parser['email_id']), User.is_deleted == False).first() if not user_record: raise ResourceNotAvailableException("User") user_id = user_record.user_id result_dict['email_id'] = user_record.email user_project_role_obj = UserProjectRole.query.filter( UserProjectRole.org_id == delete_role_api_parser["org_id"], UserProjectRole.user_id == user_id).all() user_org_role_obj = UserOrgRole.query.filter( UserOrgRole.org_id == delete_role_api_parser["org_id"], UserOrgRole.user_id == user_id).all() session_obj = Session.query.filter(Session.user_id == user_id).all() for each_project_org_session_role in (user_project_role_obj, user_org_role_obj, session_obj): for each_role in each_project_org_session_role: db.session.delete(each_role) db.session.commit() return api_response( True, APIMessages.USER_ROLE_DELETED.format( delete_role_api_parser["org_id"]), STATUS_CREATED)
def post(self, session): """ Method to store the Database Details provided by the user into the DB. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that db details added successfully), data and http status code. """ post_db_detail_parser = reqparse.RequestParser(bundle_errors=True) post_db_detail_parser.add_argument('project_id', required=True, type=int, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_connection_name', required=False, type=str, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_type', required=True, type=str, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_name', required=True, type=str, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_hostname', required=True, type=str, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_username', required=True, type=str, help=APIMessages.PARSER_MESSAGE) post_db_detail_parser.add_argument('db_password', required=True, type=str, help=APIMessages.PARSER_MESSAGE) db_detail = post_db_detail_parser.parse_args() project_id = db_detail["project_id"] project_obj = Project.query.filter( Project.project_id == db_detail["project_id"], Project.is_deleted == False).first() if not project_obj: return api_response(False, APIMessages.PROJECT_NOT_EXIST, STATUS_BAD_REQUEST) for key, value in dict(db_detail).items(): db_detail[key] = str(value).strip() list_of_args = [arg.name for arg in post_db_detail_parser.args] request_data_validation = validate_empty_fields( db_detail, list_of_args) if request_data_validation: return api_response(success=False, message=request_data_validation, http_status_code=STATUS_BAD_REQUEST, data={}) check_permission(session.user, DB_DETAILS_POST, project_obj.org_id, db_detail["project_id"]) # check whether combination of db_type,db_name,db_username, # db_hostname,project_id is already present in db or not temp_connection = DbConnection.query.filter( DbConnection.project_id == project_id, DbConnection.db_type == SupportedDBType().get_db_id_by_name( db_detail['db_type']), DbConnection.db_name == db_detail['db_name'], DbConnection.db_hostname.ilike(db_detail['db_hostname']), DbConnection.db_username == db_detail['db_username'], DbConnection.is_deleted == False).first() if temp_connection: return api_response(False, APIMessages.DB_DETAILS_ALREADY_PRESENT, STATUS_BAD_REQUEST) else: # Validating maximum characters if len(db_detail['db_connection_name']) > 100: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("100")) if len(db_detail['db_name']) > 50 or \ len(db_detail['db_hostname']) > 50 or \ len(db_detail['db_username']) > 50 or \ len(db_detail['db_password']) > 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) # Check Db connection name already exist in db or not temp_connection = DbConnection.query.filter( DbConnection.db_connection_name == db_detail["db_connection_name"], DbConnection.project_id == project_id, DbConnection.is_deleted == False).first() if temp_connection: return api_response( False, APIMessages.DB_CONNECTION_NAME_ALREADY_PRESENT, STATUS_BAD_REQUEST) # Checking spaces in database name,username and hostname spacecount_dbusername = db_detail["db_username"].find(" ") spacecount_dbhostanme = db_detail["db_hostname"].find(" ") spacecount_dbname = db_detail["db_name"].find(" ") if spacecount_dbusername > -1 or spacecount_dbhostanme > -1 \ or spacecount_dbname > -1: return api_response(False, APIMessages.NO_SPACES, STATUS_BAD_REQUEST) if SupportedDBType().get_db_id_by_name( db_detail['db_type']) is None: return api_response(success=False, message=APIMessages.DB_TYPE_NAME, http_status_code=STATUS_BAD_REQUEST, data={}) db_password = encrypt(db_detail["db_password"]) new_db = DbConnection( project_id=project_id, owner_id=session.user_id, db_connection_name=db_detail['db_connection_name'], db_type=SupportedDBType().get_db_id_by_name( db_detail['db_type']), db_name=db_detail['db_name'], db_hostname=db_detail["db_hostname"], db_username=db_detail["db_username"], db_encrypted_password=db_password, ) new_db.save_to_db() return api_response(True, APIMessages.DB_DETAILS_ADDED, STATUS_CREATED)
def post(self, session): """ Executes the manual query provided by the user returns Success response on Execution or error log in case of a error Args: session(Object): session gives user ID of the owner who is execution the job Returns: Return api response ,either successful job run or error. """ user_id = session.user_id query_parser = reqparse.RequestParser() query_parser.add_argument( 'project_id', type=int, required=True, location='json', help=APIMessages.PARSER_MESSAGE, ) query_parser.add_argument( 'connection_id', type=int, required=True, location='json', help=APIMessages.PARSER_MESSAGE, ) query_parser.add_argument( 'query', type=str, required=True, location='json', help=APIMessages.PARSER_MESSAGE, ) query_data = query_parser.parse_args() project_obj = Project.query.filter_by( project_id=query_data['project_id']).first() if not project_obj: return api_response(False, APIMessages.NO_RESOURCE.format('Project'), STATUS_BAD_REQUEST) db_connection = DbConnection.query.filter( DbConnection.db_connection_id == query_data['connection_id'], DbConnection.project_id == query_data['project_id']).first() if not db_connection: return api_response(False, APIMessages.WRONG_DB_CONNECTION, STATUS_BAD_REQUEST) check_permission(session.user, list_of_permissions=["execute"], org_id=project_obj.org_id, project_id=project_obj.project_id) query_obj = Query( project_id=project_obj.project_id, query_string=query_data['query'], db_connection_id=query_data['connection_id'], owner_id=user_id, execution_status=ExecutionStatus().get_execution_status_id_by_name( 'new')) query_obj.save_to_db() query_data = { "query_id": query_obj.query_id, "query": query_obj.query_string, "execution_status": query_obj.execution_status } run_quer_analyser_by_id.delay(query_obj.query_id, user_id) return api_response(True, APIMessages.JOB_SUBMIT, STATUS_CREATED, query_data)
def get(self, session): dqi_history_parser = reqparse.RequestParser() dqi_history_parser.add_argument( 'project_id', help=APIMessages.PARSER_MESSAGE.format('org_id'), required=True, type=int, location='args') dqi_history_parser.add_argument( "start_date", help=APIMessages.PARSER_MESSAGE.format('start_date'), required=False, type=str, location='args') dqi_history_parser.add_argument( "end_date", help=APIMessages.PARSER_MESSAGE.format('end_date'), required=False, type=str, location='args') dqi_history_data = dqi_history_parser.parse_args() # check if project Id exists check_valid_project = Project.query.filter_by( project_id=dqi_history_data['project_id'], is_deleted=False).first() if not check_valid_project: raise ResourceNotAvailableException("Project") # checking if user is authorized to make this call check_permission(session.user, list_of_permissions=PROJECT_DQI_HISTORY_GET, org_id=check_valid_project.org_id, project_id=dqi_history_data['project_id']) # Check if both start and end date are passed instead either of them if (dqi_history_data['start_date'] and not dqi_history_data['end_date']) or \ (not dqi_history_data['start_date'] and dqi_history_data['end_date']): raise GenericBadRequestException(APIMessages.START_END_DATE) try: # check if user passed dates in yyyy-mm-dd format start_date, end_date = "", "" if dqi_history_data['start_date'] and dqi_history_data['end_date']: start_date = dt.strptime( dqi_history_data['start_date'] + " 00:00:00", "%Y-%m-%d %H:%M:%S") end_date = dt.strptime( dqi_history_data['end_date'] + " 23:59:59", "%Y-%m-%d %H:%M:%S") except ValueError: raise GenericBadRequestException(APIMessages.DATE_FORMAT) # calling get_project_dqi_history to get day wise data daily_dqi = get_project_dqi_history(dqi_history_data['project_id'], start_date=start_date, end_date=end_date) if not start_date and not end_date: # If start and end date are not given, take current month range current_day = dt.today() current_month_first_day = date.today().replace(day=1) start_date = current_month_first_day.strftime("%Y-%m-%d") end_date = current_day.strftime("%Y-%m-%d") dqi_response = OrderedDict() dqi_response['project_id'] = dqi_history_data['project_id'] dqi_response['project_name'] = check_valid_project.project_name dqi_response['dqi_history'] = daily_dqi dqi_response['start_date'] = str(start_date) dqi_response['end_date'] = str(end_date) return api_response(True, APIMessages.SUCCESS, STATUS_OK, dqi_response)
def get(self, session): """ To get active projects,users and jobs for a particular org id. Returns: Standard API Response with message, data(count of active projects, users and jobs) and http status code. """ get_org_parser = reqparse.RequestParser() get_org_parser.add_argument('org_id', required=True, type=int, location='args') get_org_parser.add_argument('start_time', required=False, type=str, location='args') get_org_parser.add_argument('end_time', required=False, type=str, location='args') org_detail = get_org_parser.parse_args() result_dic = {} org_obj = Organization.query.filter_by( org_id=org_detail["org_id"]).first() if not org_obj: raise ResourceNotAvailableException("org_id") check_permission(user_object=session.user, list_of_permissions=DASH_BOARD_STATUS_GET, org_id=org_detail["org_id"]) result_dic["org_id"] = org_obj.org_id result_dic["org_name"] = org_obj.org_name project_obj = Project.query.filter_by( org_id=org_detail["org_id"]).all() list_project_id = [ each_user_grp.project_id for each_user_grp in project_obj ] active_projects = len(project_obj) result_dic["active_projects"] = active_projects user_project_role_object = UserProjectRole.query.filter( UserProjectRole.org_id == org_detail['org_id']).distinct( UserProjectRole.user_id).all() user_org_role_object = UserOrgRole.query.filter( UserOrgRole.org_id == org_detail['org_id']).distinct( UserOrgRole.user_id).all() list_user_id_in_user_project_role_object = [ each_user_grp.user_id for each_user_grp in user_project_role_object ] list_user_id_in_user_org_role_object = [ each_user_grp.user_id for each_user_grp in user_org_role_object ] user_id_list = [ list_user_id_in_user_project_role_object, list_user_id_in_user_org_role_object ] list_user_id = set().union(*user_id_list) result_dic["active_users"] = len(list_user_id) all_project_test_suite_id_list = [] for project_id in list_project_id: test_suite_object = TestSuite.query.filter_by( project_id=project_id).all() list_test_suite_id = [ each_user_grp.test_suite_id for each_user_grp in test_suite_object ] all_project_test_suite_id_list.extend(list_test_suite_id) if (org_detail["start_time"] and org_detail["end_time"]): datetime_object_start = datetime.strptime(org_detail["start_time"], "%Y-%m-%d") datetime_object_end = datetime.strptime(org_detail["end_time"], "%Y-%m-%d") all_jobs = Job.query.filter( Job.test_suite_id.in_(all_project_test_suite_id_list), Job.modified_at >= datetime_object_start, Job.modified_at < datetime_object_end).all() result_dic["active_jobs"] = len(all_jobs) result_dic["start_time"] = str(datetime_object_start) result_dic["end_time"] = str(datetime_object_end) else: current_day = date.today() currentday = datetime.strptime(str(current_day), "%Y-%m-%d") current_month_first_day = date.today().replace(day=1) datetime_object_start = datetime.strptime( str(current_month_first_day), "%Y-%m-%d") end_date_obj = datetime.now() + timedelta(days=1) all_jobs = Job.query.filter( Job.test_suite_id.in_(all_project_test_suite_id_list), Job.modified_at >= datetime_object_start, Job.modified_at < end_date_obj).all() result_dic["active_jobs"] = len(all_jobs) result_dic["start_time"] = str(datetime_object_start) result_dic["end_time"] = str(currentday) return api_response(True, APIMessages.DATA_LOADED, STATUS_CREATED, result_dic)
def get(self, session): project_dql_parser = reqparse.RequestParser() project_dql_parser.add_argument( 'project_id', help=APIMessages.PARSER_MESSAGE.format('project_id'), required=True, type=int, location='args') project_dql_parser.add_argument( "start_date", help=APIMessages.PARSER_MESSAGE.format('start_date'), required=False, type=str, location='args') project_dql_parser.add_argument( "end_date", help=APIMessages.PARSER_MESSAGE.format('end_date'), required=False, type=str, location='args') project_dql_args = project_dql_parser.parse_args() # check if project Id exists check_valid_project = Project.query.filter_by( project_id=project_dql_args['project_id'], is_deleted=False).first() if not check_valid_project: raise ResourceNotAvailableException("Project") # checking if user is authorized to make this call check_permission(session.user, list_of_permissions=PROJECT_DQI_GET, org_id=check_valid_project.org_id, project_id=project_dql_args['project_id']) # Check if both start and end date are passed instead either of them if (project_dql_args['start_date'] and not project_dql_args['end_date']) or \ (not project_dql_args['start_date'] and project_dql_args['end_date']): raise GenericBadRequestException(APIMessages.START_END_DATE) try: # check if user passed dates in yyyy-mm-dd format start_date, end_date = "", "" if project_dql_args['start_date'] and project_dql_args['end_date']: start_date = dt.strptime( project_dql_args['start_date'] + " 00:00:00", "%Y-%m-%d %H:%M:%S") end_date = dt.strptime( project_dql_args['end_date'] + " 23:59:59", "%Y-%m-%d %H:%M:%S") except ValueError: raise GenericBadRequestException(APIMessages.DATE_FORMAT) dqi_name_casting = OrderedDict([ (TestTypeDisplay.COMPLETENESS, TestClass.COUNT_CHECK), (TestTypeDisplay.NULLS, TestClass.NULL_CHECK), (TestTypeDisplay.DUPLICATES, TestClass.DUPLICATE_CHECK), (TestTypeDisplay.CONSISTENCY, TestClass.DDL_CHECK), (TestTypeDisplay.CORRECTNESS, TestClass.DATA_VALIDATION) ]) list_of_project_dqi, project_dqi_average, starting_date, \ ending_date = get_project_dqi( project_dql_args['project_id'], start_date, end_date) dqi_list = list() for each_display_class in dqi_name_casting.keys(): if each_display_class in list_of_project_dqi.keys(): dqi_dict = dict() dqi_dict['name'] = each_display_class dqi_dict['value'] = list_of_project_dqi[each_display_class] dqi_list.append(dqi_dict) project_dql_data = dict() project_dql_data['project_name'] = check_valid_project.project_name project_dql_data['project_id'] = check_valid_project.project_id project_dql_data['project_dqi_percentage'] = project_dqi_average project_dql_data['project_dqi_detail'] = dqi_list project_dql_data['start_date'] = str(starting_date) project_dql_data['end_date'] = str(ending_date) return api_response(True, APIMessages.SUCCESS, STATUS_OK, project_dql_data)
def get(self, session): """ Method to fetch all connections for the given project_id. or particular connection for the db id Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message, data(returns dbdetails for the user passed id) and http status code. """ get_db_detail_parser = reqparse.RequestParser() get_db_detail_parser.add_argument('project_id', required=False, type=int, location='args') get_db_detail_parser.add_argument('db_connection_id', required=False, type=int, location='args') database_id = get_db_detail_parser.parse_args() db_connection_id = database_id.get("db_connection_id") if db_connection_id: db_obj = DbConnection.query.filter( DbConnection.db_connection_id == db_connection_id, DbConnection.is_deleted == False).first() if not db_obj: return api_response( False, APIMessages.DBID_NOT_IN_DB.format(db_connection_id), STATUS_BAD_REQUEST) project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter( Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter( Project.project_id == db_obj.project_id, Project.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_DB_ID, STATUS_BAD_REQUEST) check_permission(session.user, DB_DETAILS_GET, project_id_org_id[0], project_id_org_id[1]) return api_response( True, APIMessages.DATA_LOADED, STATUS_CREATED, { 'project_id': db_obj.project_id, 'db_connection_name': db_obj.db_connection_name, 'db_connection_id': db_obj.db_connection_id, 'db_type': SupportedDBType().get_db_name_by_id( db_obj.db_type), 'db_type_id': db_obj.db_type, "db_name": db_obj.db_name, 'db_hostname': db_obj.db_hostname, 'db_username': db_obj.db_username, }) dbproject_id = get_db_detail_parser.parse_args() project_id = dbproject_id.get("project_id") if project_id: project_obj = DbConnection.query.filter( DbConnection.project_id == project_id, DbConnection.is_deleted == False).first() project_name_obj = Project.query.filter_by( project_id=project_id).first() if not project_name_obj: return api_response(False, APIMessages.PROJECT_NOT_EXIST, STATUS_BAD_REQUEST) check_permission(session.user, DB_DETAILS_GET, project_name_obj.org_id, project_id) def to_json(projectid): return { 'project_id': projectid.project_id, 'project_name': project_name_obj.project_name, 'db_connection_name': projectid.db_connection_name, 'db_connection_id': projectid.db_connection_id, 'db_type': SupportedDBType().get_db_name_by_id(projectid.db_type), 'db_type_id': projectid.db_type, 'db_name': projectid.db_name, 'db_hostname': projectid.db_hostname, 'db_username': projectid.db_username } db_detail_dic = {} db_list = DbConnection.query.filter_by( project_id=project_id).order_by(DbConnection.created_at).all() db_connection_list = [ each_db for each_db in db_list if each_db.is_deleted == False ] db_detail_dic["db_details"] = list( map(lambda db_connection_id: to_json(db_connection_id), db_connection_list)) return api_response(True, APIMessages.DATA_LOADED, STATUS_CREATED, db_detail_dic) else: return api_response(False, APIMessages.PASS_DBID_or_PROJECTID, STATUS_BAD_REQUEST)
def put(self, session): """ To update the test suite in the database for the user provided test case id. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that test suite updated successfully) and http status code. """ put_testcase_parser = reqparse.RequestParser(bundle_errors=True) put_testcase_parser.add_argument('test_suite_id', required=True, type=int, location='json') put_testcase_parser.add_argument('test_case_detail', required=True, type=list, location='json') dict_test_case_details = put_testcase_parser.parse_args() test_case_detail = dict_test_case_details["test_case_detail"] test_suite_obj = TestSuite.query.filter_by(test_suite_id=int( dict_test_case_details['test_suite_id'])).first() if not test_suite_obj: return api_response( False, APIMessages.TEST_CASE_NOT_IN_DB.format( dict_test_case_details['test_suite_id']), STATUS_BAD_REQUEST) project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter( Project.is_deleted == False).join( TestSuite, Project.project_id == TestSuite.project_id).filter( TestSuite.test_suite_id == dict_test_case_details['test_suite_id'], TestSuite.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_TEST_CASE, STATUS_BAD_REQUEST) check_permission(session.user, TEST_SUITE_PUT, project_id_org_id[0], project_id_org_id[1]) #check permission case_list = [] flag = False for each_test_case in test_case_detail: keys = [] for key in each_test_case: keys.append(key) if "test_case_id" in keys: test_case_id = each_test_case["test_case_id"] test_case_obj = TestCase.query.filter_by( test_case_id=test_case_id, is_deleted=False).first() if not test_case_obj: flag = True case_list.append(test_case_id) if flag == True: return api_response( False, APIMessages.TEST_CASE_NOT_IN_DB.format(case_list), STATUS_BAD_REQUEST) else: test_case_id = each_test_case["test_case_id"] del each_test_case["test_case_id"] testcasedetail = copy.deepcopy( test_case_obj.test_case_detail) if "source_db_connection_id" in keys: src_db_id = each_test_case["source_db_connection_id"] del each_test_case["source_db_connection_id"] if "target_db_connection_id" in keys: target_db_id = each_test_case[ "target_db_connection_id"] del each_test_case["target_db_connection_id"] for key, value in dict(each_test_case).items(): if type(value) == int: each_test_case[key] = value else: each_test_case[key] = value.strip() if "source_db_connection_id" in keys: testcasedetail["src_db_id"] = src_db_id if "target_db_connection_id" in keys: testcasedetail["target_db_id"] = target_db_id if "test_class" in keys: if SupportedTestClass(). \ get_test_class_id_by_name \ (each_test_case["test_class"]) is None: return api_response( success=False, message=APIMessages.TEST_CLASS_NAME, http_status_code=STATUS_BAD_REQUEST, data={}) test_case_obj.test_case_class = SupportedTestClass(). \ get_test_class_id_by_name \ (each_test_case["test_class"]) if "test_description" in keys: testcasedetail["test_desc"] = \ each_test_case["test_description"] if "src_table" in keys: table = testcasedetail["table"] for key in table: target_table = table[key] table[each_test_case["src_table"]] = key del table[key] table[each_test_case["src_table"]] = target_table if "target_table" in keys: table = testcasedetail["table"] for key in table: table[key] = each_test_case["target_table"] if "src_query" in keys: queries = testcasedetail["query"] queries["sourceqry"] = each_test_case["src_query"] if "target_query" in keys: queries = testcasedetail["query"] queries["targetqry"] = each_test_case["target_query"] if "column" in keys: column = testcasedetail["column"] testcasedetail["column"] = column if each_test_case["column"] == "": column = {} testcasedetail["column"] = column elif ";" and ":" in each_test_case["column"]: column = {} user_columns = each_test_case["column"].split(";") for columnpair in user_columns: if ":" in columnpair: singlecolumn = columnpair.split(":") column[singlecolumn[0]] = \ singlecolumn[1] else: column[columnpair] = columnpair testcasedetail["column"] = column elif ";" in each_test_case["column"]: column = {} columns = each_test_case["column"].split(";") for singlecolumn in columns: column[singlecolumn] = singlecolumn testcasedetail["column"] = column else: column = {} column[each_test_case["column"]] = \ each_test_case["column"] testcasedetail["column"] = column if "is_deleted" in keys: if each_test_case['is_deleted'] == 1: test_case_obj.is_deleted = True test_case_obj.test_case_detail = testcasedetail test_case_obj.save_to_db() else: # if not "test_case_id" in keys: # consider it as a new test case and add to db temp_test_case = {} test_case_detail = {} if "source_db_connection_id" in keys: src_db_id = each_test_case["source_db_connection_id"] del each_test_case["source_db_connection_id"] if "target_db_connection_id" in keys: target_db_id = each_test_case["target_db_connection_id"] del each_test_case["target_db_connection_id"] for key, value in dict(each_test_case).items(): if type(value) == int: each_test_case[key] = value else: each_test_case[key] = value.strip() if "source_db_connection_id" in keys: test_case_detail["src_db_id"] = src_db_id if "target_db_connection_id" in keys: test_case_detail["target_db_id"] = target_db_id if "test_class" in keys: if SupportedTestClass(). \ get_test_class_id_by_name \ (each_test_case["test_class"]) is None: return api_response( success=False, message=APIMessages.TEST_CLASS_NAME, http_status_code=STATUS_BAD_REQUEST, data={}) temp_test_case['test_case_class'] = SupportedTestClass(). \ get_test_class_id_by_name \ (each_test_case["test_class"]) if "test_description" in keys: test_case_detail["test_desc"] = \ each_test_case["test_description"] table = {} if "src_table" in keys: src_table = each_test_case["src_table"] else: src_table = "" if "target_table" in keys: target_table = each_test_case["target_table"] table[src_table] = target_table test_case_detail['table'] = table query = {} if "src_query" in keys: src_query = each_test_case["src_query"] query['sourceqry'] = src_query if "target_query" in keys: target_query = each_test_case["target_query"] query['targetqry'] = target_query test_case_detail['query'] = query if "column" in keys: column = each_test_case["column"] test_case_detail["column"] = column if each_test_case["column"] == "": column = {} test_case_detail["column"] = column elif ";" and ":" in each_test_case["column"]: column = {} user_columns = each_test_case["column"].split(";") for columnpair in user_columns: if ":" in columnpair: singlecolumn = columnpair.split(":") column[singlecolumn[0]] = \ singlecolumn[1] else: column[columnpair] = columnpair test_case_detail["column"] = column elif ";" in each_test_case["column"]: column = {} columns = each_test_case["column"].split(";") for singlecolumn in columns: column[singlecolumn] = singlecolumn test_case_detail["column"] = column else: column = {} column[each_test_case["column"]] = \ each_test_case["column"] test_case_detail["column"] = column temp_test_case['test_case_detail'] = test_case_detail if "is_deleted" in keys: temp_test_case['is_deleted'] = each_test_case['is_deleted'] temp_case = TestCase( test_suite_id=dict_test_case_details['test_suite_id'], owner_id=session.user.user_id, test_case_class=temp_test_case['test_case_class'], test_case_detail=test_case_detail) temp_case.save_to_db() return api_response(True, APIMessages.TEST_SUITE_UPDATED, STATUS_CREATED)
def put(self, session): """ Method to Update database details into the DB based on the db id. provided by the user. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message db details uploaded successfully), data and http status code. """ put_db_detail_parser = reqparse.RequestParser(bundle_errors=True) put_db_detail_parser.add_argument('db_connection_id', required=True, type=int) put_db_detail_parser.add_argument('db_connection_name', type=str) put_db_detail_parser.add_argument('db_type', type=str) put_db_detail_parser.add_argument('db_name', type=str) put_db_detail_parser.add_argument('db_hostname', type=str) put_db_detail_parser.add_argument('db_username', type=str) put_db_detail_parser.add_argument('db_password', type=str) db_detail = put_db_detail_parser.parse_args() db_details = put_db_detail_parser.parse_args() db_connection_id = db_detail["db_connection_id"] # Remove keys which contain None values in db_details dictionary del db_detail["db_connection_id"] for key, value in dict(db_detail).items(): if value == None: del db_detail[key] for key, value in dict(db_detail).items(): db_detail[key] = value.strip() if not db_connection_id: return api_response(False, APIMessages.ABSENCE_OF_DBID, STATUS_BAD_REQUEST) db_obj = DbConnection.query.filter( DbConnection.db_connection_id == db_connection_id, DbConnection.is_deleted == False).first() if not db_obj: return api_response( False, APIMessages.DBID_NOT_IN_DB.format(db_connection_id), STATUS_BAD_REQUEST) project_id = db_obj.project_id project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter( Project.project_id == db_obj.project_id, Project.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_DB_ID, STATUS_BAD_REQUEST) check_permission(session.user, DB_DETAILS_PUT, project_id_org_id[0], project_id_org_id[1]) # Updating values present in database with user given values data_base_dict = db_obj.__dict__ data_base_dict.update(db_detail) # check passed db type name is valid or not if db_details["db_type"] != None: if SupportedDBType().get_db_id_by_name( db_detail['db_type']) is None: return api_response(success=False, message=APIMessages.DB_TYPE_NAME, http_status_code=STATUS_BAD_REQUEST, data={}) # check whether combination of db_type,db_name,db_username, # db_hostname,project_id is already present in db or not if db_details["db_type"] != None: data_base_dict['db_type'] = SupportedDBType().get_db_id_by_name( data_base_dict['db_type']) db_obj = DbConnection.query.filter( DbConnection.db_connection_id != db_connection_id, DbConnection.db_type == data_base_dict['db_type'], DbConnection.db_name == data_base_dict['db_name'], DbConnection.db_username == data_base_dict['db_username'], DbConnection.db_hostname.ilike(data_base_dict['db_hostname']), DbConnection.project_id == data_base_dict['project_id'], DbConnection.is_deleted == False).all() if db_obj != []: return api_response(False, APIMessages.DB_DETAILS_ALREADY_PRESENT, STATUS_BAD_REQUEST) else: # Validating maximum characters if db_details['db_connection_name'] != None: if len(db_details['db_connection_name']) > 100: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("100")) if db_details['db_name'] != None: if len(db_detail['db_name']) > 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) if db_details['db_hostname'] != None: if len(db_detail['db_hostname']) > 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) if db_details['db_username'] != None: if len(db_detail['db_username']) > 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) if db_details['db_password'] != None: if len(db_detail['db_password']) > 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) # Check Db connection name already exist in db or not if db_details["db_connection_name"] != None: db_obj = DbConnection.query.filter( DbConnection.db_connection_id != db_connection_id, DbConnection.db_connection_name == db_detail["db_connection_name"], DbConnection.project_id == project_id, DbConnection.is_deleted == False).first() if db_obj: return api_response( False, APIMessages.DB_CONNECTION_NAME_ALREADY_PRESENT, STATUS_BAD_REQUEST) # Checking spaces in database name,username and hostname if db_details["db_username"] != None: spacecount_dbusername = db_detail["db_username"].find(" ") if spacecount_dbusername > -1: return api_response(False, APIMessages.NO_SPACES, STATUS_BAD_REQUEST) if db_details["db_hostname"] != None: spacecount_dbhostname = db_detail["db_hostname"].find(" ") if spacecount_dbhostname > -1: return api_response(False, APIMessages.NO_SPACES, STATUS_BAD_REQUEST) if db_details["db_name"] != None: spacecount_dbname = db_detail["db_name"].find(" ") if spacecount_dbname > -1: return api_response(False, APIMessages.NO_SPACES, STATUS_BAD_REQUEST) db_obj = DbConnection.query.filter( DbConnection.db_connection_id == db_connection_id, DbConnection.is_deleted == False).first() for key, value in db_detail.items(): if key == 'db_password': if value == "": return APIMessages.PASSWORD_CANNOT_EMPTY db_password = encrypt(value) db_obj.db_encrypted_password = db_password elif key == 'db_connection_name': if value == "": now = datetime.now() date_time_now = now.strftime("%d-%m-%Y %H:%M:%S") value = APIMessages.DEFAULT_DB_CONNECTION_PREFIX + date_time_now db_obj.db_connection_name = value db_obj.save_to_db() elif key == 'db_type': db_obj.db_type = SupportedDBType(). \ get_db_id_by_name(value) elif key == 'db_name': if value == "": return APIMessages.DB_NAME_CANNOT_EMPTY db_obj.db_name = value elif key == 'db_hostname': if value == "": return APIMessages.HOSTNAME_CANNOT_EMPTY db_obj.db_hostname = value elif key == 'db_username': if value == "": return APIMessages.USERNAME_CANNOT_EMPTY db_obj.db_username = value db_obj.save_to_db() return api_response( True, APIMessages.DB_DETAILS_UPDATED.format(db_connection_id), STATUS_CREATED)
def post(self, session): """ Method will add a suite to database Args: session(Object): contains User_id. Returns: Add suite to Database """ parser = reqparse.RequestParser() parser.add_argument('sheet_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str) parser.add_argument('case_id_list', help=APIMessages.PARSER_MESSAGE, required=True, type=args_as_list, default=[]) parser.add_argument('suite_name', help=APIMessages.PARSER_MESSAGE, required=True, type=str) parser.add_argument('upload_and_execute', help=APIMessages.PARSER_MESSAGE, required=True) parser.add_argument('project_id', help=APIMessages.PARSER_MESSAGE, required=True) test_suite_data = parser.parse_args() current_user = session.user_id file = request.files['inputFile'] user_obj = User.query.filter_by(user_id=current_user).first() project_obj = Project.query.filter_by( project_id=test_suite_data['project_id'], is_deleted=False).first() # check_permission check_permission(user_obj, list_of_permissions=TEST_SUITE_POST, org_id=project_obj.org_id, project_id=project_obj.project_id) # Check Test Suite name already exist in db or not temp_connection = TestSuite.query.filter( TestSuite.test_suite_name == test_suite_data["suite_name"], TestSuite.project_id == test_suite_data["project_id"]).first() if test_suite_data['suite_name'].strip() == '': return api_response(False, APIMessages.TEST_SUITE_NAME_CANNOT_BE_BLANK, STATUS_BAD_REQUEST) if len(test_suite_data['suite_name']) >= 50: raise IllegalArgumentException( APIMessages.INVALID_LENGTH.format("50")) if temp_connection: return api_response(False, APIMessages.TEST_SUITE_NAME_ALREADY_PRESENT, STATUS_BAD_REQUEST) suite_result = save_file_to_db(current_user, test_suite_data['project_id'], test_suite_data, file) if int(test_suite_data['upload_and_execute']) == 1: test_suite_obj = TestSuite.query.filter_by(test_suite_id=int( suite_result['Suite'].test_suite_id)).first() project_obj = Project.query.filter_by( project_id=test_suite_obj.project_id).first() check_permission(user_obj, list_of_permissions=TEST_SUITE_POST_EXECUTE, org_id=project_obj.org_id, project_id=test_suite_obj.project_id) create_job(current_user, test_suite_obj, False) return api_response(True, APIMessages.ADD_DATA, STATUS_CREATED)
def delete(self, session): """ To delete the data base for the user provided data base id. Args: session (object):By using this object we can get the user_id. Returns: Standard API Response with message(returns message saying that Data Base Deleted Successfully) and http status code. """ delete_db_detail_parser = reqparse.RequestParser() delete_db_detail_parser.add_argument('db_connection_id', required=True, type=int, location='args') delete_db_detail_parser.add_argument('verify_delete', required=False, type=str, location='args', default="false") deletedata = delete_db_detail_parser.parse_args() data_base_id = deletedata.get("db_connection_id") if not data_base_id: return api_response(False, APIMessages.PASS_DB_ID, STATUS_BAD_REQUEST) del_obj = DbConnection.query.filter( DbConnection.db_connection_id == data_base_id, DbConnection.is_deleted == False).first() if not del_obj: return api_response( False, APIMessages.DBID_NOT_IN_DB.format(data_base_id), STATUS_BAD_REQUEST) project_id_org_id = db.session.query( Organization.org_id, Project.project_id).filter(Organization.is_deleted == False).join( Project, Organization.org_id == Project.org_id).filter( Project.project_id == del_obj.project_id, Project.is_deleted == False).first() if project_id_org_id == () or project_id_org_id == None: return api_response(False, APIMessages.NO_DB_ID, STATUS_BAD_REQUEST) check_permission(session.user, DB_DETAILS_DELETE, project_id_org_id[0], project_id_org_id[1]) # check whether passed db conection id is associated with any testcases data_base_ids = db.session.query( TestCase.test_case_detail["src_db_id"], TestCase.test_case_detail["target_db_id"]).filter( TestCase.is_deleted == False).all() idset = set() for tupleid in data_base_ids: for id in tupleid: idset.add(id) if data_base_id in idset: return api_response(False, APIMessages.DELETE_DB_WARNING, STATUS_CONFLICT) if str(deletedata["verify_delete"]).lower() == "true": del_obj.is_deleted = True del_obj.save_to_db() return api_response(True, APIMessages.DB_DELETED.format(data_base_id), STATUS_CREATED) else: return api_response( True, APIMessages.DELETE_DB_VERIFY_DELETE.format(data_base_id), STATUS_OK)
def get(self, session): """ GET call to retrieve UserProjectRole and UserOrgRole records. Args: session (object): User Session Returns: Standard API Response with HTTP status code """ # TODO: Need to reduce DB hit parser = reqparse.RequestParser() parser.add_argument('org_id', help=APIMessages.PARSER_MESSAGE, required=True, type=int, location='args') parser.add_argument('user_id', help=APIMessages.PARSER_MESSAGE, required=False, type=int, location='args') parser.add_argument('email_id', help=APIMessages.PARSER_MESSAGE, required=False, type=str, location='args') get_role_api_parser = parser.parse_args() result_dict = {} # Checking if User Id or Email Id is mandatorily passed if not get_role_api_parser['user_id'] and \ not get_role_api_parser['email_id']: return api_response(False, APIMessages.EMAIL_USER, STATUS_BAD_REQUEST) if get_role_api_parser['user_id'] and get_role_api_parser['email_id']: raise GenericBadRequestException(APIMessages.ONLY_USER_OR_EMAIL) # checking if User Id is valid valid_org, valid_project, valid_user, valid_role = None, None, None, None if get_role_api_parser['user_id']: valid_org, valid_project, valid_user, valid_role = check_valid_id_passed_by_user( org_id=get_role_api_parser['org_id'], user_id=get_role_api_parser['user_id']) check_permission(user_object=session.user, list_of_permissions=USER_ROLE_API_GET, org_id=get_role_api_parser["org_id"]) # Get user Id based on email Id passed if get_role_api_parser['email_id'] and \ not get_role_api_parser['user_id']: valid_org, valid_project, valid_user, valid_role = check_valid_id_passed_by_user( org_id=get_role_api_parser['org_id']) valid_user = User.query.filter( User.email.ilike(get_role_api_parser['email_id']), User.is_deleted == False).first() if not valid_user: return api_response(True, APIMessages.NO_ROLES, STATUS_OK) if get_role_api_parser['org_id'] and valid_user.user_id: # Get Project Role list project_role_list = list() temp_dict = {} user_project_roles = UserProjectRole.query.filter_by( org_id=get_role_api_parser['org_id'], user_id=valid_user.user_id).all() for each_project_role in user_project_roles: if each_project_role.project_id not in temp_dict.keys(): # Add a key with value as role_id temp_dict[each_project_role.project_id] = \ [each_project_role.role_id] else: temp_dict[each_project_role.project_id].append( each_project_role.role_id) for key, value in temp_dict.items(): project_role_list.append({ 'project_id': key, 'allowed_role_list': value }) result_dict['project_role_list'] = project_role_list # Get Org Roles user_org_roles = UserOrgRole.query.filter_by( org_id=get_role_api_parser['org_id'], user_id=valid_user.user_id).all() result_dict['is_org_user'] = True if user_org_roles else False result_dict['org_allowed_role_list'] = [] if user_org_roles: for each_user_org_role in user_org_roles: result_dict['org_allowed_role_list'].append( each_user_org_role.role_id) if not (result_dict['org_allowed_role_list'] or result_dict['project_role_list']): return api_response(True, APIMessages.NO_ROLES, STATUS_OK) result_dict['user_id'] = valid_user.user_id result_dict['email_id'] = valid_user.email result_dict['first_name'] = valid_user.first_name result_dict['last_name'] = valid_user.last_name result_dict['user_id'] = valid_user.user_id result_dict['org_id'] = get_role_api_parser['org_id'] return api_response(True, APIMessages.SUCCESS, STATUS_OK, result_dict)