Exemplo n.º 1
0
 def decorated(*args, **kwargs):
     auth = request.authorization
     if not auth or not helper.check_credentials(
             Config.FLASK_BASIC_AUTH_USER, Config.FLASK_BASIC_AUTH_PASS,
             auth.username, auth.password):
         helper.middle_logic([
             {
                 "try": splunk_middleware.basic_authentication_failed,
                 "fail": []
             },
             {
                 "try": splunk.log_to_splunk,
                 "fail": []
             },
         ],
                             config=Config,
                             request=request)
         logging.warning(
             "Request denied - unauthorized - IP Address: {}".format(
                 request.remote_addr))
         message = {'error': 'Unauthorized'}
         resp = jsonify(message)
         resp.status_code = 401
         return resp
     return f(*args, **kwargs)
Exemplo n.º 2
0
def test_an_unlicenced_applicant_that_applies_using_incorrect_last_name_gets_appropriate_email(
):
    date_served = "2020-09-23"
    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "21999344", "21999344"),
                  json=vips_mock.status_has_never_applied(
                      "UL", date_served, "Wrong"),
                  status=404,
                  match_querystring=True)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"response": "ignored"},
                  status=200)

    message_dict = get_sample_application_submission("UL")

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)

    email_payload = json.loads(responses.calls[2].request.body.decode())
    assert "*****@*****.**" in email_payload['to']
    assert "Prohibition Number or Name Don't Match - Driving Prohibition 21-999344 Review" == email_payload[
        'subject']
    assert "You can re-apply at any time." in email_payload['body']
Exemplo n.º 3
0
def test_a_successful_applicant_gets_an_application_accepted_email(
        prohib, monkeypatch):
    date_served = "2021-02-19"

    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "21999344", "21999344"),
                  json=vips_mock.status_has_never_applied(prohib, date_served),
                  status=200,
                  match_querystring=True)

    responses.add(responses.POST,
                  '{}/{}/{}/application/{}'.format(Config.VIPS_API_ROOT_URL,
                                                   prohib, "21999344",
                                                   "21999344"),
                  json={},
                  status=200)

    responses.add(responses.POST,
                  "{}:{}/services/collector".format(Config.SPLUNK_HOST,
                                                    Config.SPLUNK_PORT),
                  status=200)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"response": "ignored"},
                  status=200)

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(
            datetime.datetime.strptime("2021-02-23", "%Y-%m-%d"))
        return True, args

    monkeypatch.setattr(middleware, "determine_current_datetime",
                        mock_datetime_now)
    message_dict = get_sample_application_submission(prohib)

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)

    email_payload = json.loads(responses.calls[4].request.body.decode())
    assert "*****@*****.**" in email_payload['to']
    assert "Application Accepted - Driving Prohibition 21-999344 Review" == email_payload[
        'subject']
    assert "Your application for a review of driving prohibition 21999344 has been accepted." in email_payload[
        'body']
    assert "You must pay in full by credit card by February 27, 2021" in email_payload[
        'body']
    assert "If you don't pay by February 27, 2021, your review will not go ahead." in email_payload[
        'body']
    assert "http://link-to-paybc" in email_payload['body']
Exemplo n.º 4
0
def test_if_no_disclosure_add_back_to_hold_queue(monkeypatch):
    message_dict = helper.load_json_into_dict(
        'python/common/tests/sample_data/form/disclosure_payload.json')
    message_dict['hold_until'] = (datetime.datetime.now() -
                                  datetime.timedelta(hours=1)).isoformat()
    tz = pytz.timezone('America/Vancouver')
    review_start_date = vips.vips_datetime(
        datetime.datetime.now(tz) - datetime.timedelta(days=1))

    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "20123456", "20123456"),
                  json=vips_mock.status_with_no_disclosure(
                      "IRP", review_start_date),
                  status=200,
                  match_querystring=True)

    def mock_publish(queue_name: str, payload: bytes):
        assert queue_name == "DF.hold"

    monkeypatch.setattr(Config, "ENCRYPT_KEY", "something-secret")
    monkeypatch.setattr(RabbitMQ, "publish", mock_publish)

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=RabbitMQ)
Exemplo n.º 5
0
def test_when_an_applicants_review_has_concluded_the_disclosure_event_is_deleted(
        monkeypatch):
    message_dict = helper.load_json_into_dict(
        'python/common/tests/sample_data/form/disclosure_payload.json')
    message_dict['hold_until'] = (datetime.datetime.now() -
                                  datetime.timedelta(hours=1)).isoformat()
    tz = pytz.timezone('America/Vancouver')
    review_start_date = vips.vips_datetime(
        datetime.datetime.now(tz) - datetime.timedelta(days=1))

    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "20123456", "20123456"),
                  json=vips_mock.status_applied_paid_and_scheduled(
                      "IRP", review_start_date),
                  status=200,
                  match_querystring=True)

    def mock_any_disclosure(*args, **kwargs):
        # We should never call this method
        assert False

    monkeypatch.setattr(middleware, "is_any_unsent_disclosure",
                        mock_any_disclosure)

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=RabbitMQ)
Exemplo n.º 6
0
def index():
    """
    List all forms
    """
    if request.method == 'GET':
        kwargs = helper.middle_logic([{
            "try": splunk_middleware.admin_get_forms,
            "fail": []
        }, {
            "try": splunk.log_to_splunk,
            "fail": []
        }, {
            "try":
            form_middleware.admin_list_all_forms_by_type,
            "fail": [
                {
                    "try": http_responses.server_error_response,
                    "fail": []
                },
            ]
        }],
                                     form_type=request.args.get('type'),
                                     request=request,
                                     config=Config)
        return kwargs.get('response')
Exemplo n.º 7
0
def schedule():
    """
    Confirm prohibition number and last name matches VIPS.
    Return list of possible review dates for given prohibition.
    Note: using POST instead of GET to allow last names with
    special characters from Orbeon.
    """
    if request.method == 'POST':
        # invoke middleware functions
        args = helper.middle_logic(business.get_available_time_slots(),
                                   prohibition_number=request.form['prohibition_number'],
                                   driver_last_name=request.form['last_name'],
                                   config=Config)
        if 'error_string' not in args:
            return jsonify(dict({
                "data": {
                    "is_valid": True,
                    "presentation_type": args.get('presentation_type'),
                    "time_slots": args.get('time_slots')
                }
            }))
        return jsonify(dict({
                    "data": {
                        "is_success": False,
                        "error": args.get('error_string'),
                        "timeSlots": []
                    }
                }))
Exemplo n.º 8
0
def index(form_type):
    """
    List all forms for a user
    """
    if request.method == 'GET':
        kwargs = helper.middle_logic(
            get_authorized_keycloak_user() + [{
                "try": splunk_middleware.log_form_index,
                "fail": []
            }, {
                "try":
                form_middleware.list_all_users_forms,
                "fail": [
                    {
                        "try": http_responses.server_error_response,
                        "fail": []
                    },
                ]
            }, {
                "try": splunk.log_to_splunk,
                "fail": []
            }],
            required_permission='forms-index',
            request=request,
            form_type=form_type,
            config=Config)
        return kwargs.get('response')
Exemplo n.º 9
0
def test_pay_bc_generate_invoice_method(prohibition_type, application_created, error, monkeypatch):
    is_in_vips = True
    prohibition_type = "ADP"
    today_is = "2020-09-14"
    last_name = "Gordon"
    date_served = "2020-09-10"
    is_paid = False

    def mock_status_get(*args, **kwargs):
        print('inside mock_status_get()')
        return status_get(is_in_vips, prohibition_type, date_served, last_name, is_paid, application_created)

    def mock_application_get(*args, **kwargs):
        print('inside mock_application_get()')
        return application_get()

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(datetime.datetime.strptime(today_is, "%Y-%m-%d"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    monkeypatch.setattr(middleware, "determine_current_datetime", mock_datetime_now)
    monkeypatch.setattr(vips, "status_get", mock_status_get)
    monkeypatch.setattr(vips, "application_get", mock_application_get)

    results = helper.middle_logic(business.generate_invoice(),
                                  prohibition_number="20-123456",
                                  config=Config)

    print(results.get('error_string'))
    if error is None:
        assert "error_string" not in results
    else:
        assert "error_string" in results
        assert results.get('error_string') == error
Exemplo n.º 10
0
def test_an_unlicenced_applicant_that_had_a_successful_review_cannot_apply_again(
):

    responses.add(
        responses.GET,
        '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL, "21999344",
                                 "21999344"),
        json=vips_mock.status_previously_applied_review_successful("UL"),
        status=200,
        match_querystring=True)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"response": "ignored"},
                  status=200)

    message_dict = get_sample_application_submission("UL")

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)

    email_payload = json.loads(responses.calls[2].request.body.decode())
    assert "*****@*****.**" in email_payload['to']
    assert "Previous Review on File – Driving Prohibition 21-999344 Review" == email_payload[
        'subject']
Exemplo n.º 11
0
def test_search_method(
        prohibition_type, date_served, today_is, is_paid, last_name, is_in_vips, error, monkeypatch):

    def mock_status_get(*args, **kwargs):
        print('inside mock_status_get()')
        return status_get(is_in_vips, prohibition_type, date_served, last_name, is_paid, True)

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(datetime.datetime.strptime(today_is, "%Y-%m-%d"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    monkeypatch.setattr(middleware, "determine_current_datetime", mock_datetime_now)
    monkeypatch.setattr(vips, "status_get", mock_status_get)

    results = helper.middle_logic(business.search_for_invoice(),
                                  prohibition_number="20-123456",
                                  driver_last_name="Gordon",
                                  config=Config)

    print(results.get('error_string'))
    if error is None:
        assert "error_string" not in results
    else:
        assert "error_string" in results
        assert results.get('error_string') == error
Exemplo n.º 12
0
def search():
    """
    On the Pay_BC site, a user lookups an prohibition_number (invoice) to be paid.
    PayBC searches for the invoice in our system using a GET request with an
    invoice number and a check_value.  We return an array of items to be paid.
    """
    if request.method == 'GET':
        # invoke middleware business logic
        prohibition_number = request.args.get('invoice_number')
        driver_last_name = request.args.get('check_value')
        logging.info('inputs: {}, {}'.format(prohibition_number,
                                             driver_last_name))
        args = helper.middle_logic(rules.search_for_invoice(),
                                   config=Config,
                                   prohibition_number=prohibition_number,
                                   driver_last_name=driver_last_name)
        if 'error_string' not in args:
            host_url = request.host_url.replace('http', 'https')
            return jsonify({
                "items": [{
                    "selected_invoice": {
                        "$ref":
                        host_url + 'api_v2/invoice/' +
                        args.get('prohibition_number')
                    }
                }]
            })
        return jsonify({"error": args.get('error_string')})
Exemplo n.º 13
0
def index():
    """
    List all authorized users and their associated user-roles
    """
    if request.method == 'GET':
        kwargs = helper.middle_logic(
            keycloak_logic.get_authorized_keycloak_user() + [
                {
                    "try": splunk_middleware.admin_get_users,
                    "fail": []
                },
                {
                    "try": splunk.log_to_splunk,
                    "fail": []
                },
                {
                    "try":
                    role_middleware.query_all_users,
                    "fail": [
                        {
                            "try": http_responses.server_error_response,
                            "fail": []
                        },
                    ]
                },
            ],
            required_permission='admin_users-index',
            request=request,
            config=Config)
        return kwargs.get('response')
Exemplo n.º 14
0
def show(prohibition_number):
    """
    PayBC requests details on the item to be paid from this endpoint.
    """
    if request.method == 'GET':
        # invoke middleware business logic
        args = helper.middle_logic(rules.generate_invoice(),
                                   prohibition_number=prohibition_number,
                                   config=Config)
        if 'error_string' not in args:
            presentation_type = args.get('presentation_type')
            amount_due = args.get('amount_due')
            service_date = args.get('service_date')
            return jsonify(
                dict({
                    "invoice_number": args.get('prohibition_number'),
                    "pbc_ref_number": "10008",
                    "party_number": 0,
                    "party_name": "n/a",
                    "account_number": "n/a",
                    "site_number": "0",
                    "cust_trx_type": "Review Notice of Driving Prohibition",
                    "term_due_date": service_date.isoformat(),
                    "total": amount_due,
                    "amount_due": amount_due,
                    "attribute1": args.get('notice_type_verbose'),
                    "attribute2": service_date.strftime("%b %-d, %Y"),
                    "attribute3": presentation_type,
                    "amount": amount_due
                }))
        return jsonify({"error": args.get('error_string')})
Exemplo n.º 15
0
def get_vehicle(plate_number):
    if request.method == 'GET':
        kwargs = middle_logic(
            get_authorized_keycloak_user() + [{
                "try":
                icbc_middleware.get_icbc_api_authorization_header,
                "fail": [
                    {
                        "try": http_responses.server_error_response,
                        "fail": []
                    },
                ]
            }, {
                "try":
                icbc_middleware.get_icbc_vehicle,
                "fail": [
                    {
                        "try": http_responses.server_error_response,
                        "fail": []
                    },
                ]
            }, {
                "try": icbc_middleware.splunk_get_vehicle,
                "fail": []
            }, {
                "try": splunk.log_to_splunk,
                "fail": []
            }],
            required_permission='vehicle-get',
            plate_number=plate_number.upper(),
            request=request,
            config=Config)
        return kwargs.get('response')
Exemplo n.º 16
0
def index():
    """
    List all roles for the currently logged-in user
    """
    if request.method == 'GET':
        kwargs = helper.middle_logic(
            keycloak_logic.get_authorized_keycloak_user() +
            [{
                "try": splunk_middleware.get_user_role,
                "fail": []
            }, {
                "try": splunk.log_to_splunk,
                "fail": []
            }, {
                "try":
                role_middleware.query_current_users_roles,
                "fail": [
                    {
                        "try": http_responses.server_error_response,
                        "fail": []
                    },
                ]
            }],
            required_permission='user_roles-index',
            request=request,
            config=Config)
        return kwargs.get('response')
Exemplo n.º 17
0
def test_okay_to_submit_evidence(prohibition_type, date_served, today_is,
                                 is_paid, last_name, is_valid, is_applied,
                                 review_start_date, expected, monkeypatch):
    def mock_status_get(*args, **kwargs):
        print('inside mock_status_get()')
        return status_gets(is_valid == "True", prohibition_type, date_served,
                           is_paid, review_start_date, last_name, is_applied)

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(
            datetime.datetime.strptime(today_is, "%Y-%m-%d %H:%M"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    monkeypatch.setattr(middleware, "determine_current_datetime",
                        mock_datetime_now)
    monkeypatch.setattr(vips, "status_get", mock_status_get)

    results = helper.middle_logic(business.is_okay_to_submit_evidence(),
                                  prohibition_number="00123456",
                                  driver_last_name="Gordon",
                                  config=Config)

    if expected == "True":
        print("error string: {}".format(results.get('error_string')))
        assert 'error_string' not in results
    else:
        assert 'error_string' in results
Exemplo n.º 18
0
def test_when_one_document_not_disclosed_one_document_is_emailed_to_applicant(
        monkeypatch):
    message_dict = helper.load_json_into_dict(
        'python/common/tests/sample_data/form/disclosure_payload.json')
    message_dict['hold_until'] = (datetime.datetime.now() -
                                  datetime.timedelta(hours=1)).isoformat()
    tz = pytz.timezone('America/Vancouver')
    review_start_date = vips.vips_datetime(
        datetime.datetime.now(tz) + datetime.timedelta(days=2))

    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "20123456", "20123456"),
                  json=vips_mock.status_with_one_sent_on_unsent_disclosure(
                      "IRP", review_start_date),
                  status=200,
                  match_querystring=True)

    responses.add(responses.GET,
                  '{}/{}/disclosure/{}'.format(Config.VIPS_API_ROOT_URL, "111",
                                               "20123456"),
                  json=vips_mock.disclosure_get(),
                  status=200,
                  match_querystring=True)

    responses.add(responses.PATCH,
                  '{}/disclosure/{}'.format(Config.VIPS_API_ROOT_URL,
                                            "20123456"),
                  json=vips_mock.disclosure_get(),
                  status=200,
                  match_querystring=True)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"sample": "test"},
                  status=200)

    def mock_publish(queue_name: str, payload: bytes):
        assert queue_name == "DF.hold"
        return True

    monkeypatch.setattr(Config, "ENCRYPT_KEY", "something-secret")
    monkeypatch.setattr(RabbitMQ, "publish", mock_publish)

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=RabbitMQ)

    email_payload = json.loads(responses.calls[3].request.body.decode())
    assert '*****@*****.**' in email_payload['to']
    assert len(email_payload['attachments']) == 1
Exemplo n.º 19
0
    def callback(self, ch, method, properties, body):
        # convert body (in bytes) to string
        message_dict = decode_message(body, self.config.ENCRYPT_KEY)

        logging.info("callback() invoked: {}".format(json.dumps(message_dict)))
        helper.middle_logic(helper.get_listeners(
            business.process_incoming_form(), message_dict['event_type']),
                            message=message_dict,
                            config=self.config,
                            writer=self.writer)

        # Regardless of whether the process above follows the happy path or not,
        # we need to acknowledge receipt of the message to RabbitMQ below. This
        # acknowledgement deletes it from the queue. The logic above
        # must have saved / handled the message before we get here.

        ch.basic_ack(delivery_tag=method.delivery_tag)
def test_application_form_received(prohibition_type, date_served, today_is,
                                   seized, last_name, is_valid, is_applied,
                                   email_text, monkeypatch):
    def mock_status_get(*args, **kwargs):
        print('inside mock_status_get()')
        is_response_successful, data = status_gets(is_valid == "True",
                                                   prohibition_type,
                                                   date_served, last_name,
                                                   seized, "N/A", is_applied)
        if is_response_successful and 'resp' in data:
            return True, data
        return False, dict({})

    def mock_send_email(*args, **kwargs):
        print('inside mock_send_email()')
        assert "*****@*****.**" in args[0]
        print("Subject: {}".format(args[1]))
        assert email_text in args[3]
        return True

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(
            datetime.datetime.strptime(today_is, "%Y-%m-%d"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    def mock_application_save(**args):
        print('inside mock_application_save()')
        return True, args

    def mock_add_to_hold(**args):
        print('inside mock_add_to_hold()')
        return True, args

    monkeypatch.setattr(actions, "add_to_hold_queue", mock_add_to_hold)
    monkeypatch.setattr(middleware, "determine_current_datetime",
                        mock_datetime_now)
    monkeypatch.setattr(middleware, "save_application_to_vips",
                        mock_application_save)
    monkeypatch.setattr(vips, "status_get", mock_status_get)
    monkeypatch.setattr(common_email_services, "send_email", mock_send_email)

    message_dict = helper.load_json_into_dict(
        'python/tests/sample_data/form/irp_form_submission.json')

    # For the prohibition_not_found and the prohibition_not_found_yet emails, we rely on users entering
    # correct prohibition number prefix to determine the correct letter type.
    if prohibition_type == "UL":
        message_dict['prohibition_review']['form']['prohibition-information'][
            'control-is-ul'] = "true"
        message_dict['prohibition_review']['form']['prohibition-information'][
            'control-is-irp'] = "false"

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)
Exemplo n.º 21
0
def test_disclosure_event_processing(
        prohibition_type, today_is, review_start_date, is_valid, disclosure, attachments_expected, monkeypatch):

    def mock_status_get(*args, **kwargs):
        print('inside mock_status_get()')
        return status_gets(is_valid == "True", prohibition_type, review_start_date, disclosure)

    def mock_send_email(*args, **kwargs):
        print('inside mock_send_email()')
        assert "*****@*****.**" in args[0]
        print("Subject: {}".format(args[1]))
        return True

    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(datetime.datetime.strptime(today_is, "%Y-%m-%d"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    def mock_add_to_hold(**args):
        print("inside mock_add_to_hold")
        return True, args

    def mock_disclosure_get(*args):
        print("inside mock_disclosure_get()")
        data = dict({
                "resp": "success",
                "data": {
                    "document": {
                        "document": "base64_string_of_encoded_document",
                        "mimeType": "application/pdf"
                    }
                }
            })
        return True, data

    def mock_patch(*args):
        return True, dict({})

    monkeypatch.setattr(middleware, "determine_current_datetime", mock_datetime_now)
    monkeypatch.setattr(vips, "status_get", mock_status_get)
    monkeypatch.setattr(vips, "patch", mock_patch)
    monkeypatch.setattr(common_email_services, "send_email", mock_send_email)
    monkeypatch.setattr(actions, "add_to_hold_queue", mock_add_to_hold)
    monkeypatch.setattr(vips, "disclosure_get", mock_disclosure_get)

    message_dict = helper.load_json_into_dict('python/tests/sample_data/form/disclosure_payload.json')

    results = helper.middle_logic(helper.get_listeners(business.process_incoming_form(), message_dict['event_type']),
                        message=message_dict,
                        config=Config,
                        writer=None)

    if attachments_expected > 0:
        assert 'disclosure_for_applicant' in results
        assert len(results.get('disclosure_for_applicant')) == attachments_expected
    else:
        assert 'disclosure_for_applicant' not in results
Exemplo n.º 22
0
    def callback(self, ch, method, properties, body):
        logging.info('message received; callback invoked')

        # convert body (in bytes) to string
        message_dict = decode_message(body, self.config.ENCRYPT_KEY)

        helper.middle_logic(helper.get_listeners(business.process_ekt_events(),
                                                 message_dict['event_type']),
                            message=message_dict,
                            config=self.config,
                            writer=self.writer)

        # Regardless of whether the write above is successful we need to
        # acknowledge receipt of the message to RabbitMQ. This acknowledgement
        # deletes it from the queue so the logic above must have saved or
        # handled the message before we get here.

        ch.basic_ack(delivery_tag=method.delivery_tag)
Exemplo n.º 23
0
def ready():
    """
    This endpoint checks whether we can connect to the DataBC Geocoder
    """
    test_address = "4350 STILL CREEK, CHILLIWACK"
    results = helper.middle_logic(business.determine_ready_status(),
                                  config=Config,
                                  address_raw=test_address)
    return results.get('response')
Exemplo n.º 24
0
def ingest_form():
    if request.method == 'POST':
        # invoke middleware functions
        args = helper.middle_logic(business.ingest_form(),
                                   writer=g.writer,
                                   form_parameters=available_parameters['form'],
                                   request=request,
                                   config=Config)

        return args.get('response')
Exemplo n.º 25
0
def ingest_orbeon_form():
    if request.method == 'POST':
        logging.info("ingest_form_deprecated() invoked: {} | {}".format(
            request.remote_addr, request.get_data()))
        args = helper.middle_logic(business.ingest_form(),
                                   writer=g.writer,
                                   form_parameters=available_parameters,
                                   request=request,
                                   config=Config)
        return args.get('response')
Exemplo n.º 26
0
def create(form_type):
    """
    Save a new form.  The web_app uses this endpoint to lease a unique form_id
    for 30 days and save the user's name in the form table. This endpoint is not
    used to submit a new form.  All payloads to this endpoint are ignored.
    """
    if request.method == 'POST':
        logging.info("new {} form_id requested".format(form_type))
        kwargs = helper.middle_logic(
            get_authorized_keycloak_user() + [{
                "try":
                form_middleware.request_contains_a_payload,
                "fail": [
                    {
                        "try":
                        form_middleware.lease_a_form_id,
                        "fail": [
                            {
                                "try": splunk_middleware.insufficient_form_ids,
                                "fail": []
                            },
                            {
                                "try": splunk.log_to_splunk,
                                "fail": []
                            },
                            {
                                "try": http_responses.server_error_response,
                                "fail": []
                            },
                        ]
                    },
                    {
                        "try": splunk_middleware.log_form_create,
                        "fail": []
                    },
                    {
                        "try": splunk.log_to_splunk,
                        "fail": []
                    },
                    {
                        "try": http_responses.successful_create_response,
                        "fail": []
                    },
                ]
            }, {
                "try": http_responses.bad_request_response,
                "fail": []
            }],
            required_permission='forms-create',
            request=request,
            form_type=form_type,
            config=Config)
        return kwargs.get('response')
Exemplo n.º 27
0
def show(prohibition_number):
    """
    PayBC requests details on the item to be paid from this endpoint.
    """
    if request.method == 'GET':
        logging.info("show() invoked: {} | {}".format(request.remote_addr,
                                                      request.get_data()))
        args = helper.middle_logic(rules.generate_invoice(),
                                   prohibition_number=prohibition_number,
                                   config=Config)
        return args.get('response',
                        jsonify({"error": args.get('error_string')}))
Exemplo n.º 28
0
def address():
    """
    Lookup lat/lon of street address using DataBC. If the DataBC's
    confidence score is below threshold determined in the config,
    check the address against Google's API and return both results.
    """
    if request.method == 'POST':
        # invoke middleware functions
        args = helper.middle_logic(business.geocode_address(),
                                   request=request,
                                   config=Config)
        return args.get('response')
Exemplo n.º 29
0
def test_an_applicant_that_was_served_7_days_ago_but_not_in_vips_gets_still_not_found_email(
        prohib, monkeypatch):
    def mock_datetime_now(**args):
        args['today_date'] = helper.localize_timezone(
            datetime.datetime.strptime("2020-09-29", "%Y-%m-%d"))
        print('inside mock_datetime_now: {}'.format(args.get('today_date')))
        return True, args

    def mock_add_to_hold(**args):
        print('inside mock_add_to_hold()')
        return True, args

    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "21999344", "21999344", "21999344"),
                  json=vips_mock.status_not_found(),
                  status=404,
                  match_querystring=True)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"response": "ignored"},
                  status=200)

    monkeypatch.setattr(actions, "add_to_hold_queue", mock_add_to_hold)
    monkeypatch.setattr(middleware, "determine_current_datetime",
                        mock_datetime_now)
    message_dict = get_sample_application_submission(prohib)

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)

    email_payload = json.loads(responses.calls[2].request.body.decode())
    assert "*****@*****.**" in email_payload['to']
    assert "Prohibition Still Not Found - Driving Prohibition 21-999344" in email_payload[
        'subject']
    assert "If it's not in our system by the next time we check, your online" in email_payload[
        'body']
    assert "You can't get a review extension if you miss the deadline" in email_payload[
        'body']
    assert "http://link-to-icbc" in email_payload['body']
    assert "http://link-to-service-bc" in email_payload['body']
Exemplo n.º 30
0
def test_an_unlicenced_successful_applicant_gets_an_application_accepted_email(
):
    date_served = (datetime.datetime.now() -
                   datetime.timedelta(days=6)).strftime("%Y-%m-%d")
    responses.add(responses.GET,
                  '{}/{}/status/{}'.format(Config.VIPS_API_ROOT_URL,
                                           "21999344", "21999344"),
                  json=vips_mock.status_has_never_applied("UL", date_served),
                  status=200,
                  match_querystring=True)

    responses.add(responses.POST,
                  '{}/{}/{}/application/{}'.format(Config.VIPS_API_ROOT_URL,
                                                   "UL", "21999344",
                                                   "21999344"),
                  json={},
                  status=200)

    responses.add(responses.POST,
                  "{}:{}/services/collector".format(Config.SPLUNK_HOST,
                                                    Config.SPLUNK_PORT),
                  status=200)

    responses.add(responses.POST,
                  '{}/realms/{}/protocol/openid-connect/token'.format(
                      Config.COMM_SERV_AUTH_URL, Config.COMM_SERV_REALM),
                  json={"access_token": "token"},
                  status=200)

    responses.add(responses.POST,
                  '{}/api/v1/email'.format(Config.COMM_SERV_API_ROOT_URL),
                  json={"response": "ignored"},
                  status=200)

    message_dict = get_sample_application_submission("UL")

    results = helper.middle_logic(helper.get_listeners(
        business.process_incoming_form(), message_dict['event_type']),
                                  message=message_dict,
                                  config=Config,
                                  writer=None)

    email_payload = json.loads(responses.calls[4].request.body.decode())
    assert "*****@*****.**" in email_payload['to']
    assert "Application Accepted - Driving Prohibition 21-999344 Review" == email_payload[
        'subject']
    assert "Your application for a review of driving prohibition 21999344 has been accepted." in email_payload[
        'body']
    assert "You must pay in full by credit card within 7 days of applying for this review." in email_payload[
        'body']
    assert "http://link-to-paybc" in email_payload['body']