def test_old_run(self):
        """non-recorded events should return False"""
        et = EventTracker()
        # Times older than 3 hours don't get recorded according to: http://mixpanel.com/api/docs/specification
        # equests will be rejected that are 3 hours older than present time
        result = et.run('event_foo', {'time': 1245613885})

        self.assertFalse(result)
示例#2
0
    def test_handle_properties_given(self):
        et = EventTracker()

        properties = et._handle_properties({'token': 'bar'}, None)
        self.assertEqual('bar', properties['token'])

        properties = et._handle_properties({'token': 'bar'}, 'foo')
        self.assertEqual('bar', properties['token'])
示例#3
0
    def test_disable(self):
        et = EventTracker()
        mp_settings.MIXPANEL_DISABLE = True

        def _fake_get_connection():
            assert False, "Should bail out before trying to get a connection."
        et._get_connection = _fake_get_connection

        et('foo')
示例#4
0
    def test_non_recorded(self):
        """non-recorded events should return False"""
        self.response.read.return_value = '0'

        et = EventTracker()
        # Times older than 3 hours don't get recorded according to:
        # http://mixpanel.com/api/docs/specification
        # requests will be rejected that are 3 hours older than present time
        # (though actually this is returnin False because of mocking network)
        result = et.run('event_foo', {'time': 1245613885})

        self.assertFalse(result)
示例#5
0
    def test_build_params(self):
        et = EventTracker()

        event = 'foo_event'
        is_test = 1
        properties = {'token': 'testtoken'}
        params = {'event': event, 'properties': properties}

        url_params = et._build_params(event, properties, is_test)

        expected_params = urllib.urlencode({
            'data': base64.b64encode(simplejson.dumps(params)),
            'test': is_test,
        })

        self.assertEqual(expected_params, url_params)
示例#6
0
    def test_failed_request(self):
        EventTracker.endpoint = 'brokenurl'

        with eager_tasks():
            result = EventTracker.delay('event_foo')

        self.assertNotEqual(result.traceback, None)
示例#7
0
    def test_build_and_encode_params(self):
        et = EventTracker()

        event = 'foo_event'
        test = True
        properties = {'token': 'testtoken'}
        params = {'event': event, 'properties': properties}

        params = et._build_params(event, properties)
        url_params = et._encode_params(params, test)

        expected_params = urllib.parse.urlencode({
            'data': base64.b64encode(json.dumps(params).encode('utf8')),
            'test': '1'
        })

        self.assertEqual(expected_params, url_params)
示例#8
0
    def test_failed_socket_request(self):
        def new_read(*args, **kwargs):
            raise socket.error('BOOM')

        self.response.read = new_read
        with eager_tasks():
            result = EventTracker.delay('event_foo')
        self.assertNotEqual(result.traceback, None)
def send_mixpanel_event(event_name, user, event_dict=None):
    """
    Helper function that takes from various views an event name, an event_dict and an user and populates the event dict with
    a) distinct_id of the user with key 'distinct_id'
    b) 'username' = user.firstname + user.lastname
    c) 'age' = in years, today - DOB
    d) 'gender' = user.gender
    e) total em
    f) redeemable em
    g) time on earthmiles = today - joining date
    and then calls EventTracker.delay() with the modified dictionary
    """
    from dateutil.relativedelta import relativedelta
    from datetime import datetime, date

    if event_dict == None:
        event_dict = {}
    try:
        age = relativedelta(datetime.today(), user.age, ).years
        days_on_em = (datetime.today() - user.date_joined.replace(tzinfo=None)).days
        event_dict.update(
            {
                'distinct_id': user.id,
                'Username': user.__str__(),
                'Age': age,
                'Gender': user.gender,
                'Days on Earthmiles': days_on_em,
                'Total Earthmiles': user.total_earthmiles,
                'Redeemable Earthmiles': user.redeemable_earthmiles,
            }
        )
    except AttributeError as e:
        event_dict.update(
            {
                'distinct_id': user.id,
            }
        )


    #Try to send event to mixpanel. If there is an error, it could be because we're testing on localhost, in which case, pass, else raise the error
    try:
        EventTracker.delay(event_name, event_dict)
    except ConnectionError as e:
        if 'localhost' not in str(e):
            raise
示例#10
0
    def test_is_test(self):
        et = EventTracker()

        self.assertEqual(et._is_test(None), 1)
        self.assertEqual(et._is_test(False), 0)
        self.assertEqual(et._is_test(True), 1)

        mp_settings.MIXPANEL_TEST_ONLY = False
        self.assertEqual(et._is_test(None), 0)
        self.assertEqual(et._is_test(False), 0)
        self.assertEqual(et._is_test(True), 1)
示例#11
0
def index(request):
    et = EventTracker()
    et.run('dj_event', {'distinct_id': 1}, token=settings.token )
    return HttpResponse("Hello, world!.")
示例#12
0
    def test_handle_properties_empty(self):
        et = EventTracker()
        mp_settings.MIXPANEL_API_TOKEN = 'bar'

        properties = et._handle_properties(None, None)
        self.assertEqual('bar', properties['token'])
示例#13
0
    def test_handle_properties_w_token(self):
        et = EventTracker()

        properties = et._handle_properties({}, 'foo')
        self.assertEqual('foo', properties['token'])
示例#14
0
    def test_failed_socket_request(self):
        mp_settings.MIXPANEL_API_SERVER = '127.0.0.1:60000'

        with eager_tasks():
            result = EventTracker.delay('event_foo')
        self.assertNotEqual(result.traceback, None)
示例#15
0
    def test_debug_logger(self):
        et = EventTracker()
        result = et.run('event_foo', {}, loglevel=logging.DEBUG)

        self.assertTrue(result)
示例#16
0
    def test_run(self):
        # "correct" result obtained from: http://mixpanel.com/api/docs/console
        et = EventTracker()
        result = et.run('event_foo', {})

        self.assertTrue(result)
示例#17
0
 def test_failed_socket_request(self):
     self.response.read = Mock(side_effect=socket.error('BOOM'))
     with eager_tasks():
         result = EventTracker.delay('event_foo')
     self.assertNotEqual(result.traceback, None)
示例#18
0
def send_event(event_name, **kwargs):
  if not event_name: raise ValueError("event name is required")
  EventTracker.delay(event_name, **kwargs)
示例#19
0
 def test_failed_request(self):
     self.response.status = 400
     with eager_tasks():
         result = EventTracker.delay('event_foo')
     self.assertNotEqual(result.traceback, None)
示例#20
0
from guelphapi.api.utils.log import get_data

from tastypie.resources import Resource, ModelResource

from mixpanel.tasks import EventTracker

tracker = EventTracker()
track_event = lambda *a, **kw: tracker.run(*a, **kw)

class LoggingResource(Resource):
    def dispatch(self, request_type, request, **kwargs):
        # Let the "real" dispatch do its thing.
        # This includes checking a throttle, authentication, authorization, etc
        response = super(LoggingResource, self).dispatch(request_type, request, **kwargs)
        # Only log "good" requests for now
        # We know once we're down here, that things are fine
        data = get_data(request_type, request, kwargs)
        track_event('request-%s' % request.META.get('REQUEST_METHOD', request_type), data)
        return response

class LoggingModelResource(ModelResource):
    def dispatch(self, request_type, request, **kwargs):
        # Let the "real" dispatch do its thing.
        # This includes checking a throttle, authentication, authorization, etc.
        response = super(LoggingModelResource, self).dispatch(request_type, request, **kwargs)
        # Only log "good" requests for now
        # We know once we're down here, that things are fine
        data = get_data(request_type, request, kwargs)
        track_event('request-%s' % request.META.get('REQUEST_METHOD', request_type), data)
        return response
示例#21
0
    def test_run(self):
        # "correct" result obtained from: http://mixpanel.com/api/docs/console
        et = EventTracker()
        result = et.run('event_foo', {})

        self.assertTrue(result)