def test_should_raise_exception_if_raise_set_to_true(app):
    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception('get failed'))
    redis_client.redis_store.set = Mock(side_effect=Exception('set failed'))
    redis_client.redis_store.incr = Mock(side_effect=Exception('inc failed'))
    redis_client.redis_store.pipeline = Mock(
        side_effect=Exception('pipeline failed'))
    redis_client.redis_store.expire = Mock(
        side_effect=Exception('expire failed'))
    redis_client.redis_store.delete = Mock(
        side_effect=Exception('delete failed'))
    with pytest.raises(Exception) as e:
        redis_client.get('test', raise_exception=True)
    assert str(e.value) == 'get failed'
    with pytest.raises(Exception) as e:
        redis_client.set('test', 'test', raise_exception=True)
    assert str(e.value) == 'set failed'
    with pytest.raises(Exception) as e:
        redis_client.incr('test', raise_exception=True)
    assert str(e.value) == 'inc failed'
    with pytest.raises(Exception) as e:
        redis_client.exceeded_rate_limit('test',
                                         100,
                                         200,
                                         raise_exception=True)
    assert str(e.value) == 'pipeline failed'
    with pytest.raises(Exception) as e:
        redis_client.expire('test', 0, raise_exception=True)
    assert str(e.value) == 'expire failed'
    with pytest.raises(Exception) as e:
        redis_client.delete('test', raise_exception=True)
    assert str(e.value) == 'delete failed'
def test_should_not_raise_exception_if_raise_set_to_false(app, caplog, mocker):
    mock_logger = mocker.patch('flask.Flask.logger')

    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception())
    redis_client.redis_store.set = Mock(side_effect=Exception())
    redis_client.redis_store.incr = Mock(side_effect=Exception())
    redis_client.redis_store.pipeline = Mock(side_effect=Exception())
    redis_client.redis_store.expire = Mock(side_effect=Exception())
    redis_client.redis_store.delete = Mock(side_effect=Exception())
    assert redis_client.get('get_key') is None
    assert redis_client.set('set_key', 'set_value') is None
    assert redis_client.incr('incr_key') is None
    assert redis_client.exceeded_rate_limit('rate_limit_key', 100,
                                            100) is False
    assert redis_client.expire('expire_key', 100) is None
    assert redis_client.delete('delete_key') is None
    assert redis_client.delete('a', 'b', 'c') is None
    assert mock_logger.mock_calls == [
        call.exception('Redis error performing get on get_key'),
        call.exception('Redis error performing set on set_key'),
        call.exception('Redis error performing incr on incr_key'),
        call.exception(
            'Redis error performing rate-limit-pipeline on rate_limit_key'),
        call.exception('Redis error performing expire on expire_key'),
        call.exception('Redis error performing delete on delete_key'),
        call.exception('Redis error performing delete on a, b, c'),
    ]
예제 #3
0
def test_should_not_raise_exception_if_raise_set_to_false(app):
    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception())
    redis_client.redis_store.set = Mock(side_effect=Exception())
    redis_client.redis_store.incr = Mock(side_effect=Exception())
    redis_client.redis_store.pipeline = Mock(side_effect=Exception())
    assert redis_client.get('test') is None
    assert redis_client.set('test', 'test') is None
    assert redis_client.incr('test') is None
    assert redis_client.exceeded_rate_limit('test', 100, 100) is False
예제 #4
0
class NotifyAdminAPIClient(BaseAPIClient):

    redis_client = RedisClient()

    def init_app(self, app):
        self.base_url = app.config['API_HOST_NAME']
        self.service_id = app.config['ADMIN_CLIENT_USER_NAME']
        self.api_key = app.config['ADMIN_CLIENT_SECRET']
        self.route_secret = app.config['ROUTE_SECRET_KEY_1']
        self.redis_client.init_app(app)
        self.redis_client.redis_store.decode_responses = True

    def generate_headers(self, api_token):
        headers = {
            "Content-type": "application/json",
            "Authorization": "Bearer {}".format(api_token),
            "X-Custom-Forwarder": self.route_secret,
            "User-agent": "NOTIFY-API-PYTHON-CLIENT/{}".format(__version__)
        }
        return self._add_request_id_header(headers)

    @staticmethod
    def _add_request_id_header(headers):
        if not has_request_context():
            return headers
        headers['X-B3-TraceId'] = request.request_id
        headers['X-B3-SpanId'] = request.span_id
        return headers

    def check_inactive_service(self):
        # this file is imported in app/__init__.py before current_service is initialised, so need to import later
        # to prevent cyclical imports
        from app import current_service

        # if the current service is inactive and the user isn't a platform admin, we should block them from making any
        # stateful modifications to that service
        if current_service and not current_service.active and not current_user.platform_admin:
            abort(403)

    def post(self, *args, **kwargs):
        self.check_inactive_service()
        return super().post(*args, **kwargs)

    def put(self, *args, **kwargs):
        self.check_inactive_service()
        return super().put(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self.check_inactive_service()
        return super().delete(*args, **kwargs)
def build_redis_client(app, mocked_redis_pipeline, mocker):
    redis_client = RedisClient()
    redis_client.init_app(app)
    mocker.patch.object(redis_client.redis_store, 'get', return_value=100)
    mocker.patch.object(redis_client.redis_store, 'set')
    mocker.patch.object(redis_client.redis_store, 'hincrby')
    mocker.patch.object(redis_client.redis_store, 'hgetall',
                        return_value={b'template-1111': b'8', b'template-2222': b'8'})
    mocker.patch.object(redis_client.redis_store, 'hmset')
    mocker.patch.object(redis_client.redis_store, 'expire')
    mocker.patch.object(redis_client.redis_store, 'delete')
    mocker.patch.object(redis_client.redis_store, 'pipeline', return_value=mocked_redis_pipeline)

    return redis_client
예제 #6
0
파일: __init__.py 프로젝트: malimu/notify
)
twilio_sms_client = TwilioSMSClient(
    account_sid=os.getenv('TWILIO_ACCOUNT_SID'),
    auth_token=os.getenv('TWILIO_AUTH_TOKEN'),
    from_number=os.getenv('TWILIO_FROM_NUMBER'),
)
smtp_client = SMTPClient(
    addr=os.getenv('SMTP_ADDR'),
    user=os.getenv('SMTP_USER'),
    password=os.getenv('SMTP_PASSWORD'),
)
aws_ses_client = AwsSesClient()
encryption = Encryption()
deskpro_client = DeskproClient()
statsd_client = StatsdClient()
redis_store = RedisClient()
performance_platform_client = PerformancePlatformClient()

clients = Clients()

api_user = LocalProxy(lambda: _request_ctx_stack.top.api_user)
authenticated_service = LocalProxy(
    lambda: _request_ctx_stack.top.authenticated_service)


def create_app(application):
    from app.config import configs

    notify_environment = os.environ['NOTIFY_ENVIRONMENT']

    application.config.from_object(configs[notify_environment])
예제 #7
0
from notifications_utils.clients.antivirus.antivirus_client import (
    AntivirusClient, )
from notifications_utils.clients.redis.redis_client import RedisClient
from notifications_utils.clients.statsd.statsd_client import StatsdClient
from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient

antivirus_client = AntivirusClient()
statsd_client = StatsdClient()
zendesk_client = ZendeskClient()
redis_client = RedisClient()
예제 #8
0
def mocked_redis_client(app):
    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    return redis_client