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 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 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 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_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_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_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_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_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_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_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_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 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 test_move_control_of_request_from_nro_missing_nr(app, session): user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr = None warnings = nro.move_control_of_request_from_nro(nr, user) assert warnings is not None
def test_fetch_nro_request_and_copy_to_namex_request(app, session, nr_num, expected_nr_num): user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr = nro.fetch_nro_request_and_copy_to_namex_request(user, nr_number=nr_num) assert expected_nr_num == None if (expected_nr_num is None) else nr.nrNum
def test_user(session, client): """Start with a blank database.""" user1 = User(username = '******', firstname = 'thor', lastname = 'g', sub = 'abcdefg', iss='http://nowhere.localdomain') session.add(user1) session.commit() assert user1.id is not None
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_datapump_nr_requires_consent_flag(app, mocker, consent_flag, state_cd): # create minimal NR to send to NRO nr = Request() nr.nrNum = 'NR 0000001' nr.stateCd = state_cd nr.consentFlag = consent_flag nr.lastUpdate = datetime(1970, 1, 1, 00, 00, tzinfo=timezone('US/Pacific', )) # requires the username user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr.activeUser = user # add name(s) to the NR - max 3 for i in range(1, 4): name = Name() name.state = Name.APPROVED if i == 1 else Name.NOT_EXAMINED name.name = 'sample name {}'.format(i) name.choice = i name.decision_text = 'All good to go {}'.format(i) nr.names.append(name) # mock the oracle cursor oc = mocker.MagicMock() # make the real call nro_data_pump_update(nr, ora_cursor=oc, expires_days=60) oc.callfunc.assert_called_with( 'NRO_DATAPUMP_PKG.name_examination_func', # package.func_name str, [ 'NR 0000001', # p_nr_number 'A', # p_status '19700302', # p_expiry_date (length=8) 'Y', # p_consent_flag 'bob', # p_examiner_id (anything length <=7) 'A****All good to go 1', # p_choice1 None, # p_choice2 None, # p_choice3 None, # p_exam_comment '', # p_add_info - not used in proc anymore None, # p_confname1A None, # p_confname1B None, # p_confname1C None, # p_confname2A None, # p_confname2B None, # p_confname2C None, # p_confname3A None, # p_confname3B None ]) # p_confname3C
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_user_search_columns(session, client): """Start with a blank database.""" user1 = User(username = '******', firstname = 'kial', lastname = 'g', sub = 'abcdefg', iss='http://nowhere.localdomain') session.add(user1) session.commit() assert user1.searchColumns is not None assert user1.searchColumns == 'Status,LastModifiedBy,NameRequestNumber,Names,ApplicantFirstName,ApplicantLastName,NatureOfBusiness,ConsentRequired,Priority,ClientNotification,Submitted,LastUpdate,LastComment'
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_run_job(app, session, test_name, request_data, expected_row_count): # setup user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') helper_create_requests(request_data) # Run Test processed, success = job(user, max_rows=100, delay=1800) # check expected rows processed by job assert processed == expected_row_count
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_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_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 test_update_nro_nwpta_sk(app): """ Ensure the changed ab nwpta data is updated in nro """ con = nro.connection cursor = con.cursor() user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') #Set upo request cursor.execute("insert into request(request_id, nr_num) values(42, 'NR XXXXXXX')") #tds that it is valid cursor.execute("select nr_num from request where request_id = 42") (nr_num,) = cursor.fetchone() assert nr_num == 'NR XXXXXXX' eid = _get_event_id(cursor) # Setup Base AB record cursor.execute("""insert into partner_name_system (partner_name_system_id, request_id, start_event_id,PARTNER_NAME_TYPE_CD, PARTNER_JURISDICTION_TYPE_CD) values(partner_name_system_seq.nextval, 42, :event, 'CO', 'SK')""",event=eid) # test AB change_flags = { 'is_changed__nwpta_ab': False, 'is_changed__nwpta_sk': True, } fake_request = FakeRequestNwpta() fake_nwpta_sk = FakeNwpta_SK() nwpta = PartnerList() nwpta.addPartnerNS([fake_nwpta_sk]) fake_request.partnerNS = nwpta _update_nro_partner_name_system(cursor, fake_request, eid, change_flags) cursor.execute(""" select pns.* from partner_name_system pns where pns.partner_jurisdiction_type_cd = 'SK' and pns.request_id = {} and pns.partner_name_type_cd = 'AS' and pns.end_event_id is null""" .format(fake_request.requestId)) result = list(cursor.fetchall()) assert len(result) == 1 assert result[0][4] == 'AS' assert result[0][8] == 'ASSUMED COMPANY NAME-SK'
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_datapump(app, mocker, start_date, expected_date): # create minimal NR to send to NRO nr = Request() nr.nrNum = 'NR 0000001' nr.stateCd = State.REJECTED nr.consentFlag = 'N' nr.lastUpdate = start_date # requires the username user = User('idir/bob', 'bob', 'last', 'idir', 'localhost') nr.activeUser = user # add name(s) to the NR - max 3 for i in range(1, 4): name = Name() name.state = Name.REJECTED name.name = 'sample name {}'.format(i) name.choice = i name.decision_text = 'No Distinctive Term {}'.format(i) nr.names.append(name) # mock the oracle cursor oc = mocker.MagicMock() # make the real call nro_data_pump_update(nr, ora_cursor=oc, expires_days=56) oc.callfunc.assert_called_with( 'NRO_DATAPUMP_PKG.name_examination_func', # package.func_name str, [ 'NR 0000001', # p_nr_number 'R', # p_status expected_date.strftime('%Y%m%d'), # p_expiry_date (length=8) 'N', # p_consent_flag 'bob', # p_examiner_id (anything length <=7) 'R****No Distinctive Term 1', # p_choice1 'R****No Distinctive Term 2', # p_choice2 'R****No Distinctive Term 3', # p_choice3 None, # p_exam_comment '', # p_add_info - not used in proc anymore None, # p_confname1A None, # p_confname1B None, # p_confname1C None, # p_confname2A None, # p_confname2B None, # p_confname2C None, # p_confname3A None, # p_confname3B None ]) # p_confname3C
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