Exemplo n.º 1
0
    def test_build_then_send(self):
        organization_id = "organization_id"
        app_id = "app_id"
        secret_token = "secret_token"

        try:
            Client.register_scheme('mock', DummyScheme)
        except:
            pass
        c = Client(organization_id=organization_id, secret_token=secret_token,
                app_id=app_id, hostname="test_server")

        mydate = datetime.datetime(2012, 5, 4, tzinfo=pytz.utc)
        d = calendar.timegm(mydate.timetuple())
        msg = c.build_msg_for_logging("Message", message='foo', date=d)
        expected = {
            'organization_id': organization_id,
            'app_id': app_id,
            'secret_token': secret_token,
            'message': 'foo',
            'param_message': {'message': 'foo', 'params': ()},
            'machine': {'hostname': u'test_server'},
            'level': "error",
            'extra': {},
            'timestamp': 1336089600
        }

        # The client_supplied_id is always overridden
        del msg['client_supplied_id']

        self.assertEquals(msg, expected)
Exemplo n.º 2
0
    def test_send_remote_failover_async(self, should_try, http_send):
        should_try.return_value = True

        client = Client(
            servers=["http://example.com"],
            organization_id="organization_id",
            app_id="app_id",
            secret_token="secret",
            async_mode=True,
        )
        logger = mock.Mock()
        client.error_logger.error = logger

        # test error
        encoded_data = client.encode({"message": "oh no"})
        http_send.side_effect = TransportException("oopsie", encoded_data)
        client.send_remote("http://example.com/api/store", data=encoded_data)
        client.close()
        assert client.state.status == client.state.ERROR
        assert len(logger.call_args_list) == 2
        assert "oopsie" in logger.call_args_list[0][0][0]
        assert "oh no" in logger.call_args_list[1][0][1]

        # test recovery
        http_send.side_effect = None
        client.send_remote("http://example.com/api/store", "foo")
        client.close()
        assert client.state.status == client.state.ONLINE
Exemplo n.º 3
0
    def test_send_remote_failover_async(self, should_try, http_send):
        should_try.return_value = True

        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
            async_mode=True,
        )
        logger = mock.Mock()
        client.error_logger.error = logger

        # test error
        encoded_data = client.encode({'message': 'oh no'})
        http_send.side_effect = TransportException('oopsie', encoded_data)
        client.send_remote('http://example.com/api/store', data=encoded_data)
        client.close()
        assert client.state.status == client.state.ERROR
        assert len(logger.call_args_list) == 2
        assert 'oopsie' in logger.call_args_list[0][0][0]
        assert 'oh no' in logger.call_args_list[1][0][1]

        # test recovery
        http_send.side_effect = None
        client.send_remote('http://example.com/api/store', 'foo')
        client.close()
        assert client.state.status == client.state.ONLINE
Exemplo n.º 4
0
    def test_config_non_string_types(self, mock_send):
        """
        tests if we can handle non string types as configuration, e.g.
        Value types from django-configuration
        """
        class MyValue(object):
            def __init__(self, content):
                self.content = content

            def __str__(self):
                return str(self.content)

            def __repr__(self):
                return repr(self.content)

        client = Client(
            servers=['localhost'],
            organization_id=MyValue('foo'),
            app_id=MyValue('bar'),
            secret_token=MyValue('bay')
        )
        client.capture('Message', message='foo')
        args, kwargs = mock_send.call_args
        self.assertEqual(
            'localhost' + defaults.ERROR_API_PATH.format('foo', 'bar'),
            kwargs['servers'][0]
        )
Exemplo n.º 5
0
 def test_client_uses_sync_mode_when_master_process(self, is_master_process):
     # when in the master process, the client should use the non-async
     # HTTP transport, even if async_mode is True
     is_master_process.return_value = True
     client = Client(
         servers=["http://example.com"],
         organization_id="organization_id",
         app_id="app_id",
         secret_token="secret",
         async_mode=True,
     )
     self.assertIsInstance(client._get_transport(urlparse.urlparse("http://exampe.com")), HTTPTransport)
Exemplo n.º 6
0
 def test_client_shutdown_async(self, mock_traces_collect, mock_send):
     client = Client(
         servers=["http://example.com"],
         organization_id="organization_id",
         app_id="app_id",
         secret_token="secret",
         async_mode=True,
     )
     client.send(auth_header="foo", **{"foo": "bar"})
     client.close()
     self.assertEqual(mock_traces_collect.call_count, 1)
     self.assertEqual(mock_send.call_count, 1)
Exemplo n.º 7
0
    def test_send_not_enabled(self, time, send_remote):
        time.return_value = 1328055286.51
        with mock.patch.dict("os.environ", {"OPBEAT_DISABLE_SEND": "true"}):
            client = Client(
                servers=["http://example.com"],
                organization_id="organization_id",
                app_id="app_id",
                secret_token="secret",
            )
        client.send(**{"foo": "bar"})

        assert not send_remote.called
Exemplo n.º 8
0
    def test_call_end_twice(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )

        should_collect.return_value = False
        client.begin_transaction("celery")

        client.end_transaction(200, 'test-transaction')
        client.end_transaction(200, 'test-transaction')
Exemplo n.º 9
0
    def test_send_not_enabled(self, time, send_remote):
        time.return_value = 1328055286.51
        with mock.patch.dict('os.environ', {'OPBEAT_DISABLE_SEND': 'true'}):
            client = Client(
                servers=['http://example.com'],
                organization_id='organization_id',
                app_id='app_id',
                secret_token='secret',
            )
        client.send(**{
            'foo': 'bar',
        })

        assert not send_remote.called
Exemplo n.º 10
0
 def test_client_shutdown_async(self, mock_traces_collect, mock_send):
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
         async_mode=True,
     )
     client.send(auth_header='foo', **{
         'foo': 'bar',
     })
     client.close()
     self.assertEqual(mock_traces_collect.call_count, 1)
     self.assertEqual(mock_send.call_count, 1)
Exemplo n.º 11
0
 def test_send_with_auth_header(self, time, send_remote):
     time.return_value = 1328055286.51
     client = Client(
         servers=["http://example.com"], organization_id="organization_id", app_id="app_id", secret_token="secret"
     )
     client.send(auth_header="foo", **{"foo": "bar"})
     send_remote.assert_called_once_with(
         url="http://example.com",
         data=six.b("x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T"),
         headers={
             "Content-Type": "application/octet-stream",
             "Authorization": "foo",
             "User-Agent": "opbeat-python/%s" % opbeat.VERSION,
             "X-Opbeat-Platform": self.client.get_platform_info(),
         },
     )
Exemplo n.º 12
0
    def test_send_remote_failover_sync_stdlib(self, should_try, http_send):
        should_try.return_value = True

        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
            async_mode=False,
        )
        logger = mock.Mock()
        client.error_logger.error = logger

        # test error
        encoded_data = client.encode({'message': 'oh no'})
        http_send.side_effect = ValueError('oopsie')
        client.send_remote('http://example.com/api/store', data=encoded_data)
        assert client.state.status == client.state.ERROR
        assert len(logger.call_args_list) == 1
        assert 'oopsie' in logger.call_args_list[0][0][1]

        # test recovery
        http_send.side_effect = None
        client.send_remote('http://example.com/api/store', 'foo')
        assert client.state.status == client.state.ONLINE
Exemplo n.º 13
0
 def test_custom_transport(self):
     client = Client(
         servers=['localhost'],
         organization_id='foo',
         app_id='bar',
         secret_token='baz',
         transport_class='tests.client.client_tests.DummyTransport',
     )
     self.assertEqual(client._transport_class, DummyTransport)
Exemplo n.º 14
0
    def test_send_remote_failover(self, should_try, send_remote):
        should_try.return_value = True

        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )

        # test error
        send_remote.side_effect = Exception()
        client.send_remote('http://example.com/api/store', 'foo')
        self.assertEquals(client.state.status, client.state.ERROR)

        # test recovery
        send_remote.side_effect = None
        client.send_remote('http://example.com/api/store', 'foo')
        self.assertEquals(client.state.status, client.state.ONLINE)
Exemplo n.º 15
0
 def test_config_by_environment(self):
     with mock.patch.dict('os.environ', {
         'OPBEAT_ORGANIZATION_ID': 'org',
         'OPBEAT_APP_ID': 'app',
         'OPBEAT_SECRET_TOKEN': 'token',
     }):
         client = Client()
         self.assertEqual(client.organization_id, 'org')
         self.assertEqual(client.app_id, 'app')
         self.assertEqual(client.secret_token, 'token')
Exemplo n.º 16
0
    def test_empty_processor_list(self):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
            processors=[],
        )

        self.assertEqual(client.processors, [])
 def test_send_with_auth_header(self, time, send_remote):
     time.return_value = 1328055286.51
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
     )
     client.send(auth_header='foo', **{
         'foo': 'bar',
     })
     send_remote.assert_called_once_with(
         url='http://example.com',
         data='x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T',
         headers={
             'Content-Type': 'application/octet-stream',
             'Authorization': 'foo',
             'User-Agent': 'opbeat/%s' % opbeat.VERSION
         },
     )
Exemplo n.º 18
0
    def test_metrics_collection(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )
        should_collect.return_value = False
        for i in range(7):
            client.begin_transaction("transaction.test")
            client.end_transaction('test-transaction', 200)

        self.assertEqual(len(client.instrumentation_store), 7)
        self.assertEqual(mock_send.call_count, 0)
        should_collect.return_value = True

        client.begin_transaction("transaction.test")
        client.end_transaction('my-other-transaction', 200)
        self.assertEqual(len(client.instrumentation_store), 0)
        self.assertEqual(mock_send.call_count, 1)
Exemplo n.º 19
0
    def test_metrics_collection(self, should_collect, mock_send):
        client = Client(
            servers=["http://example.com"], organization_id="organization_id", app_id="app_id", secret_token="secret"
        )
        should_collect.return_value = False
        for i in range(7):
            client.begin_transaction("transaction.test")
            client.end_transaction("test-transaction", 200)

        self.assertEqual(len(client.instrumentation_store), 7)
        self.assertEqual(mock_send.call_count, 0)
        should_collect.return_value = True

        client.begin_transaction("transaction.test")
        client.end_transaction("my-other-transaction", 200)
        self.assertEqual(len(client.instrumentation_store), 0)
        self.assertEqual(mock_send.call_count, 1)
Exemplo n.º 20
0
    def __init__(self, hide_zerorpc_frames=True, client=None, **kwargs):
        """Create a middleware object that can be injected in a ZeroRPC server.

        - hide_zerorpc_frames: modify the exception stacktrace to remove the
                               internal zerorpc frames (True by default to make
                               the stacktrace as readable as possible);
        - client: use an existing raven.Client object, otherwise one will be
                  instantiated from the keyword arguments.

        """
        self._opbeat_client = client or Client(**kwargs)
        self._hide_zerorpc_frames = hide_zerorpc_frames
Exemplo n.º 21
0
 def test_send_with_auth_header(self, time, send_remote):
     time.return_value = 1328055286.51
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
     )
     client.send(auth_header='foo', **{
         'foo': 'bar',
     })
     send_remote.assert_called_once_with(
         url='http://example.com',
         data=six.b('x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T'),
         headers={
             'Content-Type': 'application/octet-stream',
             'Authorization': 'foo',
             'User-Agent': 'opbeat-python/%s' % opbeat.VERSION,
             'X-Opbeat-Platform': self.client.get_platform_info(),
         },
     )
Exemplo n.º 22
0
    def test_ignore_patterns(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
            async_mode=True,
            transactions_ignore_patterns=[
                '^OPTIONS',
                'views.api.v2'
            ]
        )

        should_collect.return_value = False
        client.begin_transaction("web")
        client.end_transaction('OPTIONS views.healthcheck', 200)

        client.begin_transaction("web")
        client.end_transaction('GET views.users', 200)

        self.assertEqual(len(client.instrumentation_store), 1)
Exemplo n.º 23
0
    def test_ignore_patterns(self, should_collect, mock_send):
        client = Client(
            servers=["http://example.com"],
            organization_id="organization_id",
            app_id="app_id",
            secret_token="secret",
            async_mode=True,
            transactions_ignore_patterns=["^OPTIONS", "views.api.v2"],
        )

        should_collect.return_value = False
        client.begin_transaction("web")
        client.end_transaction("OPTIONS views.healthcheck", 200)

        client.begin_transaction("web")
        client.end_transaction("GET views.users", 200)

        self.assertEqual(len(client.instrumentation_store), 1)
Exemplo n.º 24
0
 def test_send(self, time, send_remote):
     time.return_value = 1328055286.51
     public = "public"
     access_token = "secret"
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
     )
     client.send(**{
         'foo': 'bar',
     })
     send_remote.assert_called_once_with(
         url='http://example.com',
         data=six.b('x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T'),
         headers={
             'Content-Type': 'application/octet-stream',
             'Authorization': 'Bearer %s' % (access_token),
             'User-Agent': 'opbeat-python/%s' % opbeat.VERSION
         },
     )
Exemplo n.º 25
0
 def test_send_with_auth_header(self, time, send_remote):
     time.return_value = 1328055286.51
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
     )
     client.send(auth_header='foo', **{
         'foo': 'bar',
     })
     send_remote.assert_called_once_with(
         url='http://example.com',
         data=six.b('x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T'),
         headers={
             'Content-Type': 'application/json',
             'Content-Encoding': 'deflate',
             'Authorization': 'foo',
             'User-Agent': 'opbeat-python/%s' % opbeat.VERSION,
             'X-Opbeat-Platform': self.client.get_platform_info(),
         },
     )
Exemplo n.º 26
0
    def test_config_non_string_types(self, mock_send):
        """
        tests if we can handle non string types as configuration, e.g.
        Value types from django-configuration
        """

        class MyValue(object):
            def __init__(self, content):
                self.content = content

            def __str__(self):
                return str(self.content)

            def __repr__(self):
                return repr(self.content)

        client = Client(
            servers=["localhost"], organization_id=MyValue("foo"), app_id=MyValue("bar"), secret_token=MyValue("bay")
        )
        client.capture("Message", message="foo")
        args, kwargs = mock_send.call_args
        self.assertEqual("localhost" + defaults.ERROR_API_PATH.format("foo", "bar"), kwargs["servers"][0])
Exemplo n.º 27
0
 def test_send(self, time, send_remote):
     time.return_value = 1328055286.51
     public = "public"
     access_token = "secret"
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
     )
     client.send(**{
         'foo': 'bar',
     })
     send_remote.assert_called_once_with(
         url='http://example.com',
         data=six.b('x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T'),
         headers={
             'Content-Type': 'application/octet-stream',
             'Authorization': 'Bearer %s' % (access_token),
             'User-Agent': 'opbeat-python/%s' % opbeat.VERSION
         },
     )
Exemplo n.º 28
0
    def test_build_then_send(self):
        organization_id = "organization_id"
        app_id = "app_id"
        secret_token = "secret_token"

        try:
            Client.register_scheme('mock', DummyScheme)
        except:
            pass
        c = Client(organization_id=organization_id,
                   secret_token=secret_token,
                   app_id=app_id,
                   hostname="test_server")

        mydate = datetime.datetime(2012, 5, 4, tzinfo=pytz.utc)
        d = calendar.timegm(mydate.timetuple())
        msg = c.build_msg_for_logging("Message", message='foo', date=d)
        expected = {
            'organization_id': organization_id,
            'app_id': app_id,
            'secret_token': secret_token,
            'message': 'foo',
            'param_message': {
                'message': 'foo',
                'params': ()
            },
            'machine': {
                'hostname': u'test_server'
            },
            'level': "error",
            'extra': {},
            'timestamp': 1336089600
        }

        # The client_supplied_id is always overridden
        del msg['client_supplied_id']

        self.assertEquals(msg, expected)
Exemplo n.º 29
0
    def test_metrics_collection(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )
        should_collect.return_value = False
        for i in range(7):
            client.begin_transaction()
            client.end_transaction(200, 'test-transaction')

        self.assertEqual(len(client.instrumentation_store), 7)
        self.assertEqual(mock_send.call_count, 0)
        should_collect.return_value = True

        client.begin_transaction()
        client.end_transaction(200, 'my-other-transaction')
        self.assertEqual(len(client.instrumentation_store), 0)
        self.assertEqual(mock_send.call_count, 1)
Exemplo n.º 30
0
    def test_config_non_string_types(self, mock_send):
        """
        tests if we can handle non string types as configuration, e.g.
        Value types from django-configuration
        """
        class MyValue(object):
            def __init__(self, content):
                self.content = content

            def __str__(self):
                return str(self.content)

            def __repr__(self):
                return repr(self.content)

        client = Client(servers=['localhost'],
                        organization_id=MyValue('foo'),
                        app_id=MyValue('bar'),
                        secret_token=MyValue('bay'))
        client.capture('Message', message='foo')
        args, kwargs = mock_send.call_args
        self.assertEqual(
            'localhost' + defaults.ERROR_API_PATH.format('foo', 'bar'),
            kwargs['servers'][0])
Exemplo n.º 31
0
    def test_ignore_patterns(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
            async_mode=True,
            transactions_ignore_patterns=[
                '^OPTIONS',
                'views.api.v2'
            ]
        )

        should_collect.return_value = False
        client.begin_transaction("web")
        client.end_transaction('OPTIONS views.healthcheck', 200)

        client.begin_transaction("web")
        client.end_transaction('GET views.users', 200)

        self.assertEqual(len(client.instrumentation_store), 1)
Exemplo n.º 32
0
    def test_call_end_twice(self, should_collect, mock_send):
        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )

        should_collect.return_value = False
        client.begin_transaction()

        client.end_transaction(200, 'test-transaction')
        client.end_transaction(200, 'test-transaction')
Exemplo n.º 33
0
 def test_client_shutdown_async(self, mock_traces_collect, mock_send):
     client = Client(
         servers=['http://example.com'],
         organization_id='organization_id',
         app_id='app_id',
         secret_token='secret',
         async_mode=True,
     )
     client.send(auth_header='foo', **{
         'foo': 'bar',
     })
     client.close()
     self.assertEqual(mock_traces_collect.call_count, 1)
     self.assertEqual(mock_send.call_count, 1)
    def test_send_remote_failover(self, should_try, send_remote):
        should_try.return_value = True

        client = Client(
            servers=['http://example.com'],
            organization_id='organization_id',
            app_id='app_id',
            secret_token='secret',
        )

        # test error
        send_remote.side_effect = Exception()
        client.send_remote('http://example.com/api/store', 'foo')
        self.assertEquals(client.state.status, client.state.ERROR)

        # test recovery
        send_remote.side_effect = None
        client.send_remote('http://example.com/api/store', 'foo')
        self.assertEquals(client.state.status, client.state.ONLINE)
Exemplo n.º 35
0
 def __init__(self, client=None, **kwargs):
     self.client = client or Client(**kwargs)
Exemplo n.º 36
0
def opbeat_filter_factory(app, global_conf, **kwargs):
    client = Client(**kwargs)
    return Opbeat(app, client)
Exemplo n.º 37
0
# -*- coding: utf-8 -*-
import datetime
import json
import os

import logging
from opbeat.base import Client
from opbeat.handlers.logging import OpbeatHandler

logging.basicConfig(level=logging.INFO)

if os.environ.get('OPBEAT_APP_ID', None):
    opbeat_client = Client(app_id=os.environ['OPBEAT_APP_ID'])

    logger = logging.getLogger(__name__)
    logger.addHandler(OpbeatHandler(opbeat_client))
else:
    opbeat_client = None

import pymongo
import requests
from requests_oauthlib import OAuth1

client = pymongo.MongoClient(os.environ.get('MONGOLAB_URI', None))
db = client.get_default_database()

auth = OAuth1(
    os.environ['CONSUMER_KEY'],
    client_secret=os.environ['CONSUMER_SECRET'],
    resource_owner_key=os.environ['OAUTH_TOKEN'],
    resource_owner_secret=os.environ['OAUTH_TOKEN_SECRET'],