Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
def test_namex_search_submitted_start_and_end_date(client, jwt, app,
                                                   submitted_start_date,
                                                   submitted_end_date,
                                                   expected_result_count):
    """Test searching by submitted start date and submitted end date."""

    submitted = [
        get_utc_server_now_with_delta(timedelta(days=-5 * (365))),
        get_utc_server_now_with_delta(timedelta(days=-1 * (365))),
        get_utc_server_now_with_delta(timedelta(days=-100)),
        get_utc_server_now_with_delta(timedelta(days=-1)),
        get_utc_server_now_with_delta(timedelta(days=-1)),
        get_utc_server_now_with_delta(timedelta(days=-1)),
        get_utc_server_now(),
        get_utc_server_now(),
        get_utc_server_now_with_delta(timedelta(days=1)),
        get_utc_server_now_with_delta(timedelta(days=100)),
        get_utc_server_now_with_delta(timedelta(days=1 * (365))),
        get_utc_server_now_with_delta(timedelta(days=5 * (365))),
    ]
    generate_nrs(len(submitted), [], [], submitted)

    # get the resource (this is what we are testing)
    rv = client.get(
        f'api/v1/requests?submittedStartDate={submitted_start_date}&submittedEndDate={submitted_end_date}&rows=1000',
        headers=create_header(jwt, [User.VIEWONLY]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    response_count = len(resp['nameRequests'][0])
    assert response_count >= 0
    assert response_count == expected_result_count
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
def test_namex_search_last_name(client, jwt, app, search_name):
    """Test search by applicant last name."""
    applicants = [
        create_applicant('1', 'ted'),
        create_applicant('2', 'test'),
        create_applicant('3', 'pretest'),
        create_applicant('4', 'testing'),
        create_applicant('5', 'testingmoreletters'),
    ]
    base_nrs = generate_nrs(len(applicants), [], [], [])
    for nr, applicant in zip(base_nrs, applicants):
        nr.applicants.append(applicant)
        nr.save_to_db()

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests?lastName={search_name}',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    if search_name == 'no matches':
        assert len(resp['nameRequests'][0]) == 0
    else:
        assert len(resp['nameRequests'][0]) > 0

    # check it returned NRs based on filter
    for nr in resp['nameRequests'][0]:
        assert search_name in nr['applicants'][0]['lastName']
Ejemplo n.º 6
0
def test_namex_search_consent(client, jwt, app, consent_option):
    """Test searching by consent."""
    base_nrs = generate_nrs(4, [], [], [])
    base_nrs[0].consentFlag = 'N'
    base_nrs[1].consentFlag = 'Y'
    base_nrs[2].consent_dt = datetime.utcnow()
    for nr in base_nrs:
        nr.save_to_db()

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests?consentOption={consent_option}',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    assert len(resp['nameRequests'][0]) > 0

    if consent_option == 'All':
        # should have returned all nrs
        assert len(resp['nameRequests'][0]) == len(base_nrs)
    else:
        # check it returned NRs based on filter
        for nr in resp['nameRequests'][0]:
            if consent_option == 'Received':
                assert nr['consent_dt'] is not None
            elif consent_option == 'Yes':
                assert nr['consentFlag'] == 'Y'
            else:
                assert nr['consentFlag'] != 'Y'
Ejemplo n.º 7
0
def execute_payment(client, jwt, create_payment_request, payment_action):
    """
    Create a payment. Automatically creates an NR for use.
    :param client:
    :param create_payment_request:
    :return:
    """
    headers = create_header(jwt, [User.STAFF])
    headers['content-type'] = 'application/json'

    draft_nr = setup_draft_nr(client)

    nr_id = draft_nr.get('id')
    # POST /api/v1/payments/<int:nr_id>/<string:payment_action>
    request_uri = API_BASE_URI + str(nr_id) + '/' + payment_action

    path = request_uri
    create_payment_request['headers'] = headers
    body = json.dumps(create_payment_request)
    log_request_path(path)

    response = client.post(path, data=body, headers=headers)

    assert response.status_code == 201

    payload = json.loads(response.data)
    verify_payment_payload(payload)

    assert payload.get('statusCode') == 'CREATED'
    assert payload.get('action') == payment_action

    return payload
Ejemplo n.º 8
0
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'
Ejemplo n.º 9
0
def test_namex_search_compname(client, jwt, app, search_name):
    """Test searching by NR names."""
    names = [[{
        'name': 'test1',
        'state': 'NE',
        'choice': 1
    }], [{
        'name': 'test 1',
        'state': 'NE',
        'choice': 1
    }], [{
        'name': 'test tester 1',
        'state': 'NE',
        'choice': 1
    }], [{
        'name': 'testing tester 1',
        'state': 'NE',
        'choice': 1
    }], [{
        'name': 'test tester 1',
        'state': 'NE',
        'choice': 1
    }]]
    generate_nrs(len(names), [], names, [])

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests?compName={search_name}',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')

    # should only contain nrs that contain the search_nr
    for nr in resp['nameRequests'][0]:
        matching_name = False
        for name in nr['names']:
            print(name)
            all_words_match = False
            for word in search_name.upper().split(' '):
                print(word)
                if word not in name['name']:
                    all_words_match = False
                    break
                else:
                    all_words_match = True
            if all_words_match:
                matching_name = True
                break
        assert matching_name
Ejemplo n.º 10
0
def test_namex_search_state(client, jwt, app, state_cd):
    """Test searching by state."""
    generate_nrs(14, [], [], [])

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests?queue={state_cd}',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    assert len(resp['nameRequests'][0]) > 0

    # should only contain nrs with the given state
    for nr in resp['nameRequests'][0]:
        assert nr['stateCd'] == state_cd
Ejemplo n.º 11
0
def test_namex_search_submitted_end_date_before_submitted_start_date(
        client, jwt, app, submitted_start_date, submitted_end_date):
    """Test searching by submitted end date before submitted start date."""

    # get the resource (this is what we are testing)
    rv = client.get(
        f'api/v1/requests?submittedStartDate={submitted_start_date}&submittedEndDate={submitted_end_date}&submittedEndDate={submitted_end_date}&rows=100000',
        headers=create_header(jwt, [User.VIEWONLY]))

    assert rv
    assert rv.status_code
    assert rv.status_code == 400
    assert rv.data
    resp = json.loads(rv.data.decode('utf-8'))
    assert resp.get('message')
    assert resp.get(
        'message') == 'submittedEndDate must be after submittedStartDate'
Ejemplo n.º 12
0
def test_namex_search_submitted_interval_with_submitted_start_and_end_date(
        client, jwt, app, submitted_interval, submitted_start_date,
        submitted_end_date):
    """Test searching by submitted interval with submitted start and end date."""

    # get the resource (this is what we are testing)
    rv = client.get(
        f'api/v1/requests?submittedInterval={submitted_interval}&submittedStartDate={submitted_start_date}&submittedEndDate={submitted_end_date}',
        headers=create_header(jwt, [User.VIEWONLY]))

    assert rv
    assert rv.status_code
    assert rv.status_code == 400
    assert rv.data
    resp = json.loads(rv.data.decode('utf-8'))
    assert resp.get('message')
    assert 'submittedInterval cannot be used in conjuction with submittedStartDate and submittedEndDate' in resp.get(
        'message')
Ejemplo n.º 13
0
def test_namex_search_nr_num(client, jwt, app, search_nr, nrs):
    """Test searching by NR number."""
    generate_nrs(len(nrs), nrs, [], [])

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests?nrNum={search_nr}',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    assert len(resp['nameRequests'][0]) == len(
        [nr for nr in nrs if search_nr in nr])

    # should only contain nrs that contain the search_nr
    for nr in resp['nameRequests'][0]:
        assert search_nr in nr['nrNum']
Ejemplo n.º 14
0
def test_namex_search_default(client, jwt, app):
    """Test default search brings back nrs as expected."""
    generate_nrs(14, [], [], [])

    # get the resource (this is what we are testing)
    rv = client.get(f'api/v1/requests',
                    headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    # default should return up to 10 and order by submitted date desc
    assert len(resp['nameRequests'][0]) == 10

    date = resp['nameRequests'][0][0]['submittedDate']
    for nr in resp['nameRequests'][0]:
        assert nr['submittedDate'] <= date
        date = nr['submittedDate']
Ejemplo n.º 15
0
def test_get_existing_user_settings(client, jwt, app):
    """Test getting user settings for an existing user."""
    user = User(
        username='******',
        sub='43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',  # this needs to match the sub in create_header
        firstname='',
        lastname='',
        iss=''
    )
    user.searchColumns = 'Status'
    user.save_to_db()

    # check it gets the existing settings stored in the db
    existing_user_settings = client.get(f'api/v1/usersettings', headers=create_header(jwt, [User.EDITOR], 'test-settings'))
    data = existing_user_settings.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('searchColumns')
    assert resp.get('searchColumns') == ['Status']
Ejemplo n.º 16
0
def test_update_user_settings(client, jwt, app):
    """Test updating user settings for an existing user."""
    # create user with settings
    user = User(
        username='******',
        sub='43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc',  # this needs to match the sub in create_header
        firstname='',
        lastname='',
        iss=''
    )
    user.searchColumns = 'Status'
    user.save_to_db()
    # update user with put endpoint
    update_user_settings = client.put(
        f'api/v1/usersettings',
        json={ 'searchColumns': ['Status','LastModifiedBy'] },
        headers=create_header(jwt, [User.EDITOR], 'test-settings')
    )
    # assert user was successfully updated
    assert update_user_settings.status_code == 204
    assert user.searchColumns == 'Status,LastModifiedBy'
Ejemplo n.º 17
0
def test_get_inprogress_event_history(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()
    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.PATCH, nr, { 'state': 'INPROGRESS' })
    # 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
Ejemplo n.º 18
0
def test_decision_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 = create_base_nr()
    nr.stateCd = State.REJECTED
    nr.save_to_db()

    EventRecorder.record(user, Event.PATCH, nr, {'state': 'REJECTED'})

    # 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": "Decision"' in rv.data
Ejemplo n.º 19
0
def test_namex_search_submitted(client, jwt, app, order, submitted_interval,
                                last_date):
    """Test searching by submitted date."""
    submitted = [
        datetime.utcnow(),
        datetime.utcnow() - timedelta(days=6),
        datetime.utcnow() - timedelta(days=8),
        datetime.utcnow() - timedelta(days=29),
        datetime.utcnow() - timedelta(days=31),
        datetime.utcnow() - timedelta(days=89),
        datetime.utcnow() - timedelta(days=91),
        datetime.utcnow() - timedelta(days=1 * (365)),
        datetime.utcnow() - timedelta(days=2 * (365)),
        datetime.utcnow() - timedelta(days=3 * (365)),
        datetime.utcnow() - timedelta(days=5 * (365)),
    ]
    generate_nrs(len(submitted), [], [], submitted)

    # get the resource (this is what we are testing)
    rv = client.get(
        f'api/v1/requests?order=submittedDate:{order}&submittedInterval={submitted_interval}',
        headers=create_header(jwt, [User.EDITOR]))
    data = rv.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('nameRequests') and resp.get('response')
    assert len(resp['nameRequests'][0]) > 0

    # check order and that submitted dates are within search interval
    date = resp['nameRequests'][0][0]['submittedDate']
    for nr in resp['nameRequests'][0]:
        if last_date:
            assert nr['submittedDate'] >= last_date.isoformat()
        if order == 'asc':
            assert date <= nr['submittedDate']
        else:
            assert date >= nr['submittedDate']
        date = nr['submittedDate']
Ejemplo n.º 20
0
def test_consumed_event_history(client, jwt, app):
    from namex.models import State, User, Event
    from namex.services import EventRecorder

    # 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()

    headers = create_header(jwt, [User.EDITOR])

    nr = create_base_nr()
    nr.stateCd = State.CONSUMED
    nr.save_to_db()

    EventRecorder.record_as_system(Event.UPDATE_FROM_NRO, 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 b'"user_action": "Get NR Details from NRO"' in rv.data
Ejemplo n.º 21
0
def test_edit_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 = create_base_nr()
    nr.stateCd = State.INPROGRESS
    nr.additionalInfo = 'additional'
    nr.save_to_db()

    EventRecorder.record(user, Event.PUT, 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 b'"user_action": "Edit NR Details (NameX)"' in rv.data
Ejemplo n.º 22
0
def test_namex_search_submitted_start_and_end_date_invalid_date_format(
        client, jwt, app, submitted_start_date, submitted_end_date,
        valid_start_date, valid_end_date):
    """Test searching by submitted start and end date with incorrect date formats."""

    # get the resource (this is what we are testing)
    rv = client.get(
        f'api/v1/requests?submittedStartDate={submitted_start_date}&submittedEndDate={submitted_end_date}',
        headers=create_header(jwt, [User.VIEWONLY]))

    assert rv
    assert rv.status_code
    assert rv.status_code == 400
    assert rv.data
    resp = json.loads(rv.data.decode('utf-8'))
    msg = resp.get('message')
    assert msg

    if not valid_start_date:
        assert 'Invalid submittedStartDate: ' in msg
        assert 'Must be of date format %Y-%m-%d' in msg
    elif (valid_start_date and not valid_end_date):
        assert 'Invalid submittedEndDate: ' in msg
        assert 'Must be of date format %Y-%m-%d' in msg
Ejemplo n.º 23
0
def test_get_new_user_settings(client, jwt, app):
    """Test getting user settings for a new user."""
    new_user_settings = client.get(f'api/v1/usersettings', headers=create_header(jwt, [User.EDITOR], 'test-settings'))
    data = new_user_settings.data
    assert data
    resp = json.loads(data.decode('utf-8'))

    assert resp.get('searchColumns')
    # should have generated default settings for a new user
    assert resp.get('searchColumns') == [
        'Status',
        'LastModifiedBy',
        'NameRequestNumber',
        'Names',
        'ApplicantFirstName',
        'ApplicantLastName',
        'NatureOfBusiness',
        'ConsentRequired',
        'Priority',
        'ClientNotification',
        'Submitted',
        'LastUpdate',
        'LastComment'
    ]