def test_send_broadcast_event_does_nothing_if_cbc_proxy_disabled(mocker, notify_api):
    mock_send_broadcast_provider_message = mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message',
    )

    event_id = uuid.uuid4()
    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']), set_config(notify_api, 'CBC_PROXY_ENABLED', False):
        send_broadcast_event(event_id)

    assert mock_send_broadcast_provider_message.apply_async.called is False
def test_trigger_link_does_nothing_if_cbc_proxy_disabled(mocker, notify_api):
    mock_trigger_link_test = mocker.patch(
        'app.celery.scheduled_tasks.trigger_link_test', )

    with set_config(notify_api, 'ENABLED_CBCS',
                    ['ee', 'vodafone']), set_config(notify_api,
                                                    'CBC_PROXY_ENABLED',
                                                    False):
        trigger_link_tests()

    assert mock_trigger_link_test.called is False
Exemple #3
0
def test_send_broadcast_provider_message_does_nothing_if_cbc_proxy_disabled(mocker, notify_api, sample_template):
    mock_proxy_client_getter = mocker.patch(
        'app.celery.broadcast_message_tasks.cbc_proxy_client',
    )
    mock_client = Mock()
    mock_proxy_client_getter.get_proxy.return_value = mock_client

    broadcast_message = create_broadcast_message(sample_template)
    broadcast_event = create_broadcast_event(broadcast_message, message_type='alert')
    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']), set_config(notify_api, 'CBC_PROXY_ENABLED', False):
        send_broadcast_provider_message(broadcast_event.id, 'ee')

    assert mock_client.create_and_send_broadcast.called is False
Exemple #4
0
def test_send_broadcast_event_only_sends_to_one_provider_if_set_on_service(
        mocker, notify_db, notify_api, sample_service):
    settings = ServiceBroadcastSettings(service=sample_service,
                                        channel="test",
                                        provider="vodafone")
    notify_db.session.add(settings)

    template = create_template(sample_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(
        template, status=BroadcastStatusType.BROADCASTING)
    event = create_broadcast_event(broadcast_message)

    mock_send_broadcast_provider_message = mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message', )

    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']):
        send_broadcast_event(event.id)

    assert mock_send_broadcast_provider_message.apply_async.call_args_list == [
        call(kwargs={
            'broadcast_event_id': event.id,
            'provider': 'vodafone'
        },
             queue='broadcast-tasks')
    ]
Exemple #5
0
def test_send_broadcast_event_creates_zendesk_p1(mocker, notify_api, sample_broadcast_service):
    template = create_template(sample_broadcast_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(
        template,
        status=BroadcastStatusType.BROADCASTING,
        areas={'areas': ['wd20-S13002775', 'wd20-S13002773'], 'simple_polygons': []},
    )
    event = create_broadcast_event(broadcast_message)
    mock_create_ticket = mocker.patch("app.celery.broadcast_message_tasks.zendesk_client.create_ticket")

    mocker.patch('app.celery.broadcast_message_tasks.send_broadcast_provider_message')

    with set_config(notify_api, 'NOTIFY_ENVIRONMENT', 'live'):
        send_broadcast_event(event.id)

    assert mock_create_ticket.call_count == 1
    zendesk_args = mock_create_ticket.call_args[1]
    assert zendesk_args['p1'] is True
    assert zendesk_args['ticket_type'] == 'incident'

    assert str(broadcast_message.id) in zendesk_args['message']
    assert 'channel severe' in zendesk_args['message']
    assert "areas ['wd20-S13002775', 'wd20-S13002773']" in zendesk_args['message']
    # the start of the content from the broadcast template
    assert "Dear Sir/Madam" in zendesk_args['message']
def test_send_broadcast_event_queues_up_for_active_providers(
        mocker, notify_api, sample_service):
    template = create_template(sample_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(
        template, status=BroadcastStatusType.BROADCASTING)
    event = create_broadcast_event(broadcast_message)

    mock_send_broadcast_provider_message = mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message', )

    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']):
        send_broadcast_event(event.id)

    assert mock_send_broadcast_provider_message.apply_async.call_args_list == [
        call(kwargs={
            'broadcast_event_id': event.id,
            'provider': 'ee'
        },
             queue='notify-internal-tasks'),
        call(kwargs={
            'broadcast_event_id': event.id,
            'provider': 'vodafone'
        },
             queue='notify-internal-tasks')
    ]
def test_most_recent_inbound_sms_paginates_properly(notify_api, sample_service):
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 1', created_at=datetime(2017, 1, 1))
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 2', created_at=datetime(2017, 1, 2))
    create_inbound_sms(sample_service, user_number='+447800900222', content='222 1', created_at=datetime(2017, 1, 3))
    create_inbound_sms(sample_service, user_number='+447800900222', content='222 2', created_at=datetime(2017, 1, 4))
    create_inbound_sms(sample_service, user_number='+447800900333', content='333 1', created_at=datetime(2017, 1, 5))
    create_inbound_sms(sample_service, user_number='+447800900333', content='333 2', created_at=datetime(2017, 1, 6))
    create_inbound_sms(sample_service, user_number='+447800900444', content='444 1', created_at=datetime(2017, 1, 7))
    create_inbound_sms(sample_service, user_number='+447800900444', content='444 2', created_at=datetime(2017, 1, 8))

    with set_config(notify_api, 'PAGE_SIZE', 2):
        # first page has most recent 444 and 333
        res = dao_get_paginated_most_recent_inbound_sms_by_user_number_for_service(sample_service.id, page=1)
        assert len(res.items) == 2
        assert res.has_next is True
        assert res.per_page == 2
        assert res.items[0].content == '444 2'
        assert res.items[1].content == '333 2'

        # second page has no 444 or 333 - just most recent 222 and 111
        res = dao_get_paginated_most_recent_inbound_sms_by_user_number_for_service(sample_service.id, page=2)
        assert len(res.items) == 2
        assert res.has_next is False
        assert res.items[0].content == '222 2'
        assert res.items[1].content == '111 2'
Exemple #8
0
def test_should_not_access_database_if_redis_disabled(notify_api, sample_service, mocker):
    with set_config(notify_api, 'REDIS_ENABLED', False):
        db_mock = mocker.patch('app.notifications.validators.services_dao')

        check_service_over_daily_message_limit('normal', sample_service)

        assert db_mock.method_calls == []
Exemple #9
0
def test_send_broadcast_event_doesnt_p1_when_cancelling(
        mocker, notify_api, sample_broadcast_service):
    template = create_template(sample_broadcast_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(
        template,
        status=BroadcastStatusType.BROADCASTING,
        areas={
            'areas': ['wd20-S13002775', 'wd20-S13002773'],
            'simple_polygons': []
        },
    )
    create_broadcast_event(broadcast_message,
                           message_type=BroadcastEventMessageType.ALERT)
    cancel_event = create_broadcast_event(
        broadcast_message, message_type=BroadcastEventMessageType.CANCEL)
    mock_create_ticket = mocker.patch(
        "app.celery.broadcast_message_tasks.zendesk_client.create_ticket")

    mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message')

    with set_config(notify_api, 'NOTIFY_ENVIRONMENT', 'live'):
        send_broadcast_event(cancel_event.id)

    assert mock_create_ticket.called is False
Exemple #10
0
def test_populate_redis_template_usage_does_nothing_if_no_data(
        mocker, notify_api, sample_service):
    mock_redis = mocker.patch('app.commands.redis_store')
    with set_config(notify_api, 'REDIS_ENABLED', True):
        populate_redis_template_usage.callback.__wrapped__(
            sample_service.id, datetime.utcnow())

    assert mock_redis.mock_calls == []
def test_send_canary_to_cbc_proxy_does_nothing_if_cbc_proxy_disabled(
        mocker, notify_api):
    mock_send_canary = mocker.patch(
        'app.clients.cbc_proxy.CBCProxyCanary.send_canary', )

    with set_config(notify_api, 'CBC_PROXY_ENABLED', False):
        scheduled_tasks.send_canary_to_cbc_proxy()

    assert mock_send_canary.called is False
def test_update_letter_notifications_statuses_calls_with_correct_bucket_location(
        notify_api, mocker):
    s3_mock = mocker.patch('app.celery.tasks.s3.get_s3_object')

    with set_config(notify_api, 'NOTIFY_EMAIL_DOMAIN', 'foo.bar'):
        update_letter_notifications_statuses(
            filename='NOTIFY-20170823160812-RSP.TXT')
        s3_mock.assert_called_with(
            '{}-ftp'.format(current_app.config['NOTIFY_EMAIL_DOMAIN']),
            'NOTIFY-20170823160812-RSP.TXT')
Exemple #13
0
def test_most_recent_inbound_sms_only_returns_most_recent_for_each_number(
        notify_api, sample_service):
    create_inbound_sms(
        sample_service,
        user_number="447700900111",
        content="111 1",
        created_at=datetime(2017, 1, 1),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900111",
        content="111 2",
        created_at=datetime(2017, 1, 2),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900111",
        content="111 3",
        created_at=datetime(2017, 1, 3),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900111",
        content="111 4",
        created_at=datetime(2017, 1, 4),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900111",
        content="111 5",
        created_at=datetime(2017, 1, 5),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900222",
        content="222 1",
        created_at=datetime(2017, 1, 1),
    )
    create_inbound_sms(
        sample_service,
        user_number="447700900222",
        content="222 2",
        created_at=datetime(2017, 1, 2),
    )

    with set_config(notify_api, "PAGE_SIZE", 3):
        with freeze_time("2017-01-02"):
            res = dao_get_paginated_most_recent_inbound_sms_by_user_number_for_service(
                sample_service.id, limit_days=7, page=1)  # noqa

    assert len(res.items) == 2
    assert res.has_next is False
    assert res.per_page == 3
    assert res.items[0].content == "111 5"
    assert res.items[1].content == "222 2"
Exemple #14
0
def test_update_letter_notifications_statuses_calls_with_correct_bucket_location(
        notify_api, mocker):
    s3_mock = mocker.patch("app.celery.tasks.s3.get_s3_object")

    with set_config(notify_api, "NOTIFY_EMAIL_DOMAIN", "foo.bar"):
        update_letter_notifications_statuses(
            filename="NOTIFY-20170823160812-RSP.TXT")
        s3_mock.assert_called_with(
            "{}-ftp".format(current_app.config["NOTIFY_EMAIL_DOMAIN"]),
            "NOTIFY-20170823160812-RSP.TXT",
        )
def test_trigger_link_tests_calls_for_all_providers(mocker, notify_api):
    mock_trigger_link_test = mocker.patch(
        'app.celery.scheduled_tasks.trigger_link_test', )

    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']):
        trigger_link_tests()

    assert mock_trigger_link_test.apply_async.call_args_list == [
        call(kwargs={'provider': 'ee'}, queue='notify-internal-tasks'),
        call(kwargs={'provider': 'vodafone'}, queue='notify-internal-tasks')
    ]
Exemple #16
0
def test_populate_redis_template_usage_does_nothing_if_redis_disabled(
        mocker, notify_api, sample_service):
    mock_redis = mocker.patch('app.commands.redis_store')
    with set_config(notify_api, 'REDIS_ENABLED', False):
        with pytest.raises(SystemExit) as exit_signal:
            populate_redis_template_usage.callback.__wrapped__(
                sample_service.id, datetime.utcnow())

    assert mock_redis.mock_calls == []
    # sys.exit with nonzero exit code
    assert exit_signal.value.code != 0
def test_authentication_returns_error_when_admin_client_has_no_secrets(client):
    api_secret = current_app.config.get('ADMIN_CLIENT_SECRET')
    api_service_id = current_app.config.get('ADMIN_CLIENT_USER_NAME')
    token = create_jwt_token(secret=api_secret, client_id=api_service_id)
    with set_config(client.application, 'ADMIN_CLIENT_SECRET', ''):
        response = client.get(
            '/service', headers={'Authorization': 'Bearer {}'.format(token)})
    assert response.status_code == 403
    error_message = json.loads(response.get_data())
    assert error_message['message'] == {
        "token": ["Invalid token: signature, api token is not valid"]
    }
def test_firetext_inbound_sms_auth(notify_db_session, notify_api, client, mocker, auth, keys, status_code):
    mocker.patch("app.notifications.receive_notifications.tasks.send_inbound_sms_to_service.apply_async")

    create_service_with_inbound_number(
        service_name='b', inbound_number='07111111111', service_permissions=[EMAIL_TYPE, SMS_TYPE, INBOUND_SMS_TYPE]
    )

    data = "source=07999999999&destination=07111111111&message=this is a message&time=2017-01-01 12:00:00"

    with set_config(notify_api, 'FIRETEXT_INBOUND_SMS_AUTH', keys):
        response = firetext_post(client, data, auth=bool(auth), password=auth)
        assert response.status_code == status_code
def test_get_jobs_accepts_page_parameter(admin_request, sample_template):
    create_10_jobs(sample_template)

    with set_config(admin_request.app, 'PAGE_SIZE', 2):
        resp_json = admin_request.get('job.get_jobs_by_service', service_id=sample_template.service_id, page=2)

    assert resp_json['data'][0]['created_at'] == '2015-01-01T08:00:00+00:00'
    assert resp_json['data'][1]['created_at'] == '2015-01-01T07:00:00+00:00'
    assert resp_json['page_size'] == 2
    assert resp_json['total'] == 10
    assert 'links' in resp_json
    assert set(resp_json['links'].keys()) == {'prev', 'next', 'last'}
Exemple #20
0
def test_authentication_returns_error_when_admin_client_has_no_secrets(client):
    api_secret = current_app.config.get('API_INTERNAL_SECRETS')[0]
    api_service_id = current_app.config.get('ADMIN_CLIENT_USER_NAME')
    token = create_jwt_token(secret=api_secret, client_id=api_service_id)
    with set_config(client.application, 'API_INTERNAL_SECRETS', []):
        response = client.get(
            '/service', headers={'Authorization': 'Bearer {}'.format(token)})
    assert response.status_code == 401
    error_message = json.loads(response.get_data())
    assert error_message['message'] == {
        "token": ["Unauthorized: admin authentication token not found"]
    }
Exemple #21
0
def test_get_uploads_should_paginate(admin_request, sample_template):
    for _ in range(10):
        create_job(sample_template)

    with set_config(admin_request.app, 'PAGE_SIZE', 2):
        resp_json = admin_request.get('upload.get_uploads_by_service',
                                      service_id=sample_template.service_id)

    assert len(resp_json['data']) == 2
    assert resp_json['page_size'] == 2
    assert resp_json['total'] == 10
    assert 'links' in resp_json
    assert set(resp_json['links'].keys()) == {'next', 'last'}
def test_should_allow_valid_token_for_request_with_path_params_for_admin_url_with_second_secret(client):
    with set_config(client.application, 'API_INTERNAL_SECRETS', ["secret1", "secret2"]):
        token = create_jwt_token(
            current_app.config['API_INTERNAL_SECRETS'][0], current_app.config['ADMIN_CLIENT_USER_NAME']
        )
        response = client.get('/service', headers={'Authorization': 'Bearer {}'.format(token)})
        assert response.status_code == 200

        token = create_jwt_token(
            current_app.config['API_INTERNAL_SECRETS'][1], current_app.config['ADMIN_CLIENT_USER_NAME']
        )
        response = client.get('/service', headers={'Authorization': 'Bearer {}'.format(token)})
        assert response.status_code == 200
Exemple #23
0
def test_get_jobs_should_paginate(admin_request, sample_template):
    create_10_jobs(sample_template)

    with set_config(admin_request.app, "PAGE_SIZE", 2):
        resp_json = admin_request.get("job.get_jobs_by_service",
                                      service_id=sample_template.service_id)

    assert resp_json["data"][0]["created_at"] == "2015-01-01T10:00:00+00:00"
    assert resp_json["data"][1]["created_at"] == "2015-01-01T09:00:00+00:00"
    assert resp_json["page_size"] == 2
    assert resp_json["total"] == 10
    assert "links" in resp_json
    assert set(resp_json["links"].keys()) == {"next", "last"}
Exemple #24
0
def test_send_broadcast_event_does_nothing_if_provider_set_on_service_isnt_enabled_globally(
        mocker, notify_db, notify_api, sample_broadcast_service):
    sample_broadcast_service.allowed_broadcast_provider = "three"
    template = create_template(sample_broadcast_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(
        template, status=BroadcastStatusType.BROADCASTING)
    event = create_broadcast_event(broadcast_message)

    mock_send_broadcast_provider_message = mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message', )

    with set_config(notify_api, 'ENABLED_CBCS', ['ee', 'vodafone']):
        send_broadcast_event(event.id)

    assert mock_send_broadcast_provider_message.apply_async.called is False
def test_two_factor_email_link_has_expired(app_, valid_token, client,
                                           mock_send_verify_code, fake_uuid):

    with set_config(app_, 'EMAIL_2FA_EXPIRY_SECONDS', -1):
        response = client.get(
            url_for_endpoint_with_token('main.two_factor_email',
                                        token=valid_token),
            follow_redirects=True,
        )

    assert response.status_code == 200
    page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')

    assert page.h1.text.strip() == 'The link has expired'
    mock_send_verify_code.assert_not_called
Exemple #26
0
def test_generate_headers_sets_standard_headers(app_):
    api_client = NotifyAdminAPIClient(SAMPLE_API_KEY, 'base_url')
    with set_config(app_, 'ROUTE_SECRET_KEY_1', 'proxy-secret'):
        api_client.init_app(app_)

    # with patch('app.notify_client.has_request_context', return_value=False):
    headers = api_client.generate_headers('api_token')

    assert set(headers.keys()) == {
        'Authorization', 'Content-type', 'User-agent', 'X-Custom-Forwarder'
    }
    assert headers['Authorization'] == 'Bearer api_token'
    assert headers['Content-type'] == 'application/json'
    assert headers['User-agent'].startswith('NOTIFY-API-PYTHON-CLIENT')
    assert headers['X-Custom-Forwarder'] == 'proxy-secret'
Exemple #27
0
def test_send_broadcast_event_doesnt_create_zendesk_on_staging(mocker, notify_api, sample_broadcast_service):
    template = create_template(sample_broadcast_service, BROADCAST_TYPE)
    broadcast_message = create_broadcast_message(template, status=BroadcastStatusType.BROADCASTING)
    event = create_broadcast_event(broadcast_message)
    mock_create_ticket = mocker.patch("app.celery.broadcast_message_tasks.zendesk_client.create_ticket")

    mock_send_broadcast_provider_message = mocker.patch(
        'app.celery.broadcast_message_tasks.send_broadcast_provider_message',
    )

    with set_config(notify_api, 'NOTIFY_ENVIRONMENT', 'staging'):
        send_broadcast_event(event.id)

    assert mock_send_broadcast_provider_message.apply_async.called is True
    assert mock_create_ticket.called is False
def test_most_recent_inbound_sms_only_returns_most_recent_for_each_number(notify_api, sample_service):
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 1', created_at=datetime(2017, 1, 1))
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 2', created_at=datetime(2017, 1, 2))
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 3', created_at=datetime(2017, 1, 3))
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 4', created_at=datetime(2017, 1, 4))
    create_inbound_sms(sample_service, user_number='+447800900111', content='111 5', created_at=datetime(2017, 1, 5))
    create_inbound_sms(sample_service, user_number='+447800900222', content='222 1', created_at=datetime(2017, 1, 1))
    create_inbound_sms(sample_service, user_number='+447800900222', content='222 2', created_at=datetime(2017, 1, 2))

    with set_config(notify_api, 'PAGE_SIZE', 3):
        res = dao_get_paginated_most_recent_inbound_sms_by_user_number_for_service(sample_service.id, page=1)

    assert len(res.items) == 2
    assert res.has_next is False
    assert res.per_page == 3
    assert res.items[0].content == '111 5'
    assert res.items[1].content == '222 2'
def test_two_factor_email_link_has_expired(app_, valid_token, client,
                                           mock_send_verify_code, fake_uuid):

    with set_config(app_, 'EMAIL_2FA_EXPIRY_SECONDS', -1):
        response = client.get(
            url_for('main.two_factor_email', token=valid_token),
            follow_redirects=True,
        )

    assert response.status_code == 200
    page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')

    assert normalize_spaces(
        page.select_one('.banner-dangerous').text
    ) == "The link in the email we sent you has expired. We’ve sent you a new one."
    assert page.h1.text.strip() == 'Email resent'
    mock_send_verify_code.assert_called_once_with(fake_uuid, 'email', None)
Exemple #30
0
def test_setting_broadcast_sets_organisation_if_config_value_set(
    mock_update_service_organisation,
    mock_update_service,
    platform_admin_client,
    fake_uuid,
):
    with set_config(platform_admin_client.application, 'BROADCAST_ORGANISATION_ID', fake_uuid):
        response = platform_admin_client.post(
            url_for('main.service_set_permission', service_id=SERVICE_ONE_ID, permission='broadcast'),
            data={'enabled': True}
        )
        assert response.status_code == 302
        assert response.location == url_for('main.service_settings', service_id=SERVICE_ONE_ID, _external=True)

    mock_update_service_organisation.assert_called_once_with(
        service_id=SERVICE_ONE_ID,
        org_id=fake_uuid
    )
def test_get_jobs_accepts_page_parameter(
        notify_db,
        notify_db_session,
        client,
        sample_template
):
    create_10_jobs(notify_db, notify_db_session, sample_template.service, sample_template)

    path = '/service/{}/job'.format(sample_template.service_id)
    auth_header = create_authorization_header(service_id=str(sample_template.service_id))

    with set_config(client.application, 'PAGE_SIZE', 2):
        response = client.get(path, headers=[auth_header], query_string={'page': 2})

    assert response.status_code == 200
    resp_json = json.loads(response.get_data(as_text=True))
    assert len(resp_json['data']) == 2
    assert resp_json['data'][0]['created_at'] == '2015-01-01T08:00:00+00:00'
    assert resp_json['data'][1]['created_at'] == '2015-01-01T07:00:00+00:00'
    assert resp_json['page_size'] == 2
    assert resp_json['total'] == 10
    assert 'links' in resp_json
    assert set(resp_json['links'].keys()) == {'prev', 'next', 'last'}