def test_get_inprogress_event_history(client, jwt, app): from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event from namex.services import EventRecorder # add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() # create JWT & setup header with a Bearer Token using the JWT token = jwt.create_jwt(claims, token_header) headers = { 'Authorization': 'Bearer ' + token, 'content-type': 'application/json' } nr = RequestDAO() nr.nrNum = 'NR 0000002' nr.stateCd = State.INPROGRESS nr.requestId = 1460775 nr._source = 'NRO' name1 = NameDAO() name1.choice = 1 name1.name = 'TEST NAME ONE' nr.names = [name1] nr.save_to_db() EventRecorder.record(user, Event.PATCH, nr, {}) # get the resource (this is the test) rv = client.get('/api/v1/events/NR%200000002', headers=headers) assert rv.status_code == 200 assert b'"user_action": "Load NR"' in rv.data
def test_get_next_event_history(client, jwt, app): from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event from namex.services import EventRecorder # add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() # create JWT & setup header with a Bearer Token using the JWT headers = create_header(jwt, [User.EDITOR]) nr = create_base_nr() nr.stateCd = State.DRAFT nr.save_to_db() EventRecorder.record(user, Event.POST + ' [payment completed] CREATE', nr, nr.json()) nr.stateCd = State.INPROGRESS nr.save_to_db() EventRecorder.record(user, Event.GET, nr, {}) # get the resource (this is the test) rv = client.get('/api/v1/events/NR%200000002', headers=headers) assert rv.status_code == 200 assert b'"user_action": "Get Next NR"' in rv.data
def test_reopen_event_history(client, jwt, app): from namex.models import Request as RequestDAO, State, Name as NameDAO, User, Event from namex.services import EventRecorder # add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() headers = create_header(jwt, [User.EDITOR]) nr = RequestDAO() nr.nrNum = 'NR 0000002' nr.stateCd = State.REJECTED nr.requestId = 1460775 nr._source = 'NRO' name1 = NameDAO() name1.choice = 1 name1.name = 'TEST NAME ONE' nr.names = [name1] nr.save_to_db() EventRecorder.record(user, Event.PATCH, nr, {}) nr.stateCd = State.INPROGRESS EventRecorder.record(user, Event.PUT, nr, { "additional": "additional", "furnished": "N" }) # get the resource (this is the test) rv = client.get('/api/v1/events/NR%200000002', headers=headers) assert rv.status_code == 200 assert b'"user_action": "Re-Open"' in rv.data
def save_auto_approved_names(approved_number_records): from namex.models import Event as EventDAO, Request as RequestDAO, User as UserDAO, State num = 0 global num_records username = '******' usr = UserDAO(username, '', '', '', '') usr.id = 86 usr.save_to_db() while approved_number_records > num: nr_num_label = 'NR 00' num_records += 1 num += 1 nr_num = nr_num_label + str(num_records) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.APPROVED nr._source = 'NAMEREQUEST' event = EventDAO() event.action = EventAction.PUT.value event.userId = EventUserId.SERVICE_ACCOUNT.value event.stateCd = State.APPROVED event.eventDate = datetime.date.today() nr.events = [event] nr.save_to_db()
def test_get_staff_comment_event_history(client, jwt, app): from namex.models import Comment, Event, State, User from namex.services import EventRecorder from namex.utils.common import convert_to_ascii # add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() headers = create_header(jwt, [User.EDITOR]) nr = create_base_nr() nr.stateCd = State.DRAFT nr.save_to_db() EventRecorder.record(user, Event.POST + ' [payment completed] CREATE', nr, nr.json()) comment_instance = Comment() comment_instance.examinerId = user.id comment_instance.nrId = nr.id comment_instance.comment = convert_to_ascii('test staff comment') comment_instance.save_to_db() EventRecorder.record(user, Event.POST, nr, {'comment': 'test staff comment'}) # get the resource (this is the test) rv = client.get('/api/v1/events/NR%200000002', headers=headers) assert rv.status_code == 200 assert b'"user_action": "Staff Comment"' in rv.data assert b'"comment": "test staff comment"' in rv.data
def get(): if not (jwt.requires_roles(User.EDITOR) or jwt.requires_roles(User.APPROVER)): return jsonify({ "message": "Error: You do not have access to the Name Request queue." }), 403 try: user = User.find_by_jwtToken(g.jwt_oidc_token_info) current_app.logger.debug('find user') if not user: user = User.create_from_jwtToken(g.jwt_oidc_token_info) nr = RequestDAO.get_queued_oldest(user) except SQLAlchemyError as err: # TODO should put some span trace on the error message current_app.logger.error(err.with_traceback(None)) return jsonify({ 'message': 'An error occurred getting the next Name Request.' }), 500 except AttributeError as err: current_app.logger.error(err) return jsonify( {'message': 'There are no Name Requests to work on.'}), 404 return jsonify(nameRequest='{}'.format(nr)), 200
def test_get_queued_oldest_multirow(client, app): # add NR to database from namex.models import Request as RequestDAO, State, User nr_first = RequestDAO() nr_first.nrNum = 'NR 0000001' nr_first.stateCd = State.DRAFT nr_first.save_to_db() for i in range(2, 12): nr = RequestDAO() nr.nrNum = 'NR {0:07d}'.format(i) nr.stateCd = State.DRAFT nr.save_to_db() user = User(username='******', firstname='first', lastname='last', sub='idir/funcmunk', iss='keycloak') user.save_to_db() nr_oldest, new_req = RequestDAO.get_queued_oldest(user) # Tests #### assert nr_first.nrNum == nr_oldest.nrNum assert nr_oldest.json()
def add_test_user_to_db(): user = User(username='******', firstname='Test', lastname='User', sub='idir/name_request_service_account', iss='keycloak') user.save_to_db() return user
def test_get_service_account_user(session, client): """Assert service account user.""" # add a user for the comment user = User('nro_service_account', '', '', '8ca7d47a-024e-4c85-a367-57c9c93de1cd', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() service_account = User.get_service_account_user() assert service_account.username == user.username
def test_add_new_comment_to_nr(client, jwt, app): from namex.models import Request as RequestDAO, State, Name as NameDAO, Comment as CommentDAO, User, \ Event as EventDAO from sqlalchemy import desc #add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() nr = RequestDAO() nr.nrNum = 'NR 0000002' nr.stateCd = State.INPROGRESS nr.requestId = 1460775 nr._source = 'NRO' name1 = NameDAO() name1.choice = 1 name1.name = 'TEST NAME ONE' nr.names = [name1] nr.save_to_db() comment1 = CommentDAO() comment1.comment = 'This is the first Comment' comment1.nr_id = nr.id comment1.examinerId = nr.userId nr.comments = [comment1] nr.save_to_db() # create JWT & setup header with a Bearer Token using the JWT token = jwt.create_jwt(claims, token_header) headers = { 'Authorization': 'Bearer ' + token, 'content-type': 'application/json' } # get the resource so we have a template for the request: rv = client.get('/api/v1/requests/NR%200000002', headers=headers) assert rv.status_code == 200 # assert we're starting with just one name: data = json.loads(rv.data) assert len(data['comments']) == 1 new_comment = {"comment": "The 13th comment entered by the user."} rv = client.post('/api/v1/requests/NR%200000002/comments', data=json.dumps(new_comment), headers=headers) assert b'"comment": "The 13th comment entered by the user."' in rv.data assert 200 == rv.status_code event_results = EventDAO.query.filter_by(nrId=nr.id).order_by( EventDAO.eventDate.desc()).first_or_404() assert event_results.action == 'post' assert event_results.eventJson[0:11] == '{"comment":'
def test_fetch_nro_request_and_copy_to_namex_request_with_nr(app, session, nr_num, expected_nr_num): user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') user.save_to_db() nr = Request() nr.nrNum = nr_num nr.userId = user.id nr.save_to_db() nr = nro.fetch_nro_request_and_copy_to_namex_request(user, nr_number=12, name_request=nr) assert expected_nr_num == None if (expected_nr_num is None) else nr.nrNum
def test_get_queued_empty_queue(client, app): # SETUP ##### # add NR to database from namex.models import Request as RequestDAO, User from namex.exceptions import BusinessException user = User(username='******', firstname='first', lastname='last', sub='idir/funcmunk', iss='keycloak') user.save_to_db() with pytest.raises(BusinessException) as e_info: nr_oldest, new_req = RequestDAO.get_queued_oldest(user)
def test_event_create_nrl(client, jwt, app): #add a user for the comment user = User('test-user', '', '', '43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc', 'url') user.save_to_db() # create JWT & setup header with a Bearer Token using the JWT headers = create_header(jwt, [User.EDITOR]) nr = create_base_nr() before_record_date = datetime.utcnow() EventRecorder.record(user, Event.POST, nr, nr.json()) # get the resource (this is the test) rv = client.get('/api/v1/events/NR%200000002', headers=headers) assert rv.status_code == 200 assert rv.data response = json.loads(rv.data) assert response['transactions'] assert len(response['transactions']) == 1 assert response['transactions'][0]['additionalInfo'] == 'test' assert response['transactions'][0]['consent_dt'] == None assert response['transactions'][0]['consentFlag'] == None assert response['transactions'][0][ 'eventDate'] > before_record_date.isoformat() assert response['transactions'][0]['expirationDate'] == None assert response['transactions'][0]['names'] == [{ 'choice': 1, 'comment': None, 'conflict1': '', 'conflict1_num': '', 'conflict2': '', 'conflict2_num': '', 'conflict3': '', 'conflict3_num': '', 'consumptionDate': None, 'corpNum': None, 'decision_text': '', 'designation': None, 'id': 1, 'name': 'TEST NAME ONE', 'name_type_cd': None, 'state': 'NE' }] assert response['transactions'][0]['priorityCd'] == None assert response['transactions'][0]['requestTypeCd'] == 'CR' assert response['transactions'][0]['request_action_cd'] == 'NEW' assert response['transactions'][0]['stateCd'] == State.PENDING_PAYMENT assert response['transactions'][0]['user_action'] == 'Created NRL' assert response['transactions'][0]['user_name'] == 'test-user'
def helper_create_requests(row_data): user = User('automation', 'automation', 'automation', 'internal', 'localhost') user.save_to_db() for row in row_data: if row['nr_num']: nr = Request() nr.nrNum = row['nr_num'] nr.stateCd = row['state'] nr.userId = user.id nr.save_to_db()
def test_comment_where_no_nr(client, jwt, app): from namex.models import User #add a user for the comment user = User('test-user','','','43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc','https://sso-dev.pathfinder.gov.bc.ca/auth/realms/sbc') user.save_to_db() # create JWT & setup header with a Bearer Token using the JWT token = jwt.create_jwt(claims, token_header) headers = {'Authorization': 'Bearer ' + token, 'content-type': 'application/json'} new_comment = {"comment": "The 13th comment entered by the user."} rv = client.post('/api/v1/requests/NR%200000002/comments', data=json.dumps(new_comment), headers=headers) assert 404 == rv.status_code
def test_move_control_of_existing_request_from_nro_missing_nr(app, session): user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') user.save_to_db() nr = Request() nr.nrNum = 'NR 9999999' nr.stateCd = State.INPROGRESS nr.nroLastUpdate = EPOCH_DATETIME nr.userId = user.id nr.save_to_db() warnings = nro.move_control_of_request_from_nro(nr, user) assert warnings is not None
def helper_create_requests(row_data): user = User('automation', 'automation', 'automation', 'internal', 'localhost') user.save_to_db() for row in row_data: print('inserting nr:{}'.format(row['nr_num'])) if row['nr_num']: nr = Request() nr.nrNum = row['nr_num'] nr.stateCd = row['state'] nr.lastUpdate = row['last_update'] nr.userId = user.id nr.save_to_db()
def test_move_control_of_request_from_nro(app, session, nr_num, expected_nr_num): user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') user.save_to_db() nr = Request() nr.nrNum = nr_num nr.stateCd = State.INPROGRESS nr.nroLastUpdate = EPOCH_DATETIME nr.userId = user.id nr.save_to_db() warnings = nro.move_control_of_request_from_nro(nr, user) assert expected_nr_num == None if (expected_nr_num is None) else nr.nrNum assert warnings is None
def add_nr_header(new_nr, nr_header, nr_submitter, user): NR_STATE = { 'HISTORICAL': 'HISTORICAL', 'H': 'HOLD', 'COMPLETED': 'COMPLETED', 'D': 'DRAFT', 'C': 'CANCELLED', 'E': 'CONDITIONAL' } if nr_submitter: submitter = User.find_by_username(nr_submitter['submitter']) new_nr.userId = user.id new_nr.stateCd = State.DRAFT if nr_header[ 'state_type_cd'] is None else NR_STATE[nr_header['state_type_cd']] new_nr.nrNum = nr_header['nr_num'] new_nr.requestId = nr_header['request_id'] new_nr.previousRequestId = nr_header['previous_request_id'] new_nr.submitCount = nr_header['submit_count'] new_nr.requestTypeCd = nr_header['request_type_cd'] new_nr.expirationDate = nr_header['expiration_date'] new_nr.additionalInfo = nr_header['additional_info'] new_nr.natureBusinessInfo = nr_header['nature_business_info'] new_nr.xproJurisdiction = nr_header['xpro_jurisdiction'] new_nr.submittedDate = nr_submitter['submitted_date'] new_nr.submitter_userid = None if (submitter is None) else submitter.id new_nr.nroLastUpdate = nr_header['last_update'] if nr_header['priority_cd'] is 'PQ': new_nr.priorityCd = 'Y' else: new_nr.priorityCd = 'N'
def patch(nr, choice, *args, **kwargs): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 errors = names_schema.validate(json_data, partial=True) if errors: return jsonify(errors), 400 nrd, nrd_name, msg, code = NRNames.common(nr, choice) if not nrd: return msg, code user = User.find_by_jwtToken(g.jwt_oidc_token_info) if not check_ownership(nrd, user): return jsonify({ "message": "You must be the active editor and it must be INPROGRESS" }), 403 names_schema.load(json_data, instance=nrd_name, partial=True) nrd_name.save_to_db() return jsonify( {"message": "Patched {nr} - {json}".format(nr=nr, json=json_data)}), 200
def test_run_job(app, session, nro_connection, namex_feeder, test_name, feeder_data): # setup user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') helper_add_namex_feeder_rows(nro_connection, feeder_data) helper_create_requests(feeder_data) # Run Test processed = job(app, db, nro_connection, user, 100) # check expected rows processed by job assert processed == len(feeder_data) # check expected state of rows pending = 0 rows = nro_connection.cursor().execute("select * from NAMEX.NAMEX_FEEDER") for row in rows: if row[2] != 'C': pending += 1 assert pending == 0 # check for rows skipped due to errors expected_errors = reduce(mul, [x['error'] for x in feeder_data]) errors = 0 rows = nro_connection.cursor().execute("select * from NAMEX.NAMEX_FEEDER") for row in rows: if row[7] is not None: errors += 1 print('error', row[7]) assert errors == expected_errors
def test_add_nwpta(app, request, session, pns): # imports for just this test from namex.services.nro.request_utils import add_nwpta # SETUP # create an NR nr = Request() nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost') session.add(nr) session.commit() # Test add_nwpta(nr, pns) session.add(nr) session.commit() partners = nr.partnerNS.all() assert len(pns) == len(partners) for partner in partners: partner_found = False for p in pns: if p['partner_jurisdiction_type_cd'] == partner.partnerJurisdictionTypeCd: partner_found = True continue assert partner_found
def test_update_nro_request_state_to_approved(app): """ Code should not allow us to set state to anything except Draft """ con = nro.connection cursor = con.cursor() eid = _get_event_id(cursor) user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') fake_request = FakeRequest() fake_request.requestId = 884047 fake_request.stateCd = 'APPROVED' fake_request.activeUser = user _update_nro_request_state(cursor, fake_request, eid, {'is_changed__request_state': True}) cursor.execute( "select state_type_cd from request_state where request_id = {} and start_event_id = {}" .format(fake_request.requestId, eid)) resultset = cursor.fetchone() assert resultset is None
def test_add_nr_header_set_state(state_type_cd, nr_names, expected): from namex.services.nro.request_utils import add_names, add_nr_header # the correct state for a Request that is completed in NRO is determined by the Name states nr = Request() user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr_submitter = None nr_header = { 'priority_cd': 'N', 'state_type_cd': state_type_cd, 'nr_num': 'NR 0000001', 'request_id': 1, 'previous_request_id': None, 'submit_count': 0, 'request_type_cd': 'REQ', 'expiration_date': None, 'additional_info': None, 'nature_business_info': 'N/A', 'xpro_jurisdiction': None, 'submitted_date': EPOCH_DATETIME, 'last_update': EPOCH_DATETIME } add_nr_header(nr, nr_header, nr_submitter, user) add_names(nr, nr_names) assert nr.stateCd == expected
def test_add_names_with_changes(app, request, session, previous_names, test_names): # imports for just this test from namex.services.nro.request_utils import add_names # SETUP # create an NR nr = Request() nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost') if previous_names: add_names(nr, previous_names) session.add(nr) session.commit() # Test add_names(nr, test_names) session.add(nr) session.commit() names = nr.names.all() assert len(test_names) == len(names) for name in names: name_found = False decision_data_intact = False for tn in test_names: if tn['name'] == name.name: name_found = True continue assert name_found
def test_add_nr_header_with_priority(priority_cd, expected): from namex.services.nro.request_utils import add_nr_header nr = Request() user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr_submitter = None nr_header = { 'priority_cd': priority_cd, 'state_type_cd': 'H', 'nr_num': 'NR 0000001', 'request_id': 1, 'previous_request_id': None, 'submit_count': 0, 'request_type_cd': 'REQ', 'expiration_date': None, 'additional_info': None, 'nature_business_info': 'N/A', 'xpro_jurisdiction': None, 'submitted_date': EPOCH_DATETIME, 'last_update': EPOCH_DATETIME } add_nr_header(nr, nr_header, nr_submitter, user) assert nr.priorityCd == expected
def test_request_add_applicant_existing(app, request, session, applicant1, applicant2): # imports for just this test from namex.models import Applicant from namex.services.nro.request_utils import add_applicant # SETUP # create an NR and add an applicant nr = Request() nr.activeUser = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr.applicants.append(Applicant(**applicant1)) session.add(nr) session.commit() # Test # Call add_applicant and then assert the new NR applicant matches our data add_applicant(nr, applicant2) session.add(nr) session.commit() appl = nr.applicants.one_or_none() nra = dict_to_json_keys(applicant2) a = appl.as_dict() if a.get('partyId'): a.pop('partyId') # check entire dict assert nra == a
def initialize(_self): _self.validate_config(current_app) request_json = request.get_json() if nr_action: _self.nr_action = nr_action if nr_action is NameRequestPatchActions.CHECKOUT.value: # Make sure the NR isn't already checked out checked_out_by_different_user = nr_model.checkedOutBy is not None and nr_model.checkedOutBy != request_json.get('checkedOutBy', None) if checked_out_by_different_user: raise NameRequestIsInProgressError() # set the user id of the request to name_request_service_account service_account_user = User.find_by_username('name_request_service_account') nr_model.userId = service_account_user.id # The request payload will be empty when making this call, add them to the request _self.request_data = { # Doesn't have to be a UUID but this is easy and works for a pretty unique token 'checkedOutBy': str(uuid4()), 'checkedOutDt': datetime.now() } # Set the request data to the service _self.nr_service.request_data = self.request_data elif nr_action is NameRequestPatchActions.CHECKIN.value: # The request payload will be empty when making this call, add them to the request _self.request_data = { 'checkedOutBy': None, 'checkedOutDt': None } # Set the request data to the service _self.nr_service.request_data = self.request_data else: super().initialize()
def test_update_nro_add_new_name_choice(app): """ Ensure name can be changed, or removed. """ con = nro.connection cursor = con.cursor() eid = _get_event_id(cursor) user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') fake_request = FakeRequest() fake_name1 = FakeName() fake_name2 = FakeName() fake_name1.choice = 1 fake_name2.choice = 2 # Add a second name choice: fake_name1.name = "Fake name" fake_name2.name = 'Second fake name' names = NamesList() names.addNames([fake_name1, fake_name2]) fake_request.names = names fake_request.requestId = 884047 fake_request.stateCd = 'INPROGRESS' fake_request.activeUser = user change_flags = { 'is_changed__name1': False, 'is_changed__name2': True, 'is_changed__name3': False, } # Fail if our test data is not still valid: cursor.execute(""" select ni.name from name n, name_instance ni where ni.name_id = n.name_id and n.request_id = {} and ni.end_event_id is null """ .format(fake_request.requestId)) result = list(cursor.fetchall()) assert len(result) == 1 _update_nro_names(cursor, fake_request, eid, change_flags) cursor.execute(""" select ni.name from name n, name_instance ni where ni.name_id = n.name_id and n.request_id = {} and ni.end_event_id is null """ .format(fake_request.requestId)) result = list(cursor.fetchall()) assert result assert len(result) == 2 assert result[0][0] != 'Fake name'
def get_or_create_user_by_jwt(jwt_oidc_token): # GET existing or CREATE new user based on the JWT info try: user = User.find_by_jwtToken(jwt_oidc_token) current_app.logger.debug('finding user: {}'.format(jwt_oidc_token)) if not user: current_app.logger.debug( 'didnt find user, attempting to create new user from the JWT info:{}'.format(jwt_oidc_token)) user = User.create_from_jwtToken(jwt_oidc_token) return user except Exception as err: current_app.logger.error(err.with_traceback(None)) raise ServicesError('unable_to_get_or_create_user', '{"code": "unable_to_get_or_create_user",' '"description": "Unable to get or create user from the JWT, ABORT"}' )