def test_search_invalid_criteria_400(session, client, jwt, search_type, json_data): """Assert that validation of a search request with invalid criteria throws a BusinessException.""" # test with pytest.raises(BusinessException) as bad_request_err: SearchClient.validate_query(json_data) # check assert bad_request_err assert bad_request_err.value.status_code == HTTPStatus.BAD_REQUEST
def test_search_history_sort(session, client, jwt): """Assert that search results history sort order works as expected.""" # setup json_data = { 'type': 'REGISTRATION_NUMBER', 'criteria': { 'value': 'TEST0001' } } search_query = SearchClient.create_from_json(json_data, 'PS12345') # test search_query.search() search_detail = SearchResult.create_from_search_query(search_query) search_detail.save() # check assert search_detail.search_id == search_query.search_id result = search_detail.json # print(details_json) history = result[0]['financingStatement']['changes'] assert len(history) == 4 assert history[0]['changeRegistrationNumber'] == 'TEST0009' assert history[1]['changeRegistrationNumber'] == 'TEST0008' assert history[2]['amendmentRegistrationNumber'] == 'TEST0007' assert history[3]['changeRegistrationNumber'] == 'TEST0010'
def test_search_no_results(session, search_type, json_data): """Assert that a search query with no results returns the expected result.""" query = SearchClient.create_from_json(json_data, None) query.search() assert query.search_id assert not query.search_response assert query.returned_results_size == 0
def test_search_valid(session, search_type, json_data): """Assert that a valid search returns the expected search type result.""" query = SearchClient.create_from_json(json_data, None) query.search() result = query.json # print(result) assert query.search_id assert query.search_response assert result['searchId'] assert result['searchQuery'] assert result['searchDateTime'] assert result['totalResultsSize'] assert result['maxResultsSize'] assert result['returnedResultsSize'] assert len(result['results']) >= 1 assert result['results'][0]['baseRegistrationNumber'] assert result['results'][0]['createDateTime'] assert result['results'][0]['matchType'] == 'EXACT' assert result['results'][0]['registrationType'] if search_type == 'BS': assert result['results'][0]['debtor'] assert result['results'][0]['debtor'][ 'businessName'] == 'TEST BUS 2 DEBTOR' elif search_type == 'IS': assert result['results'][0]['debtor'] assert result['results'][0]['debtor']['personName'] assert result['results'][0]['debtor']['personName']['last'] == 'DEBTOR' assert result['results'][0]['debtor']['personName'][ 'first'] == 'TEST IND' elif search_type == 'AM': assert result['results'][0]['baseRegistrationNumber'] == 'TEST0001' assert result['results'][0]['registrationNumber'] == 'TEST0007' elif search_type == 'CH': assert result['results'][0]['baseRegistrationNumber'] == 'TEST0001' assert result['results'][0]['registrationNumber'] == 'TEST0008' elif search_type == 'RG': assert result['results'][0]['baseRegistrationNumber'] == 'TEST0001' else: assert result['results'][0]['vehicleCollateral'] assert result['results'][0]['vehicleCollateral']['year'] assert result['results'][0]['vehicleCollateral']['make'] assert result['results'][0]['vehicleCollateral']['serialNumber'] if search_type != 'MH': assert result['results'][0]['vehicleCollateral']['model'] if search_type == 'AF': assert result['results'][0]['vehicleCollateral']['type'] == 'AF' assert result['results'][0]['vehicleCollateral'][ 'serialNumber'] == 'AF16031' elif search_type == 'AC': assert result['results'][0]['vehicleCollateral']['type'] == 'AC' assert result['results'][0]['vehicleCollateral'][ 'serialNumber'] == 'CFYXW' elif search_type == 'MH': assert result['results'][0]['vehicleCollateral'][ 'manufacturedHomeRegistrationNumber'] == '220000'
def test_search_detail_full_create(session, client, jwt): """Assert that submitting a new search and selecting the detail results works as expected.""" # setup json_data = { 'type': 'SERIAL_NUMBER', 'criteria': { 'value': 'JU622994' }, 'clientReferenceId': 'T-SR-SS-1001' } search_query = SearchClient.create_from_json(json_data, 'PS12345') # test search_query.search() query_json = search_query.json # print(query_json) search_detail = SearchResult.create_from_search_query(search_query) search_detail.save() # check assert search_detail.search_id == search_query.search_id assert not search_detail.search_select assert search_detail.exact_match_count > 0 assert search_detail.similar_match_count > 0 exact_count = search_detail.exact_match_count similar_count = search_detail.similar_match_count # Search step 2: modify search selection and update. # setup query_results_json = query_json['results'] select_json = [] for result in query_results_json: if result['matchType'] == 'EXACT': select_json.append(result) elif result['baseRegistrationNumber'] not in ('TEST0002', 'TEST0003'): select_json.append(result) # test search_detail2 = SearchResult.validate_search_select( select_json, search_detail.search_id) search_detail2.update_selection(select_json) # check # print(search_detail2.search_select) assert search_detail2.search_select assert exact_count == search_detail2.exact_match_count assert similar_count > search_detail2.similar_match_count details_json = search_detail2.json # print(details_json) for detail in details_json['details']: assert detail['financingStatement']['baseRegistrationNumber'] not in ( 'TEST0002', 'TEST0003')
def test_search_autosave(session): """Assert that a valid search query selection update works as expected.""" query = SearchClient.find_by_id(200000000) assert query.search_response update_data = json.loads(query.search_response) if update_data[0]['matchType'] == 'EXACT': update_data[0]['matchType'] = 'SIMILAR' else: update_data[0]['matchType'] = 'EXACT' query.update_search_selection(update_data) json_data = query.json assert json_data['results'][0]['matchType'] == update_data[0]['matchType']
def test_find_by_account_id(session): """Assert that the account search history list first item contains all expected elements.""" history = SearchClient.find_all_by_account_id('PS12345') # print(history) assert history assert history[0]['searchId'] assert history[0]['searchDateTime'] assert history[0]['totalResultsSize'] assert history[0]['returnedResultsSize'] assert history[0]['exactResultsSize'] assert history[0]['selectedResultsSize'] assert history[0]['searchQuery'] assert len(history) >= 1
def test_search_enddatatetime_invalid(session, client, jwt): """Assert that validation of a search with an invalid endDateTime throws a BusinessException.""" # setup json_data = { 'type': 'REGISTRATION_NUMBER', 'criteria': { 'value': 'TEST0001' }, 'clientReferenceId': 'T-API-SQ-RG-8', 'startDateTime': '2021-01-20T19:38:43+00:00' } ts_end = now_ts_offset(1, True) json_data['endDateTime'] = format_ts(ts_end) # test with pytest.raises(BusinessException) as bad_request_err: SearchClient.validate_query(json_data) # check assert bad_request_err assert bad_request_err.value.status_code == HTTPStatus.BAD_REQUEST print(bad_request_err.value.error)
def test_search_no_account(session): """Assert that a search query with not account id returns the expected result.""" json_data = { 'type': 'REGISTRATION_NUMBER', 'criteria': { 'value': 'TEST0001' }, 'clientReferenceId': 'T-SQ-RG-4' } query = SearchClient.create_from_json(json_data, None) query.search() assert query.search_id assert query.search_response
def test_create_from_json(session): """Assert that the search_client creates from a json format correctly.""" json_data = { 'type': 'SERIAL_NUMBER', 'criteria': { 'value': 'JU622994' }, 'clientReferenceId': 'T-SQ-SS-1' } search_client = SearchClient.create_from_json(json_data, 'PS12345') assert search_client.account_id == 'PS12345' assert search_client.search_type_cd == 'SS' assert search_client.client_reference_id == 'T-SQ-SS-1' assert search_client.search_ts assert search_client.search_criteria
def test_search_discharged(session, search_type, json_data, excluded_match): """Assert that a discharged financing statement is excluded from the search results.""" query = SearchClient.create_from_json(json_data, None) query.search() result = query.json assert result['searchId'] if search_type == 'RG': assert not query.search_response assert query.returned_results_size == 0 elif 'results' in result: for r in result['results']: if search_type == 'BS': assert r['debtor']['businessName'] != excluded_match elif search_type == 'IS': assert r['debtor']['personName']['first'] != excluded_match else: assert r['vehicleCollateral']['serialNumber'] != excluded_match
def get(): """Get account search history.""" try: # Quick check: must have an account ID. account_id = resource_utils.get_account_id(request) if account_id is None: return resource_utils.account_required_response() # Verify request JWT and account ID if not authorized(account_id, jwt): return resource_utils.unauthorized_error_response(account_id) # Try to fetch search history by account id. # No results throws a not found business exception. current_app.logger.info( f'Fetching search history for {account_id}.') history = SearchClient.find_all_by_account_id(account_id) return jsonify(history), HTTPStatus.OK except BusinessException as exception: return resource_utils.business_exception_response(exception) except Exception as default_exception: # noqa: B902; return nicer default error return resource_utils.default_exception_response(default_exception)
def put(search_id): """Execute a search selection update request replacing the current value with the request body contents.""" try: if search_id is None: return resource_utils.path_param_error_response('search ID') # Quick check: must be staff or provide an account ID. account_id = resource_utils.get_account_id(request) if not is_staff(jwt) and account_id is None: return resource_utils.account_required_response() # Verify request JWT and account ID if not authorized(account_id, jwt): return resource_utils.unauthorized_error_response(account_id) request_json = request.get_json(silent=True) # Validate schema. valid_format, errors = schema_utils.validate( request_json, 'searchSummary', 'ppr') if not valid_format: return resource_utils.validation_error_response( errors, VAL_ERROR) search_client = SearchClient.find_by_id(search_id) if not search_client: return resource_utils.not_found_error_response( 'searchId', search_id) # Save the updated search selection. search_client.update_search_selection(request_json) return jsonify(json.loads( search_client.search_response)), HTTPStatus.ACCEPTED except BusinessException as exception: return resource_utils.business_exception_response(exception) except Exception as default_exception: # noqa: B902; return nicer default error return resource_utils.default_exception_response(default_exception)
def post(): """Execute a new search request using criteria in the request body.""" try: # Quick check: must be staff or provide an account ID. account_id = resource_utils.get_account_id(request) if not is_staff(jwt) and account_id is None: return resource_utils.account_required_response() # Verify request JWT and account ID if not authorized(account_id, jwt): return resource_utils.unauthorized_error_response(account_id) request_json = request.get_json(silent=True) # Validate request against the schema. valid_format, errors = schema_utils.validate( request_json, 'searchQuery', 'ppr') if not valid_format: return resource_utils.validation_error_response( errors, VAL_ERROR) # Perform any extra data validation such as start and end dates here SearchClient.validate_query(request_json) query = SearchClient.create_from_json(request_json, account_id) # Charge a search fee. if account_id: payment = Payment(jwt=jwt.get_token_auth_header(), account_id=account_id) pay_ref = payment.create_payment(TransactionTypes.SEARCH.value, 1, None, query.client_reference_id) invoice_id = pay_ref['invoiceId'] query.pay_invoice_id = int(invoice_id) query.pay_path = pay_ref['receipt'] # Execute the search query: treat no results as a success. try: query.search() # if not query.search_response or query.returned_results_size == 0: # return resource_utils.unprocessable_error_response('search query') # Now save the initial detail results in the search_result table with no # search selection criteria (the absence indicates an incomplete search). search_result = SearchResult.create_from_search_query(query) search_result.save() except Exception as db_exception: # noqa: B902; handle all db related errors. current_app.logger.error( f'Search {account_id} db save failed: ' + repr(db_exception)) current_app.logger.error( f'Search {account_id} rolling back payment for invoice {invoice_id}.' ) try: payment.cancel_payment(invoice_id) except Exception as cancel_exception: # noqa: B902; log exception current_app.logger.error( f'Search {account_id} payment refund failed for invoice {invoice_id}: ' + repr(cancel_exception)) raise db_exception return query.json, HTTPStatus.CREATED except SBCPaymentException as pay_exception: return resource_utils.pay_exception_response(pay_exception) except BusinessException as exception: return resource_utils.business_exception_response(exception) except Exception as default_exception: # noqa: B902; return nicer default error return resource_utils.default_exception_response(default_exception)
def test_get_total_count(session, search_type, json_data, result_size): """Assert that the get total count function works as expected.""" search_client = SearchClient.create_from_json(json_data, 'PS12345') search_client.get_total_count() # print('test_total_count ' + search_type + ' actual results size=' + str(search_client.total_results_size)) assert search_client.total_results_size >= result_size
def test_find_by_account_id_no_result(session): """Assert that the find search history by invalid account ID returns the expected result.""" history = SearchClient.find_all_by_account_id('XXXX345') # check assert len(history) == 0