Source

pyramid_mixpanel / pyramid_mixpanel / tests / unittests / test_pyramid_mixpanel.py

# -*- coding: utf-8 -*-
import json
import base64
import unittest
from decimal import Decimal

import mock


class TestPyramidMixpanel(unittest.TestCase):

    @mock.patch('pyramid_mixpanel.MixpanelUtility')
    def test_includeme(self, utility):
        from pyramid_mixpanel import includeme, get_mixpanel_utility
        config = mock.Mock()

        includeme(config)

        config.registry.registerUtility.assert_called_once_with(
            utility.return_value
            )
        config.commit.assert_called_once_with()
        utility.assert_called_once_with(config.registry.settings)

    def test_get_mixpanel_utility(self):
        from pyramid_mixpanel import get_mixpanel_utility, IMixpanelUtility
        request = mock.Mock()

        result = get_mixpanel_utility(request)

        request.registry.getUtility.assert_called_once_with(IMixpanelUtility)
        self.assertEqual(result, request.registry.getUtility.return_value)

    @mock.patch('requests.get')
    def test_track(self, m_get):
        from pyramid_mixpanel import MixpanelUtility
        mu = MixpanelUtility({'pyramid_mixpanel.token': 'token'})
        event = 'test_event'
        properties = {
            u'token': u'123456789',
            u'install_referrer': 'Direct Link',
            }

        mu.track(event, properties)

        url = "https://api.mixpanel.com/track"
        params = {'event': event, 'properties': properties}
        data = base64.b64encode(json.dumps(params))
        m_get.assert_called_once_with(url, params={'data': data})

    @mock.patch('requests.get')
    @mock.patch('pyramid_mixpanel.log')
    def test_track_exception(self, m_log, m_requests_get):
        from pyramid_mixpanel import MixpanelUtility
        mu = MixpanelUtility({'pyramid_mixpanel.token': 'token'})

        mu.track('test_event', {'prop': Decimal(10)})

        self.assertFalse(m_requests_get.called)
        self.assertTrue(m_log.exception.called)