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_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_get_next_oldest(client, jwt, app): # add NR to database from namex.models import Request as RequestDAO, State nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.DRAFT nr._source = 'NRO' nr.save_to_db() for i in range(2, 12): nr = RequestDAO() nr.nrNum = 'NR {0:07d}'.format(i) nr.stateCd = State.DRAFT nr._source = 'NRO' 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} # The message expected to be returned json_msg = jsonify(nameRequest='NR 0000001') # get the resource (this is the test) rv = client.get('/api/v1/requests/queues/@me/oldest', headers=headers) assert b'"nameRequest": "NR 0000001"' in rv.data
def save_words_list_name(words_list, queue=False): from namex.models import Request as RequestDAO, State, Name as NameDAO num = 0 req = 1460775 for record in words_list: nr_num_label = 'NR 00000' num += 1 req += 1 nr_num = nr_num_label + str(num) nr = RequestDAO() nr.nrNum = nr_num if queue: nr.stateCd = State.DRAFT nr.expirationDate = datetime.date.today() + datetime.timedelta(days=1) else: nr.stateCd = State.APPROVED nr.requestId = req nr.requestTypeCd = EntityTypes.CORPORATION.value nr._source = 'NAMEREQUEST' name = NameDAO() name.choice = 1 name.name = record name.state = State.APPROVED name.corpNum = '0652480' nr.names = [name] nr.save_to_db()
def test_name_search_populated_by_name(): """Tests changing a name updates the nameSearch column.""" from namex.models import Name, Request as RequestDAO, State name = Name() name.choice = 1 name.name = 'TEST' name.state = 'NE' nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.DRAFT nr.names.append(name) nr.save_to_db() test = RequestDAO.find_by_id(nr.id) # sanity check names = test.names.all() assert len(names) == 1 assert names[0].name == 'TEST' # check nameSearch assert nr.nameSearch == '|1TEST1|' # alter name name.name = 'CHANGED' name.save_to_db() # check nameSearch assert nr.nameSearch == '|1CHANGED1|'
def create_nr(nr_num: str, request_state: str, names: list, names_state: list): now = datetime.utcnow() with freeze_time(now): name_request = Request() name_request.nrNum = nr_num name_request.stateCd = request_state name_request._source = 'NRO' name_request.expirationDate = add_years(now, 1) name_request.entity_type_cd = 'CR' # name_request.priorityCd = start_priority name_request.save_to_db() for index, name in enumerate(names): name_state = names_state[index] choice = index + 1 name_obj = Name() name_obj.nrId = name_request.id name_obj.name = name name_obj.state = name_state name_obj.choice = choice name_obj.name_type_cd = 'CO' name_obj.save_to_db() return name_request
def test_full_access_to_name_request(test_name, \ name_request_number, temp_request_number, user_email, user_phone, \ header_name_request_number, header_temp_request_number, header_user_email, header_user_phone, \ expected): """Assure that this contains the headers required to fully access an NR.""" from namex.utils.auth import full_access_to_name_request # setup nr = RequestDAO() nr.nrNum = name_request_number or temp_request_number nr.stateCd = State.DRAFT nr._source = ValidSources.NAMEREQUEST.value applicant = Applicant() applicant.phoneNumber = user_phone applicant.emailAddress = user_email nr.applicants.append(applicant) nr.save_to_db() builder = EnvironBuilder(method='POST', data={}, headers={ 'BCREG_NR': header_name_request_number, 'BCREG_NRL': header_temp_request_number, 'BCREG-User-Email': header_user_email, 'BCREG-User-Phone': header_user_phone }) env = builder.get_environ() req = Request(env) print(req) assert expected == full_access_to_name_request(req)
def build_draft(data=None, test_names=None, generate_id_seq=None): try: nr = RequestDAO() # Set defaults, if these exist in the provided data they will be overwritten nr.stateCd = State.DRAFT nr.requestId = 1460775 nr._source = 'NRO' if not data: data = {} # Map the data, if provided for key, value in data.items(): # Don't set list attrs, they have to be set separately to handle sequences if hasattr(nr, key) and not isinstance(data.get(key), list): nr.__setattr__(key, value) nr.names = [] for test_name in test_names: nr.names.append(build_name(test_name, generate_id_seq)) return nr except Exception as err: print(repr(err))
def build_rejected(data=None, test_names=None, generate_id_seq=None): """ :param data: :param test_names: :param generate_id_seq: :return: """ nr = RequestDAO() # Set defaults, if these exist in the provided data they will be overwritten nr.stateCd = State.REJECTED nr.requestId = 1460775 nr._source = 'NRO' if not data: data = {} # Map the data, if provided for key, value in data.items(): # Don't set list attrs, they have to be set separately to handle sequences if hasattr(nr, key) and not isinstance(data.get(key), list): nr.__setattr__(key, value) nr.names = [] for test_name in test_names: nr.names.append(build_name(test_name, generate_id_seq)) return nr
def furnish_request_message(request: Request, option: str): # pylint: disable=redefined-outer-name """Send notification info to the mail queue.""" current_app.logger.debug( 'Start of the furnishing of request for %s nrNum=%s', option, request.nrNum) payload = create_cloud_event_msg( msg_id=str(uuid.uuid4()), msg_type='bc.registry.names.request', source=f'/requests/{request.nrNum}', time=datetime.utcfromtimestamp( time.time()).replace(tzinfo=timezone.utc).isoformat(), identifier=request.nrNum, json_data_body={'request': { 'nrNum': request.nrNum, 'option': option }}) current_app.logger.debug('About to publish email for %s nrNum=%s', option, request.nrNum) publish_email_message(payload) if option == 'before-expiry': request.notifiedBeforeExpiry = True elif option == 'expired': request.notifiedExpiry = True request.stateCd = State.EXPIRED request.save_to_db()
def test_comment_where_no_user(client, jwt, app): from namex.models import Request as RequestDAO, State, Name as NameDAO, Comment as CommentDAO, User 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() # 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_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 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_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_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":'
async def test_update_payment_record( app, session, test_name, action_code, start_request_state, end_request_state, start_priority, end_priority, start_datetime, days_after_start_datetime, start_payment_state, end_payment_state, start_payment_date, end_payment_has_value, error): """Assert that the update_payment_record works as expected.""" from namex.models import Request, State, Payment from namex_pay.worker import update_payment_record print(test_name) now = datetime.utcnow() with freeze_time(now): # setup PAYMENT_TOKEN = 'dog' NR_NUMBER = 'NR B000001' name_request = Request() name_request.nrNum = NR_NUMBER name_request.stateCd = start_request_state name_request._source = 'NRO' name_request.expirationDate = start_datetime name_request.priorityCd = start_priority name_request.save_to_db() payment = Payment() payment.nrId = name_request.id payment._payment_token = PAYMENT_TOKEN payment._payment_status_code = start_payment_state payment.payment_action = action_code payment.furnished = False payment._payment_completion_date = start_payment_date payment.save_to_db() # run test if error: # expecting it to raise an error with pytest.raises(error): await update_payment_record(payment) else: # else it was processable if not (payment_final := await update_payment_record(payment)): payment_final = payment nr_final = Request.find_by_nr(NR_NUMBER) assert nr_final.stateCd == end_request_state assert nr_final.priorityCd == end_priority assert nr_final.expirationDate == ( start_datetime or now) + timedelta(days=days_after_start_datetime) assert eval( f'payment_final.payment_completion_date {end_payment_has_value} None' ) assert payment_final.payment_status_code == end_payment_state
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 create_nr(nr_num: str, state_cd: str, submitted: datetime, names: list) -> Request: """Create new NR.""" nr = Request() nr.nrNum = nr_num nr.stateCd = state_cd nr.submittedDate = submitted nr._source = 'NRO' for name in names: nr.names.append( create_name(name['name'], name['state'], name['choice'])) nr.save_to_db() return nr
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_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 test_get_expiry_days(client, test_name, days, action_cd, request_type): """ Test that get_expiry_date method returns a either 56 or 421 days """ mock_nr = RequestDAO() # Set defaults, if these exist in the provided data they will be overwritten mock_nr.stateCd = State.APPROVED mock_nr.request_action_cd = action_cd mock_nr.requestTypeCd = request_type mock_nr.expirationDate = None mock_expiry_days = int(nr_svc.get_expiry_days(mock_nr)) assert mock_expiry_days == days
def test_has_consumed_name(): """Assert has_consumed_name.""" from namex.models import Name, Request as RequestDAO, State name = Name() name.choice = 1 name.name = 'TEST' name.state = 'APPROVED' nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.CONSUMED nr.names.append(name) nr.save_to_db() assert nr.has_consumed_name is True
def save_name(submitted_date, nr_num, priority=False): from namex.models import Request as RequestDAO, State num = 0 global num_records nr_num_label = 'NR ' nr_num = nr_num_label + str(nr_num) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.DRAFT nr.priorityCd = 'Y' if priority else 'N' nr._source = 'NAMEREQUEST' nr.submittedDate = submitted_date 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 create_name_request(self): """ # !Important! All new name requests should be initially set to the DRAFT state. # Use apply_state_change on the name_request to transition to any other state. :return: """ try: name_request = Request() self.generate_nr_keys() name_request.stateCd = State.DRAFT except Exception as err: raise CreateNameRequestError(err) return name_request
def create_base_nr(): nr = RequestDAO() nr.nrNum = 'NR 0000002' nr.stateCd = State.PENDING_PAYMENT nr.requestId = 1460775 nr._source = ValidSources.NAMEREQUEST.value name1 = NameDAO() name1.choice = 1 name1.name = 'TEST NAME ONE' nr.names = [name1] nr.additionalInfo = 'test' nr.requestTypeCd = 'CR' nr.request_action_cd = 'NEW' nr.save_to_db() return nr
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_is_expired(): """Assert is_expired.""" from namex.models import Name, Request as RequestDAO, State name = Name() name.choice = 1 name.name = 'TEST' name.state = 'APPROVED' nr = RequestDAO() nr.nrNum = 'NR 0000001' nr.stateCd = State.EXPIRED nr.names.append(name) nr.save_to_db() assert nr.is_expired is True
def test_get_queued_oldest(client, app): # SETUP ##### # add NR to database from namex.models import Request as RequestDAO, State, User nr = RequestDAO() nr.nrNum='NR 0000001' 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.nrNum == nr_oldest.nrNum
def save_names_queue(queue_number_records, priority=False): from namex.models import Request as RequestDAO, State num = 0 global num_records while queue_number_records > num: nr_num_label = 'NR ' num_records += 1 num += 1 nr_num = nr_num_label + str(num_records) nr = RequestDAO() nr.nrNum = nr_num nr.stateCd = State.DRAFT nr.priorityCd = 'Y' if priority else 'N' nr._source = 'NAMEREQUEST' nr.save_to_db()