Ejemplo n.º 1
0
def initialize():
    global _initialized

    with _setup_lock:
        if _initialized:
            return

        _initialized = True

        try:
            register_serializers()
            install_middleware(
                'raven.contrib.django.middleware.SentryMiddleware',
                ('raven.contrib.django.middleware.SentryMiddleware',
                 'raven.contrib.django.middleware.SentryLogMiddleware'))
            install_middleware(
                'raven.contrib.django.middleware.DjangoRestFrameworkCompatMiddleware'
            )

            handler = CustomSentryDjangoHandler()
            handler.install()

            # instantiate client so hooks get registered
            get_client()  # NOQA
        except Exception:
            _initialized = False
Ejemplo n.º 2
0
def initialize():
    global _initialized

    with _setup_lock:
        if _initialized:
            return

        _initialized = True

        try:
            register_serializers()
            install_middleware(
                'raven.contrib.django.middleware.SentryMiddleware',
                (
                    'raven.contrib.django.middleware.SentryMiddleware',
                    'raven.contrib.django.middleware.SentryLogMiddleware'))
            install_middleware(
                'raven.contrib.django.middleware.DjangoRestFrameworkCompatMiddleware')

            handler = CustomSentryDjangoHandler()
            handler.install()

            # instantiate client so hooks get registered
            get_client()  # NOQA
        except Exception:
            _initialized = False
Ejemplo n.º 3
0
    def test_invalid_client(self):
        extra_settings = {"SENTRY_CLIENT": "raven.contrib.django.DjangoClient"}  # default
        # Should return fallback client (TempStoreClient)
        client = get_client("nonexistent.and.invalid")

        # client should be valid, and the same as with the next call.
        assert client is get_client()

        with Settings(**extra_settings):
            assert isinstance(get_client(), DjangoClient)
Ejemplo n.º 4
0
    def test_does_exclude_filtered_types(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info
        try:
            get_client().ignore_exceptions = set(['ValueError'])

            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Ejemplo n.º 5
0
    def test_does_exclude_filtered_types(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info
        try:
            get_client().ignore_exceptions = set(['ValueError'])

            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Ejemplo n.º 6
0
    def test_ignore_exceptions_with_module_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        if six.PY3:
            get_client().ignore_exceptions = set(['builtins.ValueError'])
        else:
            get_client().ignore_exceptions = set(['exceptions.ValueError'])

        sentry_exception_handler(request=self.request)

        assert not mock_capture.called
Ejemplo n.º 7
0
    def test_invalid_client(self):
        extra_settings = {
            'SENTRY_CLIENT': 'raven.contrib.django.DjangoClient',  # default
        }
        # Should return fallback client (MockClient)
        client = get_client('nonexistent.and.invalid')

        # client should be valid, and the same as with the next call.
        assert client is get_client()

        with Settings(**extra_settings):
            assert isinstance(get_client(), DjangoClient)
Ejemplo n.º 8
0
    def test_invalid_client(self):
        extra_settings = {
            'SENTRY_CLIENT': 'raven.contrib.django.DjangoClient',  # default
        }
        # Should return fallback client (MockClient)
        client = get_client('nonexistent.and.invalid')

        # client should be valid, and the same as with the next call.
        assert client is get_client()

        with Settings(**extra_settings):
            assert isinstance(get_client(), DjangoClient)
Ejemplo n.º 9
0
    def test_ignore_exceptions_with_expression_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        try:
            if six.PY3:
                get_client().ignore_exceptions = set(['builtins.*'])
            else:
                get_client().ignore_exceptions = set(['exceptions.*'])
            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Ejemplo n.º 10
0
    def test_ignore_exceptions_with_module_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        try:
            if six.PY3:
                get_client().ignore_exceptions = set(['builtins.ValueError'])
            else:
                get_client().ignore_exceptions = set(['exceptions.ValueError'])
            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
    def test_basic(self):
        with Settings(HEKA_CONF=self.HEKA_CONF,
                      HEKA=self.HEKA,
                      SENTRY_CLIENT=self.SENTRY_CLIENT,
                      SENTRY_DSN=DSN):

            self.raven = get_client()

            self.raven.capture('Message', message='foo')

            msgs = []
            for mdata in settings.HEKA.stream.msgs:
                h, m = decode_message(mdata)
                msgs.append(m)

            self.assertEquals(len(msgs), 1)
            event = self.raven.decode(msgs[0].payload)

            self.assertTrue('sentry.interfaces.Message' in event)
            message = event['sentry.interfaces.Message']
            self.assertEquals(message['message'], 'foo')
            self.assertEquals(event['level'], logging.ERROR)
            self.assertEquals(event['message'], 'foo')

            # The project_id must be extracted from the SENTRY_DSN
            # option
            self.assertEquals(event['project'], str(TESTING_PROJECT_ID))

            # This is different than the regular Django test as we are
            # *decoding* a serialized message - so instead of checking
            # for datetime, we expect a string
            self.assertTrue(isinstance(event['timestamp'], basestring))
Ejemplo n.º 12
0
    def test_basic(self):
        with Settings(HEKA_CONF=self.HEKA_CONF,
                      HEKA=self.HEKA,
                      SENTRY_CLIENT=self.SENTRY_CLIENT,
                      SENTRY_DSN=DSN):

            self.raven = get_client()

            self.raven.capture('Message', message='foo')

            msgs = []
            for mdata in settings.HEKA.stream.msgs:
                h, m = decode_message(mdata)
                msgs.append(m)

            self.assertEquals(len(msgs), 1)
            event = self.raven.decode(msgs[0].payload)

            self.assertTrue('sentry.interfaces.Message' in event)
            message = event['sentry.interfaces.Message']
            self.assertEquals(message['message'], 'foo')
            self.assertEquals(event['level'], logging.ERROR)
            self.assertEquals(event['message'], 'foo')

            # The project_id must be extracted from the SENTRY_DSN
            # option
            self.assertEquals(event['project'],
                    str(TESTING_PROJECT_ID))

            # This is different than the regular Django test as we are
            # *decoding* a serialized message - so instead of checking
            # for datetime, we expect a string
            self.assertTrue(isinstance(event['timestamp'], basestring))
Ejemplo n.º 13
0
def get_sentry_handler():
    # This should effectively make Tastypie do the same thing as
    # the error trapping in
    # raven.contrib.django.models:sentry_exception_handler
    from raven.contrib.django.models import get_client
    handler = SentryHandler(get_client())
    return handler
Ejemplo n.º 14
0
    def test_signal_integration(self):
        with Settings(METLOG_CONF=self.METLOG_CONF,
                      METLOG=self.METLOG,
                      SENTRY_CLIENT=self.SENTRY_CLIENT,
                      SENTRY_DSN=DSN):

            self.raven = get_client()

            try:
                int('hello')
            except:
                got_request_exception.send(sender=self.__class__, request=None)
            else:
                self.fail('Expected an exception.')

            msgs = settings.METLOG.sender.msgs

            self.assertEquals(len(msgs), 1)

            event = self.raven.decode(json.loads(msgs[0])['payload'])
            self.assertTrue('sentry.interfaces.Exception' in event)
            exc = event['sentry.interfaces.Exception']
            self.assertEquals(exc['type'], 'ValueError')
            self.assertEquals(exc['value'], u"invalid literal for int() with base 10: 'hello'")
            self.assertEquals(event['level'], logging.ERROR)
            self.assertEquals(event['message'], u"ValueError: invalid literal for int() with base 10: 'hello'")
            self.assertEquals(event['culprit'], 'tests.contrib.django.tests.test_signal_integration')

            # The project_id must be extracted from the SENTRY_DSN
            # option
            self.assertEquals(event['project'],
                    str(TESTING_PROJECT_ID))
Ejemplo n.º 15
0
def initialize():
    global _initialized

    with _setup_lock:
        if _initialized:
            return

        register_serializers()
        install_middleware()

        handler = CustomSentryDjangoHandler()
        handler.install()

        # instantiate client so hooks get registered
        get_client()  # NOQA

        _initialized = True
Ejemplo n.º 16
0
 def test_transport_specification(self):
     extra_settings = {
         'SENTRY_TRANSPORT': 'raven.transport.HTTPTransport',
         'SENTRY_DSN': 'http://*****:*****@example.com/1',
     }
     with Settings(**extra_settings):
         client = get_client(reset=True)
         assert type(client.remote.get_transport()) is HTTPTransport
Ejemplo n.º 17
0
 def test_transport_specification(self):
     extra_settings = {
         'SENTRY_TRANSPORT': 'raven.transport.HTTPTransport',
         'SENTRY_DSN': 'http://*****:*****@example.com/1',
     }
     with Settings(**extra_settings):
         client = get_client(reset=True)
         assert type(client.remote.get_transport()) is HTTPTransport
Ejemplo n.º 18
0
 def process_response(self, request, response):
     if response.status_code != 404 or _is_ignorable_404(request.get_full_path()):
         return response
     client = get_client()
     result = client.create_from_text('Http 404', request=request, level=logging.INFO, logger='http404')
     request.sentry = {
         'id': client.get_ident(result),
     }
     return response
Ejemplo n.º 19
0
    def test_cookies(self):
        request = APIRequestFactory().post('/')
        request.COOKIES['username'] = '******'

        raven = get_client()
        result = raven.get_data_from_request(request)

        self.assertFalse('cookies' in result['request'])
        self.assertFalse('Cookie' in result['request']['headers'])
Ejemplo n.º 20
0
def main():
    settings_from_file(os.path.expanduser(os.path.join('~', '.sentry', 'sentry.conf.py')))

    from raven.contrib.django.models import get_client

    client = get_client()
    functions = funcs()

    while True:
        random.choice(functions)(client)

        time.sleep(1)
Ejemplo n.º 21
0
    def test_get_client(self):
        assert get_client() == get_client()
        assert get_client('raven.base.Client').__class__ == Client
        assert get_client() == self.raven

        assert get_client('%s.%s' % (type(self.raven).__module__, type(self.raven).__name__)) == self.raven
        assert get_client() == self.raven
Ejemplo n.º 22
0
    def test_get_client(self):
        self.assertEquals(get_client(), get_client())
        self.assertEquals(get_client('raven.base.Client').__class__, Client)
        self.assertEquals(get_client(), self.raven)

        self.assertEquals(get_client('%s.%s' % (self.raven.__class__.__module__, self.raven.__class__.__name__)), self.raven)
        self.assertEquals(get_client(), self.raven)
Ejemplo n.º 23
0
    def test_get_client(self):
        self.assertEquals(get_client(), get_client())
        self.assertEquals(get_client('raven.base.Client').__class__, Client)
        self.assertEquals(get_client(), self.raven)

        self.assertEquals(get_client('%s.%s' % (self.raven.__class__.__module__, self.raven.__class__.__name__)), self.raven)
        self.assertEquals(get_client(), self.raven)
Ejemplo n.º 24
0
    def test_get_client(self):
        assert get_client() == get_client()
        assert get_client('raven.base.Client').__class__ == Client
        assert get_client() == self.raven

        assert get_client('%s.%s' % (type(self.raven).__module__, type(self.raven).__name__)) == self.raven
        assert get_client() == self.raven
Ejemplo n.º 25
0
 def process_response(self, request, response):
     if response.status_code != 404 or _is_ignorable_404(
             request.get_full_path()):
         return response
     client = get_client()
     result = client.create_from_text('Http 404',
                                      request=request,
                                      level=logging.INFO,
                                      logger='http404')
     request.sentry = {
         'id': client.get_ident(result),
     }
     return response
Ejemplo n.º 26
0
def sync_changed_files(sync_key, last_commit_hash, sync_url, project_dir):
    try:
        _sync_changed_files(sync_key, last_commit_hash, sync_url, project_dir)
    except Exception:
        import traceback
        traceback.print_exc()
        exc_info = sys.exc_info()
        try:
            raven_client = get_client()
            raven_client.captureException(exc_info=exc_info)
        except:
            import traceback
            traceback.print_exc()
            pass
Ejemplo n.º 27
0
    def emit(self, record):
        from raven.contrib.django.middleware import SentryLogMiddleware
        from raven.contrib.django.models import get_client

        # Fetch the request from a threadlocal variable, if available
        request = getattr(SentryLogMiddleware.thread, 'request', None)

        self.format(record)

        # Avoid typical config issues by overriding loggers behavior
        if record.name.startswith('sentry.errors'):
            print >> sys.stderr, "Recursive log message sent to SentryHandler"
            print >> sys.stderr, record.message
            return

        self.format(record)
        try:
            get_client().create_from_record(record, request=request)
        except Exception:
            print >> sys.stderr, "Top level Sentry exception caught - failed creating log record"
            print >> sys.stderr, record.msg
            print >> sys.stderr, traceback.format_exc()
            return
Ejemplo n.º 28
0
    def emit(self, record):
        from raven.contrib.django.middleware import SentryLogMiddleware
        from raven.contrib.django.models import get_client

        # Fetch the request from a threadlocal variable, if available
        request = getattr(record, 'request',
                          getattr(SentryLogMiddleware.thread, 'request', None))

        self.format(record)

        # Avoid typical config issues by overriding loggers behavior
        if record.name.startswith('sentry.errors'):
            print >> sys.stderr, "Recursive log message sent to SentryHandler"
            print >> sys.stderr, record.message
            return

        self.format(record)
        try:
            get_client().create_from_record(record, request=request)
        except Exception:
            print >> sys.stderr, "Top level Sentry exception caught - failed creating log record"
            print >> sys.stderr, record.msg
            print >> sys.stderr, traceback.format_exc()
            return
Ejemplo n.º 29
0
 def process_response(self, request, response):
     if response.status_code != 404 or _is_ignorable_404(request.get_full_path()):
         return response
     client = get_client()
     data = client.get_data_from_request(request)
     data.update({
         'level': logging.INFO,
         'logger': 'http404',
     })
     result = client.capture('Message', message='Page Not Found: %s' % request.build_absolute_uri(), data=data)
     request.sentry = {
         'project_id': data.get('project', client.project),
         'id': client.get_ident(result),
     }
     return response
Ejemplo n.º 30
0
    def _wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception:
            # not sure about this...
            import traceback

            traceback.print_exc()
            exc_info = sys.exc_info()

            try:
                raven_client = get_client()
                raven_client.captureException(exc_info=exc_info)
            except:
                import traceback

                traceback.print_exc()
Ejemplo n.º 31
0
    def handle(self, **options):
        from raven.contrib.django.models import get_client

        client = get_client()
        functions = funcs()

        s = time.time()
        r = 0
        try:
            while True:
                random.choice(functions)(client)
                r += 1
        except KeyboardInterrupt:
            pass
        finally:
            total_time = time.time() - s
            print '%d requests serviced in %.3fs' % (r, total_time)
            avg = total_time / r
            print 'avg of %.3fs/req, %d req/s' % (avg, 1 / avg)
Ejemplo n.º 32
0
    def handle(self, **options):
        from raven.contrib.django.models import get_client

        client = get_client()
        functions = funcs()

        s = time.time()
        r = 0
        try:
            while True:
                random.choice(functions)(client)
                r += 1
        except KeyboardInterrupt:
            pass
        finally:
            total_time = time.time() - s
            print '%d requests serviced in %.3fs' % (r, total_time)
            avg = total_time / r
            print 'avg of %.3fs/req, %d req/s' % (avg, 1 / avg)
    def test_signal_integration(self):
        with Settings(HEKA_CONF=self.HEKA_CONF,
                      HEKA=self.HEKA,
                      SENTRY_CLIENT=self.SENTRY_CLIENT,
                      SENTRY_DSN=DSN):

            self.raven = get_client()

            try:
                int('hello')
            except:
                got_request_exception.send(sender=self.__class__, request=None)
            else:
                self.fail('Expected an exception.')

            msgs = []
            for mdata in settings.HEKA.stream.msgs:
                h, m = decode_message(mdata)
                msgs.append(m)

            self.assertEquals(len(msgs), 1)

            event = self.raven.decode(msgs[0].payload)
            self.assertTrue('sentry.interfaces.Exception' in event)
            exc = event['sentry.interfaces.Exception']
            self.assertEquals(exc['type'], 'ValueError')
            self.assertEquals(
                exc['value'],
                u"invalid literal for int() with base 10: 'hello'")
            self.assertEquals(event['level'], logging.ERROR)
            self.assertEquals(
                event['message'],
                u"ValueError: invalid literal for int() with base 10: 'hello'")
            self.assertEquals(
                event['culprit'],
                'tests.contrib.django.tests in test_signal_integration')

            # The project_id must be extracted from the SENTRY_DSN
            # option
            self.assertEquals(event['project'], str(TESTING_PROJECT_ID))
Ejemplo n.º 34
0
def main():
    settings_from_file(os.path.expanduser(os.path.join('~', '.sentry', 'sentry.conf.py')))

    from raven.contrib.django.models import get_client

    client = get_client()
    functions = funcs()

    s = time.time()
    r = 0
    try:
        while True:
            random.choice(functions)(client)
            r += 1
            eventlet.sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        total_time = time.time() - s
        print '%d requests serviced in %.3fs' % (r, total_time)
        avg = total_time / r
        print 'avg of %.3fs/req, %d req/s' % (avg, 1 / avg)
Ejemplo n.º 35
0
    def handle(self, **options):
        from raven.contrib.django.models import get_client

        client = get_client()
        functions = funcs()

        s = time.time()
        r = 0
        pool = eventlet.GreenPool(16)
        try:
            while True:
                pool.spawn_n(random.choice(functions), (client))
                r += 1
                # eventlet.sleep(0.3)
        except KeyboardInterrupt:
            pass
        finally:
            pool.waitall()
            total_time = time.time() - s
            print '%d requests serviced in %.3fs' % (r, total_time)
            avg = total_time / r
            print 'avg of %.3fs/req, %d req/s' % (avg, 1 / avg)
Ejemplo n.º 36
0
 def setUp(self):
     self.raven = get_client()
Ejemplo n.º 37
0
 def test_proxy_responds_as_client(self):
     self.assertEquals(get_client(), client)
Ejemplo n.º 38
0
    def _get_client(self):
        from raven.contrib.django.models import get_client

        return get_client()
Ejemplo n.º 39
0
 def setUp(self):
     super(SentryExceptionHandlerTest, self).setUp()
     self.client = get_client()
     self.handler = SentryDjangoHandler(self.client)
Ejemplo n.º 40
0
 def setUp(self):
     super(SentryExceptionHandlerTest, self).setUp()
     self.client = get_client()
     self.handler = SentryDjangoHandler(self.client)
Ejemplo n.º 41
0
"""
raven.contrib.django.celery.tasks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

# TODO: need to educate myself on how this works

from raven.contrib.django.models import get_client

# We just need to pull in the client to ensure the task is registered
client = get_client()
Ejemplo n.º 42
0
def send_raw(*args, **kwargs):
    super(DjangoClient, get_client()).send_encoded(*args, **kwargs)
Ejemplo n.º 43
0
def send_raw_integrated(kwargs):
    super(DjangoClient, get_client()).send_integrated(kwargs)
Ejemplo n.º 44
0
def send_raw(*args, **kwargs):
    from raven.contrib.django.models import get_client
    super(DjangoClient, get_client()).send_encoded(*args, **kwargs)
Ejemplo n.º 45
0
#!/usr/bin/env python
import os
import sys
import traceback

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openahjo.settings")

    from django.core.management import execute_from_command_line

    try:
        execute_from_command_line(sys.argv)
    except Exception as e:
        if sys.stdout.isatty():
            traceback.print_exc()
        else:
            from django.conf import settings
            if settings.DEBUG or not hasattr(settings, 'RAVEN_CONFIG'):
                raise
            from raven.contrib.django.models import get_client
            exc_info = sys.exc_info()
            if getattr(exc_info[0], 'skip_sentry', False):
                raise
            get_client().captureException(exc_info)
            raise
Ejemplo n.º 46
0
 def test_wrong_params(self):
     query = 'SELECT COUNT(*) FROM mytestmodel WHERE id = %s'
     args = ['foobar', 42]
     record_sql(None, None, None, None, query, args)
     crumbs = get_client().context.breadcrumbs.get_buffer()
     self.assertEqual(crumbs[-1]['message'], query)
Ejemplo n.º 47
0
 def test_proxy_responds_as_client(self):
     assert get_client() == client
Ejemplo n.º 48
0
 def test_proxy_responds_as_client(self):
     assert get_client() == client
Ejemplo n.º 49
0
 def setUp(self):
     self.raven = get_client()
     self.handler = SentryDjangoHandler(self.raven)
     self.handler.install()
     self.addCleanup(self.handler.uninstall)
Ejemplo n.º 50
0
 def setUp(self):
     self.logger = logging.getLogger(__name__)
     self.raven = get_client()
Ejemplo n.º 51
0
 def test_proxy_responds_as_client(self):
     self.assertEquals(get_client(), client)
Ejemplo n.º 52
0
 def setUp(self):
     self.raven = get_client()
Ejemplo n.º 53
0
 def setUp(self):
     self.logger = logging.getLogger(__name__)
     self.raven = get_client()
Ejemplo n.º 54
0
 def client(self):
     if self._client is None:
         self._client = get_client(
             getattr(settings, 'SENTRY_GEARMAN_CLIENT',
                     'raven.contrib.django.client.DjangoClient'))
     return self._client
Ejemplo n.º 55
0
def send_raw_integrated(kwargs):
    from raven.contrib.django.models import get_client
    super(DjangoClient, get_client()).send_integrated(kwargs)
Ejemplo n.º 56
0
 def setUp(self):
     self.raven = get_client()
     self.handler = SentryDjangoHandler(self.raven)
     self.handler.install()
     self.addCleanup(self.handler.uninstall)