Commits

Arun Karunagath  committed 73a74eb Merge

fixed merge conflict

  • Participants
  • Parent commits 0f87507, 6bc9b6c

Comments (0)

Files changed (9)

 *pyc
-dist/*
-build/*
-pyga.egg-info/*
-doc/_build/*
+dist
+build
+*.egg-info
+*.egg
+doc/_build
 *~
+.ropeproject
+.vimrc
+# target: help - Display callable targets
+help:
+	@egrep "^# target:" [Mm]akefile
+
+# target: audit - Audit source code
+.PHONY: audit
+audit:
+	pylama pyga -i E501
+
+# target: test - Run tests
+.PHONY: test
+test: setup.py
+	python setup.py test
+
+# target: clean - Clean repo
+.PHONY: clean
+clean:
+	find $(CURDIR) -name "*.pyc" -delete
+	find $(CURDIR) -name "*.orig" -delete

File pyga/entities.py

         if not self.source:
             raise exceptions.ValidationError('Campaigns need to have at least the "source" attribute defined.')
 
-    def create_from_referrer(self, url):
+    @staticmethod
+    def create_from_referrer(url):
         obj = Campaign(Campaign.TYPE_REFERRAL)
         parse_rslt = urlparse(url)
         obj.source = parse_rslt.netloc
             try:
                 setattr(self, self.UTMZ_PARAM_MAP[key], unquote_plus(val))
             except KeyError:
-                pass
+                continue
 
         return self
 
     def __getattribute__(self, name):
         if name == 'unique_id':
             tmp = object.__getattribute__(self, name)
-            if tmp == None:
+            if tmp is None:
                 self.unique_id = self.generate_unique_id()
         return object.__getattribute__(self, name)
 

File pyga/exceptions.py

 class ValidationError(Exception):
-    pass
+    pass

File pyga/requests.py

 # -*- coding: utf-8 -*-
 
 import logging
-from sys import stderr
 import calendar
 from math import floor
 from pyga.entities import Campaign, CustomVariable, Event, Item, Page, Session, SocialInteraction, Transaction, Visitor
 
 __author__ = "Arun KR (kra3) <the1.arun@gmail.com>"
 __license__ = "Simplified BSD"
+__version__ = '2.4.2'
 
 logger = logging.getLogger(__name__)
 
         headers = {}
         headers['Host'] = self.config.endpoint.split('/')[2]
         headers['User-Agent'] = self.user_agent
-        headers['X-Forwarded-For'] = self.x_forwarded_for and  self.x_forwarded_for or ''
+        headers['X-Forwarded-For'] = self.x_forwarded_for and self.x_forwarded_for or ''
 
         if use_post:
             # Don't ask me why "text/plain", but ga.js says so :)
 
         #  Do not actually send the request if endpoint host is set to null
         if self.config.endpoint:
-            response = urllib2.urlopen(request, timeout=self.config.request_timeout)
+            response = urllib2.urlopen(
+                request, timeout=self.config.request_timeout)
 
         return response
 
             for cvar in custom_vars.itervalues():
                 name = utils.encode_uri_components(cvar.name)
                 value = utils.encode_uri_components(cvar.value)
-                x10.set_key(self.X10_CUSTOMVAR_NAME_PROJECT_ID, cvar.index, name)
-                x10.set_key(self.X10_CUSTOMVAR_VALUE_PROJCT_ID, cvar.index, value)
+                x10.set_key(
+                    self.X10_CUSTOMVAR_NAME_PROJECT_ID, cvar.index, name)
+                x10.set_key(
+                    self.X10_CUSTOMVAR_VALUE_PROJCT_ID, cvar.index, value)
 
                 if cvar.scope and cvar.scope != CustomVariable.SCOPE_PAGE:
-                    x10.set_key(self.X10_CUSTOMVAR_SCOPE_PROJECT_ID, cvar.index, cvar.scope)
+                    x10.set_key(self.X10_CUSTOMVAR_SCOPE_PROJECT_ID,
+                                cvar.index, cvar.scope)
 
             params.utme = '%s%s' % (params.utme, x10.render_url_string())
 
         campaign = self.tracker.campaign
         if campaign:
             params._utmz = '%s.%s.%s.%s.' % (
-                    self._generate_domain_hash(),
-                    calendar.timegm(campaign.creation_time.timetuple()),
-                    self.visitor.visit_count,
-                    campaign.response_count,
-                )
+                self._generate_domain_hash(),
+                calendar.timegm(campaign.creation_time.timetuple()),
+                self.visitor.visit_count,
+                campaign.response_count,
+            )
 
             param_map = {
                 'utmcid': campaign.id,
                 if v:
                     # Only spaces and pluses get escaped in gaforflash and ga.js, so we do the same
                     params._utmz = '%s%s=%s%s' % (params._utmz, k,
-                            v.replace('+', '%20').replace(' ', '%20'),
-                            Campaign.CAMPAIGN_DELIMITER
-                        )
+                                                  v.replace('+', '%20').replace(' ', '%20'),
+                                                  Campaign.CAMPAIGN_DELIMITER
+                                                  )
 
             params._utmz = params._utmz.rstrip(Campaign.CAMPAIGN_DELIMITER)
 
     def build_cookie_parameters(self, params):
         domain_hash = self._generate_domain_hash()
         params._utma = "%s.%s.%s.%s.%s.%s" % (
-                domain_hash,
-                self.visitor.unique_id,
-                calendar.timegm(self.visitor.first_visit_time.timetuple()),
-                calendar.timegm(self.visitor.previous_visit_time.timetuple()),
-                calendar.timegm(self.visitor.current_visit_time.timetuple()),
-                self.visitor.visit_count
-            )
+            domain_hash,
+            self.visitor.unique_id,
+            calendar.timegm(self.visitor.first_visit_time.timetuple()),
+            calendar.timegm(self.visitor.previous_visit_time.timetuple()),
+            calendar.timegm(self.visitor.current_visit_time.timetuple()),
+            self.visitor.visit_count
+        )
         params._utmb = '%s.%s.10.%s' % (
-                domain_hash,
-                self.session.track_count,
-                calendar.timegm(self.session.start_time.timetuple()),
-            )
+            domain_hash,
+            self.session.track_count,
+            calendar.timegm(self.session.start_time.timetuple()),
+        )
         params._utmc = domain_hash
         cookies = []
         cookies.append('__utma=%s;' % params._utma)
     X10_SITESPEED_PROJECT_ID = 14
 
     def __init__(self, config, tracker, visitor, session, page):
-        super(PageViewRequest, self).__init__(config, tracker, visitor, session)
+        super(
+            PageViewRequest, self).__init__(config, tracker, visitor, session)
         self.page = page
 
     def get_type(self):
             params.utmr = self.page.referrer
 
         if self.page.load_time:
-            if params.utmn % 100 <  self.config.site_speed_sample_rate:
+            if params.utmn % 100 < self.config.site_speed_sample_rate:
                 x10 = X10()
                 x10.clear_key(self.X10_SITESPEED_PROJECT_ID)
                 x10.clear_value(self.X10_SITESPEED_PROJECT_ID)
 
                 # from ga.js
                 key = max(min(floor(self.page.load_time / 100), 5000), 0) * 100
-                x10.set_key(self.X10_SITESPEED_PROJECT_ID, X10.OBJECT_KEY_NUM, key)
-                x10.set_value(self.X10_SITESPEED_PROJECT_ID, X10.VALUE_VALUE_NUM, self.page.load_time)
+                x10.set_key(
+                    self.X10_SITESPEED_PROJECT_ID, X10.OBJECT_KEY_NUM, key)
+                x10.set_value(self.X10_SITESPEED_PROJECT_ID,
+                              X10.VALUE_VALUE_NUM, self.page.load_time)
                 params.utme = '%s%s' % (params.utme, x10.render_url_string())
 
         return params
         x10 = X10()
         x10.clear_key(self.X10_EVENT_PROJECT_ID)
         x10.clear_value(self.X10_EVENT_PROJECT_ID)
-        x10.set_key(self.X10_EVENT_PROJECT_ID, X10.OBJECT_KEY_NUM, self.event.category)
-        x10.set_key(self.X10_EVENT_PROJECT_ID, X10.TYPE_KEY_NUM, self.event.action)
+        x10.set_key(self.X10_EVENT_PROJECT_ID, X10.OBJECT_KEY_NUM,
+                    self.event.category)
+        x10.set_key(
+            self.X10_EVENT_PROJECT_ID, X10.TYPE_KEY_NUM, self.event.action)
 
         if self.event.label:
-            x10.set_key(self.X10_EVENT_PROJECT_ID, X10.LABEL_KEY_NUM, self.event.label)
+            x10.set_key(self.X10_EVENT_PROJECT_ID,
+                        X10.LABEL_KEY_NUM, self.event.label)
 
         if self.event.value:
-            x10.set_value(self.X10_EVENT_PROJECT_ID, X10.VALUE_VALUE_NUM, self.event.value)
+            x10.set_value(self.X10_EVENT_PROJECT_ID,
+                          X10.VALUE_VALUE_NUM, self.event.value)
 
         params.utme = "%s%s" % (params.utme, x10.render_url_string())
 
 
 class SocialInteractionRequest(Request):
     def __init__(self, config, tracker, visitor, session, social_interaction, page):
-        super(SocialInteractionRequest, self).__init__(config, tracker, visitor, session)
+        super(SocialInteractionRequest, self).__init__(config,
+                                                       tracker, visitor, session)
         self.social_interaction = social_interaction
         self.page = page
 
         params = super(SocialInteractionRequest, self).build_parameters()
 
         tmppagepath = self.social_interaction.target
-        if tmppagepath == None:
+        if tmppagepath is None:
             tmppagepath = self.page.path
 
         params.utmsn = self.social_interaction.network
 
 class TransactionRequest(Request):
     def __init__(self, config, tracker, visitor, session, transaction):
-        super(TransactionRequest, self).__init__(config, tracker, visitor, session)
-        self.transaction =  transaction
+        super(TransactionRequest, self).__init__(config, tracker,
+                                                 visitor, session)
+        self.transaction = transaction
 
     def get_type(self):
         return TransactionRequest.TYPE_TRANSACTION
     def __setattr__(self, name, value):
         if name == 'account_id':
             if value and not utils.is_valid_google_account(value):
-                raise ValueError('Given Google Analytics account ID is not valid')
+                raise ValueError(
+                    'Given Google Analytics account ID is not valid')
 
         elif name == 'campaign':
             if isinstance(value, Campaign):
                 if indx != X10.__MINIMUM and indx - 1 != last_indx:
                     tmpstr = '%s%s%s' % (tmpstr, indx, X10.__DELIM_NUM_VALUE)
 
-                tmpstr = '%s%s' % (tmpstr, self.__escape_extensible_value(entry))
+                tmpstr = '%s%s' % (
+                    tmpstr, self.__escape_extensible_value(entry))
                 result.append(tmpstr)
 
             last_indx = indx
     def render_url_string(self):
         result = ''
         for project_id, project in self.project_data.iteritems():
-            result = '%s%s%s' % (result, project_id, self.__render_project(project))
+            result = '%s%s%s' % (
+                result, project_id, self.__render_project(project))
 
         return result
 
 import os
 from setuptools import setup, find_packages
+from pyga.requests import __version__, __license__
+
 
-ver = '2.4.1'
 README = os.path.join(os.path.dirname(__file__), 'README.rst')
 long_desc = open(README).read() + '\n\n'
 
 setup(name='pyga',
-      version=ver,
+      version=__version__,
+      license=__license__,
       author='Arun K.R.',
       author_email='the1.arun@gmail.com',
       url='http://kra3.github.com/py-ga-mob/',
-      license='Simplified BSD',
       description='Server side implemenation of Google Analytics in Python.',
       long_description=long_desc,
       keywords='google analytics  mobile serverside',
       requires=[],
-      install_requires=['setuptools',],
+      install_requires=['setuptools', ],
       packages=find_packages(),
       namespace_packages=['pyga'],
       classifiers=[
         'Topic :: Internet :: WWW/HTTP',
         'Topic :: Internet :: WWW/HTTP :: WSGI',
       ],
-)
+      test_suite='tests',
+      tests_require=['mock']
+    )
+import unittest
+
+
+class TestGA(unittest.TestCase):
+
+    def test_request(self):
+        from pyga.requests import Tracker, Visitor, Session, Page
+        from mock import Mock
+        import urllib2
+
+        mocked = urllib2.urlopen = Mock()
+
+        meta = dict(
+            REMOTE_ADDR='134.321.0.1',
+            HTTP_USER_AGENT='Test User Agent 1.0',
+            HTTP_ACCEPT_LANGUAGE='en-US,en;q=0.8,ru;q=0.6',
+        )
+        tracker = Tracker('UA-0000-0000', 'test.com')
+        visitor = Visitor()
+        visitor.extract_from_server_meta(meta)
+        self.assertEqual(visitor.ip_address, '134.321.0.1')
+        self.assertEqual(visitor.locale, 'en_US')
+        self.assertEqual(visitor.user_agent, 'Test User Agent 1.0')
+        session = Session()
+        page = Page('/test_path')
+        tracker.track_pageview(page, session, visitor)
+        (request, ), _ = mocked.call_args_list.pop()
+        self.assertEqual(request.headers.get('X-forwarded-for'), '134.321.0.1')
+        self.assertEqual(request.headers.get('User-agent'), 'Test User Agent 1.0')

File tests/serialize.py

 import unittest
 from cPickle import loads, dumps
-import sys
-sys.path.insert(0, '..')
-
-from pyga.requests import Visitor
 
 
 class TestSerialize(unittest.TestCase):
         This will test if the unique_id is equals after deserialization
         even if it is not acessed before serialization
         """
+        from pyga.requests import Visitor
+
         visitor = Visitor()
         serialized_visitor = dumps(visitor)
         deserialized_visitor = loads(serialized_visitor)

File tests/utils.py

 import unittest
-import sys
-sys.path.insert(0, '..')
 
 from pyga import utils
 
 
 class TestAnonymizeIp(unittest.TestCase):
     def test_with_no_ip(self):
-    	self.assertEqual("", utils.anonymize_ip(""))
+        self.assertEqual("", utils.anonymize_ip(""))
 
     def test_with_valid_ip(self):
-    	self.assertEqual("1.2.3.0", utils.anonymize_ip("1.2.3.4"))
-    	self.assertEqual("192.168.137.0", utils.anonymize_ip("192.168.137.123"))
+        self.assertEqual("1.2.3.0", utils.anonymize_ip("1.2.3.4"))
+        self.assertEqual(
+            "192.168.137.0", utils.anonymize_ip("192.168.137.123"))
 
 
 if __name__ == '__main__':
-	unittest.main()
+    unittest.main()