Skip to content

Commit

Permalink
test no session, refs #4, #8
Browse files Browse the repository at this point in the history
  • Loading branch information
st4lk committed Oct 27, 2015
1 parent 9e3614a commit fe5a4e8
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 24 deletions.
9 changes: 0 additions & 9 deletions affiliate/templatetags/admin_affiliate_tags.py

This file was deleted.

6 changes: 3 additions & 3 deletions affiliate/tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
import urllib
from django.utils.http import urlencode
from django.utils.six.moves.urllib.parse import parse_qsl, urlparse, urlunparse
from . import settings as affiliate_settings
try:
Expand All @@ -23,7 +23,7 @@ def add_affiliate_code(url, aid_code):
query = dict(parse_qsl(parsed.query))
query.update({affiliate_settings.PARAM_NAME: str(aid_code)})
url_parts = list(parsed)
url_parts[4] = urllib.urlencode(query)
url_parts[4] = urlencode(query)
return urlunparse(url_parts)


Expand All @@ -32,5 +32,5 @@ def remove_affiliate_code(url):
query = dict(parse_qsl(parsed.query))
query.pop(affiliate_settings.PARAM_NAME, None)
url_parts = list(parsed)
url_parts[4] = urllib.urlencode(query)
url_parts[4] = urlencode(query)
return urlunparse(url_parts)
1 change: 1 addition & 0 deletions requirements_test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ model-mommy
freezegun
coverage
tox>=1.7.0
mock
50 changes: 38 additions & 12 deletions tests/test_affiliate_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

from django.test import TestCase
from django.utils import timezone
from django.utils.http import urlencode
from model_mommy import mommy
from freezegun import freeze_time

from affiliate.settings import PARAM_NAME, SESSION_AGE
from affiliate.settings import SESSION_AGE
from .utils import get_aid_url, modify_settings


class TestAffiliateMiddleware(TestCase):
Expand All @@ -17,31 +17,31 @@ def test_no_affiliate_in_url(self):
self.assertFalse(resp.context['request'].affiliate.exist())

def test_bad_affiliate_code(self):
resp = self.client.get(self.get_aid_url('/', 123))
resp = self.client.get(get_aid_url('/', 123))
self.assertEqual(resp.status_code, 200)
self.assertFalse(resp.context['request'].affiliate.exist())

def test_affiliate_assigned(self):
affiliate = mommy.make('affiliate.Affiliate')
resp = self.client.get(self.get_aid_url('/', affiliate.aid))
resp = self.client.get(get_aid_url('/', affiliate.aid))
self.assertEqual(resp.status_code, 200)
affiliate_resp = resp.context['request'].affiliate
self.assertTrue(affiliate_resp.exist())
self.assertEqual(affiliate.aid, affiliate_resp.aid)

def test_previous_affiliate_is_used(self):
affiliate = mommy.make('affiliate.Affiliate')
resp = self.client.get(self.get_aid_url('/', affiliate.aid))
resp = self.client.get(get_aid_url('/', affiliate.aid))
self.assertEqual(resp.status_code, 200)
resp = self.client.get(self.get_aid_url('/', affiliate.aid + 100)) # invalid aid code
resp = self.client.get(get_aid_url('/', affiliate.aid + 100)) # invalid aid code
self.assertEqual(resp.status_code, 200)
affiliate_resp = resp.context['request'].affiliate
self.assertTrue(affiliate_resp.exist())
self.assertEqual(affiliate.aid, affiliate_resp.aid)

def test_affiliate_saved_in_session(self):
affiliate = mommy.make('affiliate.Affiliate')
self.client.get(self.get_aid_url('/', affiliate.aid))
self.client.get(get_aid_url('/', affiliate.aid))

# next response without aid still contains affiliate
with freeze_time(timezone.now() + timedelta(seconds=SESSION_AGE - 1)):
Expand All @@ -54,7 +54,7 @@ def test_affiliate_saved_in_session(self):

def test_affiliate_session_expired(self):
affiliate = mommy.make('affiliate.Affiliate')
self.client.get(self.get_aid_url('/', affiliate.aid))
self.client.get(get_aid_url('/', affiliate.aid))

# affiliate is expired
with freeze_time(timezone.now() + timedelta(seconds=SESSION_AGE + 1)):
Expand All @@ -65,15 +65,41 @@ def test_affiliate_session_expired(self):

def test_previous_affiliate_session_expired(self):
affiliate = mommy.make('affiliate.Affiliate')
resp = self.client.get(self.get_aid_url('/', affiliate.aid))
resp = self.client.get(get_aid_url('/', affiliate.aid))
self.assertEqual(resp.status_code, 200)

# affiliate is expired
with freeze_time(timezone.now() + timedelta(seconds=SESSION_AGE + 1)):
resp = self.client.get(self.get_aid_url('/', affiliate.aid + 100)) # invalid aid code
resp = self.client.get(get_aid_url('/', affiliate.aid + 100)) # invalid aid code

self.assertEqual(resp.status_code, 200)
self.assertFalse(resp.context['request'].affiliate.exist())

def get_aid_url(self, url, aid_code):
return '?'.join([url, urlencode({PARAM_NAME: aid_code})])

@modify_settings(MIDDLEWARE_CLASSES={
'remove': [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
],
}, INSTALLED_APPS={
'remove': [
'django.contrib.sessions'
]
})
class TestAffiliateMiddlewareNoSession(TestCase):
def test_no_session_affiliate_in_url(self):
from affiliate import settings as affiliate_settings
affiliate_settings.SAVE_IN_SESSION = False

affiliate = mommy.make('affiliate.Affiliate')
resp = self.client.get(get_aid_url('/', affiliate.aid))
self.assertEqual(resp.status_code, 200)
affiliate_resp = resp.context['request'].affiliate
self.assertTrue(affiliate_resp.exist())
self.assertEqual(affiliate.aid, affiliate_resp.aid)

# next request can't remember previous affiliate
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
self.assertFalse(resp.context['request'].affiliate.exist())
58 changes: 58 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from django.utils.http import urlencode
from affiliate.settings import PARAM_NAME


def get_aid_url(url, aid_code):
return '?'.join([url, urlencode({PARAM_NAME: aid_code})])


try:
from django.test import modify_settings
except ImportError:
from django.test.utils import override_settings, settings, six

class modify_settings(override_settings):
"""
Like override_settings, but makes it possible to append, prepend or remove
items instead of redefining the entire list.
"""
def __init__(self, *args, **kwargs):
if args:
# Hack used when instantiating from SimpleTestCase._pre_setup.
assert not kwargs
self.operations = args[0]
else:
assert not args
self.operations = list(kwargs.items())

def save_options(self, test_func):
if test_func._modified_settings is None:
test_func._modified_settings = self.operations
else:
# Duplicate list to prevent subclasses from altering their parent.
test_func._modified_settings = list(
test_func._modified_settings) + self.operations

def enable(self):
self.options = {}
for name, operations in self.operations:
try:
# When called from SimpleTestCase._pre_setup, values may be
# overridden several times; cumulate changes.
value = self.options[name]
except KeyError:
value = list(getattr(settings, name, []))
for action, items in operations.items():
# items my be a single value or an iterable.
if isinstance(items, six.string_types):
items = [items]
if action == 'append':
value = value + [item for item in items if item not in value]
elif action == 'prepend':
value = [item for item in items if item not in value] + value
elif action == 'remove':
value = [item for item in value if item not in items]
else:
raise ValueError("Unsupported action: %s" % action)
self.options[name] = value
super(modify_settings, self).enable()

0 comments on commit fe5a4e8

Please sign in to comment.