Restructure our python module. A lot.

This commit is contained in:
Raphael Michel
2015-02-14 17:55:13 +01:00
parent cf18f3e200
commit 077413f41c
117 changed files with 193 additions and 163 deletions

View File

@@ -0,0 +1,110 @@
import os
import sys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.conf import settings
from selenium import webdriver
RUN_LOCAL = ('SAUCE_USERNAME' not in os.environ)
"""
For a long time, we used SauceLabs for CI testing, because they provide free
browser VMs for Open Source projects. However, more tests failed because of
connection timeouts to SauceLabs than for real reasons, so we're using
PhantomJS now. However, we'll keep the SauceClient code here as it might prove
useful some day.
"""
if RUN_LOCAL:
# could add Chrome, Firefox, etc... here
BROWSERS = [os.environ.get('TEST_BROWSER', 'PhantomJS')]
else:
from sauceclient import SauceClient
USERNAME = os.environ.get('SAUCE_USERNAME')
ACCESS_KEY = os.environ.get('SAUCE_ACCESS_KEY')
sauce = SauceClient(USERNAME, ACCESS_KEY)
BROWSERS = [
{"platform": "Mac OS X 10.9",
"browserName": "chrome",
"version": "35"},
{"platform": "Windows 8.1",
"browserName": "internet explorer",
"version": "11"},
{"platform": "Linux",
"browserName": "firefox",
"version": "29"}]
def on_platforms():
if RUN_LOCAL:
def decorator(base_class):
module = sys.modules[base_class.__module__].__dict__
for i, platform in enumerate(BROWSERS):
d = dict(base_class.__dict__)
d['browser'] = platform
name = "%s_%s" % (base_class.__name__, i + 1)
module[name] = type(name, (base_class,), d)
pass
return decorator
def decorator(base_class):
module = sys.modules[base_class.__module__].__dict__
for i, platform in enumerate(BROWSERS):
d = dict(base_class.__dict__)
d['desired_capabilities'] = platform
name = "%s_%s" % (base_class.__name__, i + 1)
module[name] = type(name, (base_class,), d)
return decorator
class BrowserTest(StaticLiveServerTestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
settings.DEBUG = ('--debug' in sys.argv)
def setUp(self):
if RUN_LOCAL:
self.setUpLocal()
else:
self.setUpSauce()
def tearDown(self):
if RUN_LOCAL:
self.tearDownLocal()
else:
self.tearDownSauce()
def setUpSauce(self):
if 'TRAVIS_JOB_NUMBER' in os.environ:
self.desired_capabilities['tunnel-identifier'] = \
os.environ['TRAVIS_JOB_NUMBER']
self.desired_capabilities['build'] = os.environ['TRAVIS_BUILD_NUMBER']
self.desired_capabilities['tags'] = \
[os.environ['TRAVIS_PYTHON_VERSION'], 'CI']
self.desired_capabilities['name'] = self.id()
sauce_url = "http://%s:%s@ondemand.saucelabs.com:80/wd/hub"
self.driver = webdriver.Remote(
desired_capabilities=self.desired_capabilities,
command_executor=sauce_url % (USERNAME, ACCESS_KEY)
)
self.driver.implicitly_wait(5)
def setUpLocal(self):
self.driver = getattr(webdriver, self.browser)()
self.driver.implicitly_wait(3)
def tearDownLocal(self):
self.driver.quit()
def tearDownSauce(self):
print("\nLink to your job: \n "
"https://saucelabs.com/jobs/%s \n" % self.driver.session_id)
try:
if sys.exc_info() == (None, None, None):
sauce.jobs.update_job(self.driver.session_id, passed=True)
else:
sauce.jobs.update_job(self.driver.session_id, passed=False)
finally:
self.driver.quit()

View File

@@ -0,0 +1,47 @@
import random
from django.test import TestCase
from django.core.cache import cache as django_cache
from django.utils.timezone import now
from pretix.base.models import Event, Organizer
class CacheTest(TestCase):
"""
This test case tests the invalidation of the event related
cache.
"""
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
self.cache = self.event.get_cache()
randint = random.random()
self.testkey = "test" + str(randint)
def test_interference(self):
django_cache.clear()
self.cache.set(self.testkey, "foo")
self.assertIsNone(django_cache.get(self.testkey))
self.assertIn(self.cache.get(self.testkey), (None, "foo"))
def test_longkey(self):
self.cache.set(self.testkey * 100, "foo")
self.assertEquals(self.cache.get(self.testkey * 100), "foo")
def test_invalidation(self):
self.cache.set(self.testkey, "foo")
self.cache.clear()
self.assertIsNone(self.cache.get(self.testkey))
def test_many(self):
inp = {
'a': 'foo',
'b': 'bar',
}
self.cache.set_many(inp)
self.assertEquals(inp, self.cache.get_many(inp.keys()))

View File

@@ -0,0 +1,72 @@
from django.test import TestCase, Client
from django.utils.timezone import now
from django.conf import settings
from pretix.base.models import Event, Organizer, User
class LocaleDeterminationTest(TestCase):
"""
This test case tests various methods around the properties /
variations concept.
"""
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
self.TEST_LOCALE = 'de' if settings.LANGUAGE_CODE == 'en' else 'en'
self.TEST_LOCALE_LONG = 'de-AT' if settings.LANGUAGE_CODE == 'en' else 'en-NZ'
self.user = User.objects.create_user('dummy@dummy.dummy', 'dummy@dummy.dummy', 'dummy')
def test_global_default(self):
c = Client()
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, settings.LANGUAGE_CODE)
def test_browser_default(self):
c = Client(HTTP_ACCEPT_LANGUAGE=self.TEST_LOCALE)
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, self.TEST_LOCALE)
c = Client(HTTP_ACCEPT_LANGUAGE=self.TEST_LOCALE_LONG)
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, self.TEST_LOCALE)
def test_unknown_browser_default(self):
c = Client(HTTP_ACCEPT_LANGUAGE='sjn')
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, settings.LANGUAGE_CODE)
def test_cookie_settings(self):
c = Client()
cookies = c.cookies
cookies[settings.LANGUAGE_COOKIE_NAME] = self.TEST_LOCALE
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, self.TEST_LOCALE)
cookies[settings.LANGUAGE_COOKIE_NAME] = self.TEST_LOCALE_LONG
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, self.TEST_LOCALE)
def test_user_settings(self):
c = Client()
self.user.locale = self.TEST_LOCALE
self.user.save()
response = c.post('/control/login', {
'email': 'dummy@dummy.dummy',
'password': 'dummy',
})
self.assertEqual(response.status_code, 302)
response = c.get('/control/login')
language = response['Content-Language']
self.assertEqual(language, self.TEST_LOCALE)

View File

@@ -0,0 +1,294 @@
from datetime import timedelta
from django.test import TestCase
from django.utils.timezone import now
from pretix.base.models import (
Event, Organizer, Item, ItemVariation,
Property, PropertyValue, User, Quota,
Order, OrderPosition, CartPosition
)
from pretix.base.types import VariationDict
class ItemVariationsTest(TestCase):
"""
This test case tests various methods around the properties /
variations concept.
"""
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
p = Property.objects.create(event=self.event, name='Size')
PropertyValue.objects.create(prop=p, value='S')
PropertyValue.objects.create(prop=p, value='M')
PropertyValue.objects.create(prop=p, value='L')
p = Property.objects.create(event=self.event, name='Color')
PropertyValue.objects.create(prop=p, value='black')
PropertyValue.objects.create(prop=p, value='blue')
def test_variationdict(self):
i = Item.objects.create(event=self.event, name='Dummy')
p = Property.objects.get(event=self.event, name='Size')
i.properties.add(p)
iv = ItemVariation.objects.create(item=i)
pv = PropertyValue.objects.get(prop=p, value='S')
iv.values.add(pv)
variations = i.get_all_variations()
for vd in variations:
for i, v in vd.relevant_items():
self.assertIs(type(v), PropertyValue)
for v in vd.relevant_values():
self.assertIs(type(v), PropertyValue)
if vd[p.pk] == pv:
vd1 = vd
vd2 = VariationDict()
vd2[p.pk] = pv
self.assertEqual(vd2.identify(), vd1.identify())
self.assertEqual(vd2, vd1)
vd2[p.pk] = PropertyValue.objects.get(prop=p, value='M')
self.assertNotEqual(vd2.identify(), vd.identify())
self.assertNotEqual(vd2, vd1)
vd3 = vd2.copy()
self.assertEqual(vd3, vd2)
vd2[p.pk] = pv
self.assertNotEqual(vd3, vd2)
vd4 = VariationDict()
vd4[4] = 'b'
vd4[2] = 'a'
self.assertEqual(vd4.ordered_values(), ['a', 'b'])
def test_get_all_variations(self):
i = Item.objects.create(event=self.event, name='Dummy')
# No properties available
v = i.get_all_variations()
self.assertEqual(len(v), 1)
self.assertEqual(v[0], {})
# One property, no variations
p = Property.objects.get(event=self.event, name='Size')
i.properties.add(p)
v = i.get_all_variations()
self.assertIs(type(v), list)
self.assertEqual(len(v), 3)
values = []
for var in v:
self.assertIs(type(var), VariationDict)
self.assertIn(p.pk, var)
self.assertIs(type(var[p.pk]), PropertyValue)
values.append(var[p.pk].value)
self.assertEqual(sorted(values), sorted(['S', 'M', 'L']))
# One property, one variation
iv = ItemVariation.objects.create(item=i)
iv.values.add(PropertyValue.objects.get(prop=p, value='S'))
v = i.get_all_variations()
self.assertIs(type(v), list)
self.assertEqual(len(v), 3)
values = []
num_variations = 0
for var in v:
self.assertIs(type(var), VariationDict)
if 'variation' in var and type(var['variation']) is ItemVariation:
self.assertEqual(iv.pk, var['variation'].pk)
values.append(var['variation'].values.all()[0].value)
num_variations += 1
elif p.pk in var:
self.assertIs(type(var[p.pk]), PropertyValue)
values.append(var[p.pk].value)
self.assertEqual(sorted(values), sorted(['S', 'M', 'L']))
self.assertEqual(num_variations, 1)
# Two properties, one variation
p2 = Property.objects.get(event=self.event, name='Color')
i.properties.add(p2)
iv.values.add(PropertyValue.objects.get(prop=p2, value='black'))
v = i.get_all_variations()
self.assertIs(type(v), list)
self.assertEqual(len(v), 6)
values = []
num_variations = 0
for var in v:
self.assertIs(type(var), VariationDict)
if 'variation' in var:
self.assertEqual(iv.pk, var['variation'].pk)
values.append(sorted([ivv.value for ivv in iv.values.all()]))
self.assertEqual(sorted([ivv.value for ivv in iv.values.all()]), sorted(['S', 'black']))
num_variations += 1
else:
values.append(sorted([pv.value for pv in var.values()]))
self.assertEqual(sorted(values), sorted([
['S', 'black'],
['S', 'blue'],
['M', 'black'],
['M', 'blue'],
['L', 'black'],
['L', 'blue'],
]))
self.assertEqual(num_variations, 1)
class VersionableTestCase(TestCase):
def test_shallow_cone(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
old = Item.objects.create(event=event, name='Dummy', default_price=14)
prop = Property.objects.create(event=event, name='Size')
old.properties.add(prop)
new = old.clone_shallow()
self.assertIsNone(new.version_end_date)
self.assertIsNotNone(old.version_end_date)
self.assertEqual(new.properties.count(), 0)
self.assertEqual(old.properties.count(), 1)
class UserTestCase(TestCase):
def test_identifier_local(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
u = User(event=event, username='tester')
u.set_password("test")
u.save()
self.assertEqual(u.identifier, "%s@%s.event.pretix" % (u.username.lower(), event.id))
def test_identifier_global(self):
u = User(email='test@example.com')
u.set_password("test")
u.save()
self.assertEqual(u.identifier, "test@example.com")
class QuotaTestCase(TestCase):
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
self.quota = Quota.objects.create(name="Test", size=2, event=self.event)
self.item1 = Item.objects.create(event=self.event, name="Ticket")
self.item2 = Item.objects.create(event=self.event, name="T-Shirt")
p = Property.objects.create(event=self.event, name='Size')
pv1 = PropertyValue.objects.create(prop=p, value='S')
PropertyValue.objects.create(prop=p, value='M')
PropertyValue.objects.create(prop=p, value='L')
self.var1 = ItemVariation.objects.create(item=self.item2)
self.var1.values.add(pv1)
self.item2.properties.add(p)
def test_available(self):
self.quota.items.add(self.item1)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 2))
self.quota.items.add(self.item2)
self.quota.variations.add(self.var1)
try:
self.item2.check_quotas()
self.assertTrue(False)
except:
pass
self.assertEqual(self.var1.check_quotas(), (Quota.AVAILABILITY_OK, 2))
def test_sold_out(self):
self.quota.items.add(self.item1)
order = Order.objects.create(event=self.event, status=Order.STATUS_PAID,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_GONE, 0))
self.quota.items.add(self.item2)
self.quota.variations.add(self.var1)
self.quota.size = 3
self.quota.save()
self.assertEqual(self.var1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
order = Order.objects.create(event=self.event, status=Order.STATUS_PAID,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item2, variation=self.var1, price=2)
self.assertEqual(self.var1.check_quotas(), (Quota.AVAILABILITY_GONE, 0))
def test_ordered(self):
self.quota.items.add(self.item1)
order = Order.objects.create(event=self.event, status=Order.STATUS_PAID,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
order = Order.objects.create(event=self.event, status=Order.STATUS_PENDING,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_ORDERED, 0))
order.expires = now() - timedelta(days=3)
order.save()
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
def test_reserved(self):
self.quota.items.add(self.item1)
self.quota.size = 3
self.quota.save()
order = Order.objects.create(event=self.event, status=Order.STATUS_PAID,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 2))
order = Order.objects.create(event=self.event, status=Order.STATUS_PENDING,
expires=now() + timedelta(days=3),
total=4)
OrderPosition.objects.create(order=order, item=self.item1, price=2)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
cp = CartPosition.objects.create(event=self.event, item=self.item1, price=2,
expires=now() + timedelta(days=3))
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_RESERVED, 0))
cp.expires = now() - timedelta(days=3)
cp.save()
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
self.quota.items.add(self.item2)
self.quota.variations.add(self.var1)
cp = CartPosition.objects.create(event=self.event, item=self.item2, variation=self.var1,
price=2, expires=now() + timedelta(days=3))
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_RESERVED, 0))
def test_multiple(self):
self.quota.items.add(self.item1)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 2))
quota2 = Quota.objects.create(event=self.event, name="Test 2", size=1)
quota2.items.add(self.item1)
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_OK, 1))
quota2.size = 0
quota2.save()
self.assertEqual(self.item1.check_quotas(), (Quota.AVAILABILITY_GONE, 0))

View File

@@ -0,0 +1,57 @@
from django.test import TestCase
from django.utils.timezone import now
from django.conf import settings
from pretix.base.models import Event, Organizer
from pretix.base.plugins import get_all_plugins
from pretix.base.signals import determine_availability
class PluginRegistryTest(TestCase):
"""
This test case performs tests for the plugin registry.
"""
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
def test_plugin_names(self):
for mod in get_all_plugins():
self.assertIn(mod.module, settings.INSTALLED_APPS)
def test_metadata(self):
for mod in get_all_plugins():
self.assertTrue(hasattr(mod, 'name'))
self.assertTrue(hasattr(mod, 'version'))
self.assertTrue(hasattr(mod, 'type'))
class PluginSignalTest(TestCase):
"""
This test case tests the EventPluginSignal handler
"""
def setUp(self):
o = Organizer.objects.create(name='Dummy', slug='dummy')
self.event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(),
)
def test_no_plugins_active(self):
self.event.plugins = ''
self.event.save()
responses = determine_availability.send(self.event)
self.assertEqual(len(responses), 0)
def test_one_plugin_active(self):
self.event.plugins = 'pretix.plugins.testdummy'
self.event.save()
payload = {'foo': 'bar'}
responses = determine_availability.send(self.event, **payload)
self.assertEqual(len(responses), 1)
self.assertIn('pretix.plugins.testdummy.signals', [r[0].__module__ for r in responses])