Beispiel #1
0
def test_get_service_for_user(notify_api, notify_db, notify_db_session,
                              sample_service):
    second_user = create_sample_user(notify_db, notify_db_session,
                                     '*****@*****.**')
    create_sample_service(notify_db,
                          notify_db_session,
                          service_name='Second Service',
                          user=second_user)
    create_sample_service(notify_db,
                          notify_db_session,
                          service_name='Another Service',
                          user=sample_service.users[0])
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            auth_header = create_authorization_header(path='/service',
                                                      method='GET')
            resp = client.get('/service?user_id={}'.format(
                sample_service.users[0].id),
                              headers=[auth_header])
            assert resp.status_code == 200
            json_resp = json.loads(resp.get_data(as_text=True))
            assert len(json_resp['data']) == 2
            print(x for x in json_resp['data'])
            assert 'Another Service' in [
                x.get('name') for x in json_resp['data']
            ]
            assert 'Sample service' in [
                x.get('name') for x in json_resp['data']
            ]
            assert 'Second Service' not in [
                x.get('name') for x in json_resp['data']
            ]
def test_get_services(notify_api, notify_db, notify_db_session, sample_user):
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           user=sample_user)
    assert Service.query.count() == 1
    assert len(get_model_services()) == 1
    service_name = "Another service"
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_user)
    assert Service.query.count() == 2
    assert len(get_model_services()) == 2
def test_get_services(notify_api, notify_db, notify_db_session, sample_user):
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           user=sample_user)
    assert Service.query.count() == 1
    assert len(get_model_services()) == 1
    service_name = "Another service"
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_user)
    assert Service.query.count() == 2
    assert len(get_model_services()) == 2
def test_get_services_for_user(notify_api, notify_db, notify_db_session, sample_service):
    assert Service.query.count() == 1
    service_name = "Random service"
    second_user = create_sample_user(notify_db, notify_db_session, '*****@*****.**')
    create_sample_service(notify_db, notify_db_session, service_name='another service', user=second_user)

    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_service.users[0])
    assert Service.query.count() == 3
    services = get_model_services(user_id=sample_service.users[0].id)
    assert len(services) == 2
    assert service_name in [x.name for x in services]
    assert 'Sample service' in [x.name for x in services]
def test_get_api_keys_should_return_all_keys_for_service(notify_api, notify_db,
                                                         notify_db_session,
                                                         sample_api_key):
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            another_user = create_user(notify_db, notify_db_session, email='*****@*****.**')
            another_service = create_sample_service(notify_db, notify_db_session, service_name='another',
                                                    user=another_user)
            create_sample_api_key(notify_db, notify_db_session, service=another_service)
            api_key2 = ApiKey(**{'service_id': sample_api_key.service_id, 'name': 'second_api_key'})
            api_key3 = ApiKey(**{'service_id': sample_api_key.service_id, 'name': 'third_api_key',
                                 'expiry_date': datetime.utcnow() + timedelta(hours=-1)})
            save_model_api_key(api_key2)
            save_model_api_key(api_key3)
            assert ApiKey.query.count() == 4

            auth_header = create_authorization_header(path=url_for('service.get_api_keys',
                                                                   service_id=sample_api_key.service_id),
                                                      method='GET')
            response = client.get(url_for('service.get_api_keys',
                                          service_id=sample_api_key.service_id),
                                  headers=[('Content-Type', 'application/json'), auth_header])
            assert response.status_code == 200
            json_resp = json.loads(response.get_data(as_text=True))
            assert len(json_resp['apiKeys']) == 3
def test_should_allow_api_call_if_under_day_limit_regardless_of_type(
        notify_db,
        notify_db_session,
        notify_api,
        sample_user,
        mocker,
        restricted):
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async')
            mocker.patch('app.encryption.encrypt', return_value="something_encrypted")

            service = create_sample_service(notify_db, notify_db_session, limit=2, restricted=restricted)
            email_template = create_sample_email_template(notify_db, notify_db_session, service=service)
            sms_template = create_sample_template(notify_db, notify_db_session, service=service)
            create_sample_notification(notify_db, notify_db_session, template=email_template, service=service)

            data = {
                'to': sample_user.mobile_number,
                'template': str(sms_template.id)
            }

            auth_header = create_authorization_header(service_id=service.id)

            response = client.post(
                path='/notifications/sms',
                data=json.dumps(data),
                headers=[('Content-Type', 'application/json'), auth_header])

            assert response.status_code == 201
def test_get_api_keys_should_return_all_keys_for_service(notify_api, notify_db,
                                                         notify_db_session,
                                                         sample_api_key):
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            another_user = create_user(notify_db, notify_db_session, email='*****@*****.**')

            another_service = create_sample_service(
                notify_db,
                notify_db_session,
                service_name='another',
                user=another_user,
                email_from='another'
            )
            # key for another service
            create_sample_api_key(notify_db, notify_db_session, service=another_service)

            # this service already has one key, add two more, one expired
            create_sample_api_key(notify_db, notify_db_session, service=sample_api_key.service)
            one_to_expire = create_sample_api_key(notify_db, notify_db_session, service=sample_api_key.service)
            expire_api_key(service_id=one_to_expire.service_id, api_key_id=one_to_expire.id)

            assert ApiKey.query.count() == 4

            auth_header = create_authorization_header()
            response = client.get(url_for('service.get_api_keys',
                                          service_id=sample_api_key.service_id),
                                  headers=[('Content-Type', 'application/json'), auth_header])
            assert response.status_code == 200
            json_resp = json.loads(response.get_data(as_text=True))
            assert len(json_resp['apiKeys']) == 3
Beispiel #8
0
def test_send_notification_to_service_users_sends_to_active_users_only(
        notify_db, notify_db_session, mocker):
    mocker.patch("app.service.sender.send_notification_to_queue")

    create_notify_service(notify_db, notify_db_session)

    first_active_user = create_user(email="*****@*****.**", state="active")
    second_active_user = create_user(email="*****@*****.**", state="active")
    pending_user = create_user(email="*****@*****.**", state="pending")
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=first_active_user)
    dao_add_user_to_service(service, second_active_user)
    dao_add_user_to_service(service, pending_user)
    template = create_template(service, template_type=EMAIL_TYPE)

    send_notification_to_service_users(service_id=service.id,
                                       template_id=template.id)
    notifications = Notification.query.all()
    notifications_recipients = [
        notification.to for notification in notifications
    ]

    assert Notification.query.count() == 2
    assert pending_user.email_address not in notifications_recipients
    assert first_active_user.email_address in notifications_recipients
    assert second_active_user.email_address in notifications_recipients
def test_should_block_api_call_if_over_day_limit_for_restricted_service(
        notify_db,
        notify_db_session,
        notify_api,
        mocker):
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async')
            mocker.patch('app.encryption.encrypt', return_value="something_encrypted")

            service = create_sample_service(notify_db, notify_db_session, limit=1, restricted=True)
            email_template = create_sample_email_template(notify_db, notify_db_session, service=service)
            create_sample_notification(
                notify_db, notify_db_session, template=email_template, service=service, created_at=datetime.utcnow()
            )

            data = {
                'to': '*****@*****.**',
                'template': str(email_template.id)
            }

            auth_header = create_authorization_header(service_id=service.id)

            response = client.post(
                path='/notifications/email',
                data=json.dumps(data),
                headers=[('Content-Type', 'application/json'), auth_header])
            json.loads(response.get_data(as_text=True))

            assert response.status_code == 429
def test_get_api_keys_should_return_all_keys_for_service(
        notify_api, notify_db, notify_db_session, sample_api_key):
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            another_user = create_user(email='*****@*****.**')

            another_service = create_sample_service(notify_db,
                                                    notify_db_session,
                                                    service_name='another',
                                                    user=another_user,
                                                    email_from='another')
            # key for another service
            create_sample_api_key(notify_db,
                                  notify_db_session,
                                  service=another_service)

            # this service already has one key, add two more, one expired
            create_sample_api_key(notify_db,
                                  notify_db_session,
                                  service=sample_api_key.service)
            one_to_expire = create_sample_api_key(
                notify_db, notify_db_session, service=sample_api_key.service)
            expire_api_key(service_id=one_to_expire.service_id,
                           api_key_id=one_to_expire.id)

            assert ApiKey.query.count() == 4

            auth_header = create_authorization_header()
            response = client.get(
                url_for('service.get_api_keys',
                        service_id=sample_api_key.service_id),
                headers=[('Content-Type', 'application/json'), auth_header])
            assert response.status_code == 200
            json_resp = json.loads(response.get_data(as_text=True))
            assert len(json_resp['apiKeys']) == 3
def test_get_user_service(notify_api, notify_db, notify_db_session, sample_service, sample_admin_service_id):
    """
    Tests GET endpoint "/<user_id>/service/<service_id>" to retrieve a service for a user.
    """
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            user = User.query.first()
            another_name = "another name"
            another_service = create_sample_service(
                notify_db,
                notify_db_session,
                service_name=another_name,
                user=user)
            assert Service.query.count() == 3
            auth_header = create_authorization_header(service_id=sample_admin_service_id,
                                                      path=url_for('user.get_service_by_user_id', user_id=user.id,
                                                                   service_id=another_service.id),
                                                      method='GET')
            resp = client.get(
                url_for('user.get_service_by_user_id', user_id=user.id, service_id=another_service.id),
                headers=[('Content-Type', 'application/json'), auth_header])
            assert resp.status_code == 200
            json_resp = json.loads(resp.get_data(as_text=True))
            assert json_resp['data']['name'] == another_name
            assert json_resp['data']['id'] == another_service.id
def test_get_user_service(notify_api, notify_db, notify_db_session, sample_user):
    assert Service.query.count() == 0
    service_name = "Random service"
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_user)
    assert get_model_services(service_id=sample_service.id).name == service_name
    assert Service.query.count() == 1
def test_get_service_for_user(notify_api, notify_db, notify_db_session, sample_service):
    second_user = create_sample_user(notify_db, notify_db_session, '*****@*****.**')
    create_sample_service(notify_db, notify_db_session, service_name='Second Service', user=second_user)
    create_sample_service(notify_db, notify_db_session, service_name='Another Service', user=sample_service.users[0])
    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            auth_header = create_authorization_header(
                path='/service',
                method='GET')
            resp = client.get('/service?user_id={}'.format(sample_service.users[0].id),
                              headers=[auth_header])
            assert resp.status_code == 200
            json_resp = json.loads(resp.get_data(as_text=True))
            assert len(json_resp['data']) == 2
            print(x for x in json_resp['data'])
            assert 'Another Service' in [x.get('name') for x in json_resp['data']]
            assert 'Sample service' in [x.get('name') for x in json_resp['data']]
            assert 'Second Service' not in [x.get('name') for x in json_resp['data']]
def test_get_services_for_user(notify_api, notify_db, notify_db_session,
                               sample_service):
    assert Service.query.count() == 1
    service_name = "Random service"
    second_user = create_sample_user(notify_db, notify_db_session,
                                     '*****@*****.**')
    create_sample_service(notify_db,
                          notify_db_session,
                          service_name='another service',
                          user=second_user)

    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_service.users[0])
    assert Service.query.count() == 3
    services = get_model_services(user_id=sample_service.users[0].id)
    assert len(services) == 2
    assert service_name in [x.name for x in services]
    assert 'Sample service' in [x.name for x in services]
def test_get_user_service(notify_api, notify_db, notify_db_session,
                          sample_user):
    assert Service.query.count() == 0
    service_name = "Random service"
    sample_service = create_sample_service(notify_db,
                                           notify_db_session,
                                           service_name=service_name,
                                           user=sample_user)
    assert get_model_services(
        service_id=sample_service.id).name == service_name
    assert Service.query.count() == 1
Beispiel #16
0
def test_send_notification_to_service_users_sends_to_queue(
        notify_db, notify_db_session, sample_user, mocker):
    send_mock = mocker.patch("app.service.sender.send_notification_to_queue")

    create_notify_service(notify_db, notify_db_session)
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=sample_user)
    template = create_template(service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(service_id=service.id,
                                       template_id=template.id)

    assert send_mock.called
    assert send_mock.call_count == 1
def test_should_send_notification_to_whitelist_recipient(
    client,
    notify_db,
    notify_db_session,
    notification_type,
    to,
    _create_sample_template,
    key_type,
    service_restricted,
    mocker
):
    service = create_sample_service(notify_db, notify_db_session, limit=2, restricted=service_restricted)
    apply_async = mocker.patch('app.celery.provider_tasks.deliver_{}.apply_async'.format(notification_type))
    template = _create_sample_template(notify_db, notify_db_session, service=service)
    if notification_type == 'sms':
        service_whitelist = create_sample_service_whitelist(notify_db, notify_db_session,
                                                            service=service, mobile_number=to)
    elif notification_type == 'email':
        service_whitelist = create_sample_service_whitelist(notify_db, notify_db_session,
                                                            service=service, email_address=to)

    assert service_whitelist.service_id == service.id
    assert to in [member.recipient for member in service.whitelist]

    create_sample_notification(notify_db, notify_db_session, template=template, service=service)

    data = {
        'to': to,
        'template': str(template.id)
    }

    sample_key = create_sample_api_key(notify_db, notify_db_session, service, key_type=key_type)
    auth_header = create_jwt_token(secret=sample_key.unsigned_secret, client_id=str(sample_key.service_id))

    response = client.post(
        path='/notifications/{}'.format(notification_type),
        data=json.dumps(data),
        headers=[('Content-Type', 'application/json'), ('Authorization', 'Bearer {}'.format(auth_header))])

    json_resp = json.loads(response.get_data(as_text=True))
    assert response.status_code == 201
    assert json_resp['data']['notification']['id']
    assert json_resp['data']['body'] == template.content
    assert json_resp['data']['template_version'] == template.version
    assert apply_async.called
def test_should_not_send_notification_to_non_whitelist_recipient_in_trial_mode(
    client,
    notify_db,
    notify_db_session,
    notification_type,
    to,
    _create_sample_template,
    key_type,
    mocker
):
    service = create_sample_service(notify_db, notify_db_session, limit=2, restricted=True)
    service_whitelist = create_sample_service_whitelist(notify_db, notify_db_session, service=service)

    apply_async = mocker.patch('app.celery.provider_tasks.deliver_{}.apply_async'.format(notification_type))
    template = _create_sample_template(notify_db, notify_db_session, service=service)
    assert service_whitelist.service_id == service.id
    assert to not in [member.recipient for member in service.whitelist]

    create_sample_notification(notify_db, notify_db_session, template=template, service=service)

    data = {
        'to': to,
        'template': str(template.id)
    }

    api_key = create_sample_api_key(notify_db, notify_db_session, service, key_type=key_type)
    auth_header = create_jwt_token(secret=api_key.unsigned_secret, client_id=str(api_key.service_id))

    response = client.post(
        path='/notifications/{}'.format(notification_type),
        data=json.dumps(data),
        headers=[('Content-Type', 'application/json'), ('Authorization', 'Bearer {}'.format(auth_header))])

    expected_response_message = (
        'Can’t send to this recipient when service is in trial mode '
        '– see https://www.notifications.service.gov.uk/trial-mode'
    ) if key_type == KEY_TYPE_NORMAL else ('Can’t send to this recipient using a team-only API key')

    json_resp = json.loads(response.get_data(as_text=True))
    assert response.status_code == 400
    assert json_resp['result'] == 'error'
    assert expected_response_message in json_resp['message']['to']
    apply_async.assert_not_called()
Beispiel #19
0
def test_send_notification_to_service_users_includes_user_fields_in_personalisation(
        notify_db, notify_db_session, sample_user, mocker):
    persist_mock = mocker.patch('app.service.sender.persist_notification')
    mocker.patch('app.service.sender.send_notification_to_queue')

    create_notify_service(notify_db, notify_db_session)
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=sample_user)
    template = create_template(service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(
        service_id=service.id,
        template_id=template.id,
        include_user_fields=['name', 'email_address', 'state'])

    persist_call = persist_mock.call_args_list[0][1]

    assert len(persist_mock.call_args_list) == 1
    assert persist_call['personalisation'] == {
        'name': sample_user.name,
        'email_address': sample_user.email_address,
        'state': sample_user.state,
    }
Beispiel #20
0
def test_send_notification_to_service_users_includes_user_fields_in_personalisation(
        notify_db, notify_db_session, sample_user, mocker):
    persist_mock = mocker.patch("app.service.sender.persist_notification")
    mocker.patch("app.service.sender.send_notification_to_queue")

    create_notify_service(notify_db, notify_db_session)
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=sample_user)
    template = create_template(service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(
        service_id=service.id,
        template_id=template.id,
        include_user_fields=["name", "email_address", "state"],
    )

    persist_call = persist_mock.call_args_list[0][1]

    assert len(persist_mock.call_args_list) == 1
    assert persist_call["personalisation"] == {
        "name": sample_user.name,
        "email_address": sample_user.email_address,
        "state": sample_user.state,
    }
Beispiel #21
0
def test_send_notification_to_service_users_persists_notifications_correctly(
        notify_db, notify_db_session, notification_type, sample_user, mocker):
    mocker.patch("app.service.sender.send_notification_to_queue")

    notify_service, user = create_notify_service(notify_db, notify_db_session)
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=sample_user)
    template = create_template(service, template_type=notification_type)
    send_notification_to_service_users(service_id=service.id,
                                       template_id=template.id)
    to = sample_user.email_address if notification_type == EMAIL_TYPE else sample_user.mobile_number

    notification = Notification.query.one()

    assert Notification.query.count() == 1
    assert notification.to == to
    assert str(
        notification.service_id) == current_app.config["NOTIFY_SERVICE_ID"]
    assert notification.template.id == template.id
    assert notification.template.template_type == notification_type
    assert notification.notification_type == notification_type
    assert notification.reply_to_text == notify_service.get_default_reply_to_email_address(
    )