Commit 6249b7d0 authored by Thom Wiggers's avatar Thom Wiggers 📐
Browse files

Merge branch 'extend-events-tests' into 'master'

Add more tests to the events app

See merge request !717
parents 67f421bb e6cf8529
......@@ -23,6 +23,11 @@ def _do_next(request, response):
class DoNextModelAdmin(TranslatedModelAdmin):
"""
This class adds processing of a `next` parameter in the urls
of the add and change admin forms. If it is set and safe this
override will redirect the user to the provided url.
"""
def response_add(self, request, obj):
res = super().response_add(request, obj)
......
......@@ -78,8 +78,8 @@ class EventCalenderJSSerializer(CalenderJSSerializer):
def _registered(self, instance):
try:
return services.is_user_registered(instance,
self.context['member'])
return services.is_user_registered(self.context['member'],
instance)
except AttributeError:
return None
......@@ -190,8 +190,8 @@ class EventListSerializer(serializers.ModelSerializer):
def _registered(self, instance):
try:
return services.is_user_registered(
instance, self.context['request'].user)
return services.is_user_registered(self.context['request'].user,
instance)
except AttributeError:
return None
......
......@@ -6,7 +6,7 @@ from events.exceptions import RegistrationError
from events.models import Registration, RegistrationInformationField
def is_user_registered(event, member):
def is_user_registered(member, event):
if not event.registration_required or not member.is_authenticated:
return None
......@@ -52,11 +52,8 @@ def is_organiser(member, event):
return True
if event and member.has_perm('events.change_event'):
committees = 0
if event is not None:
committees = member.get_committees().filter(
pk=event.organiser.pk).count()
return committees != 0
return member.get_committees().filter(
pk=event.organiser.pk).count() != 0
return False
......
......@@ -18,7 +18,7 @@ def show_cards(context):
upcoming = [{
'event': x,
'current_user_registration': services.is_user_registered(
x, context['user']),
context['user'], x),
} for x in upcoming_events[:4]]
except AttributeError:
upcoming = [{
......
import datetime
from unittest import mock
from django.contrib.admin import AdminSite
from django.http import HttpResponseRedirect
from django.test import TestCase, RequestFactory, override_settings
from django.utils import timezone
from freezegun import freeze_time
from activemembers.models import Committee, CommitteeMembership
from events.admin import (
DoNextModelAdmin,
RegistrationInformationFieldInline,
EventAdmin
)
from events.models import Event, RegistrationInformationField
from members.models import Member
class DoNextModelAdminTest(TestCase):
def setUp(self):
self.site = AdminSite()
self.admin = DoNextModelAdmin(Event, admin_site=self.site)
self.rf = RequestFactory()
@mock.patch('utils.translation.TranslatedModelAdmin.response_add')
def test_response_add(self, super_mock):
super_mock.return_value = None
request = self.rf.get('/admin/events/event/1')
response = self.admin.response_add(request, None)
self.assertIsNone(response, "Should return the original response")
request = self.rf.get('/admin/events/event/1', data={
'next': 'http://example.org',
})
response = self.admin.response_add(request, None)
self.assertNotIsInstance(response, HttpResponseRedirect,
"Should not redirect")
request = self.rf.get('/admin/events/event/1', data={
'next': '/test',
})
response = self.admin.response_add(request, None)
self.assertIsInstance(response, HttpResponseRedirect)
self.assertEqual('/test', response.url,
"Should return the url in the next parameter.")
@mock.patch('utils.translation.TranslatedModelAdmin.response_change')
def test_response_change(self, super_mock):
super_mock.return_value = None
request = self.rf.get('/admin/events/event/1')
response = self.admin.response_change(request, None)
self.assertIsNone(response, "Should return the original response")
request = self.rf.get('/admin/events/event/1', data={
'next': 'http://example.org',
})
response = self.admin.response_change(request, None)
self.assertNotIsInstance(response, HttpResponseRedirect,
"Should not redirect")
request = self.rf.get('/admin/events/event/1', data={
'next': '/test',
})
response = self.admin.response_change(request, None)
self.assertIsInstance(response, HttpResponseRedirect)
self.assertEqual('/test', response.url,
"Should return the url in the next parameter.")
@freeze_time('2017-01-01')
class RegistrationInformationFieldInlineTest(TestCase):
fixtures = ['members.json', 'committees.json']
@classmethod
def setUpTestData(cls):
cls.committee = Committee.objects.get(pk=1)
cls.event = Event.objects.create(
pk=1,
organiser=cls.committee,
title_nl='testevenement',
title_en='testevent',
description_en='desc',
description_nl='besch',
published=True,
start=(timezone.now() + datetime.timedelta(hours=1)),
end=(timezone.now() + datetime.timedelta(hours=2)),
location_en='test location',
location_nl='test locatie',
map_location='test map location',
price=0.00,
fine=0.00
)
cls.member = Member.objects.filter(last_name="Wiggers").first()
cls.member.is_superuser = True
cls.member.save()
CommitteeMembership.objects.create(
member=cls.member,
committee=cls.committee
)
RegistrationInformationField.objects.create(
pk=1,
event=cls.event,
type=RegistrationInformationField.BOOLEAN_FIELD,
name_en="test bool",
name_nl="test bool",
required=False
)
RegistrationInformationField.objects.create(
pk=2,
event=cls.event,
type=RegistrationInformationField.INTEGER_FIELD,
name_en="test int",
name_nl="test int",
required=False
)
RegistrationInformationField.objects.create(
pk=3,
event=cls.event,
type=RegistrationInformationField.TEXT_FIELD,
name_en="test text",
name_nl="test text",
required=False
)
def setUp(self):
self.site = AdminSite()
self.inline = RegistrationInformationFieldInline(Event,
self.site)
self.rf = RequestFactory()
def test_get_formset(self):
request = self.rf.get('/admin/events/event/1/change/')
request.user = self.member
formset = self.inline.get_formset(request, None)
self.assertEqual(0, formset.form.declared_fields['order'].initial)
formset = self.inline.get_formset(request, self.event)
self.assertEqual(3, formset.form.declared_fields['order'].initial)
@freeze_time('2017-01-01')
class EventAdminTest(TestCase):
fixtures = ['members.json', 'committees.json']
@classmethod
def setUpTestData(cls):
cls.committee = Committee.objects.get(pk=1)
cls.event = Event.objects.create(
pk=1,
organiser=cls.committee,
title_nl='testevenement',
title_en='testevent',
description_en='desc',
description_nl='besch',
published=True,
start=(timezone.now() + datetime.timedelta(hours=1)),
end=(timezone.now() + datetime.timedelta(hours=2)),
location_en='test location',
location_nl='test locatie',
map_location='test map location',
price=0.00,
fine=0.00
)
cls.member = Member.objects.filter(last_name="Wiggers").first()
def setUp(self):
self.admin_site = AdminSite()
self.admin = EventAdmin(Event, self.admin_site)
self.rf = RequestFactory()
def test_overview_link(self):
self.assertEqual(self.admin.overview_link(self.event),
'<a href="/events/admin/1/">testevenement</a>')
@mock.patch('events.admin.DoNextModelAdmin.has_change_permission')
@mock.patch('events.services.is_organiser')
def test_has_change_permission(self, organiser_mock, permission_mock):
permission_mock.return_value = None
organiser_mock.return_value = True
request = self.rf.get('/admin/events/event/1/change/')
request.member = self.member
res = self.admin.has_change_permission(request, None)
self.assertEqual(res, None)
res = self.admin.has_change_permission(request, self.event)
self.assertEqual(res, None)
organiser_mock.return_value = False
res = self.admin.has_change_permission(request, self.event)
self.assertEqual(res, False)
@override_settings(LANGUAGE_CODE='en')
def test_event_date(self):
self.assertEqual(self.admin.event_date(self.event),
'Sunday 01 jan 2017, 2:00')
@override_settings(LANGUAGE_CODE='en')
def test_registration_date(self):
self.assertEqual(self.admin.registration_date(self.event),
'')
self.event.registration_start = timezone.now()
self.assertEqual(self.admin.registration_date(self.event),
'Sunday 01 jan 2017, 1:00')
@override_settings(LANGUAGE_CODE='en')
def test_edit_link(self):
self.assertEqual(self.admin.edit_link(None), 'Edit')
@override_settings(LANGUAGE_CODE='en')
def test_num_participants(self):
self.assertEqual(self.admin.num_participants(self.event),
'0/∞')
self.event.max_participants = 2
self.assertEqual(self.admin.num_participants(self.event),
'0/2')
from datetime import timedelta, datetime
from unittest import mock
from django.contrib.auth.models import AnonymousUser, Permission
from django.test import TestCase
from django.utils import timezone
from freezegun import freeze_time
from activemembers.models import Committee, CommitteeMembership
from events import services
from events.exceptions import RegistrationError
from events.models import Event, Registration, RegistrationInformationField
from members.models import Member
@freeze_time('2017-01-01')
class ServicesTest(TestCase):
fixtures = ['members.json', 'committees.json']
@classmethod
def setUpTestData(cls):
cls.committee = Committee.objects.get(pk=1)
cls.event = Event.objects.create(
pk=1,
organiser=cls.committee,
title_nl='testevenement',
title_en='testevent',
description_en='desc',
description_nl='besch',
published=True,
start=(timezone.now() + timedelta(hours=1)),
end=(timezone.now() + timedelta(hours=2)),
location_en='test location',
location_nl='test locatie',
map_location='test map location',
price=0.00,
fine=0.00)
cls.member = Member.objects.filter(last_name="Wiggers").first()
cls.member.is_superuser = False
cls.member.save()
cls.perm_change_event = Permission.objects.get(
content_type__model='event',
codename='change_event')
cls.perm_override_organiser = Permission.objects.get(
content_type__model='event',
codename='override_organiser')
def setUp(self):
self.committee.refresh_from_db()
self.event.refresh_from_db()
self.member.refresh_from_db()
def _toggle_event_change_perm(self, enable):
# Refetch member to empty permissions cache
self.member = Member.objects.get(pk=self.member.pk)
if enable:
self.member.user_permissions.add(self.perm_change_event)
else:
self.member.user_permissions.remove(self.perm_change_event)
def _toggle_override_organiser_perm(self, enable):
# Refetch member to empty permissions cache
self.member = Member.objects.get(pk=self.member.pk)
if enable:
self.member.user_permissions.add(self.perm_override_organiser)
else:
self.member.user_permissions.remove(self.perm_override_organiser)
def test_is_user_registered(self):
self.assertEqual(None, services.is_user_registered(AnonymousUser(),
self.event))
self.event.registration_start = timezone.now() - timedelta(hours=1)
self.event.registration_end = timezone.now()
self.assertEqual(None, services.is_user_registered(AnonymousUser(),
self.event))
self.assertFalse(services.is_user_registered(self.member,
self.event))
Registration.objects.create(
event=self.event,
member=self.member,
date_cancelled=None
)
self.assertTrue(services.is_user_registered(self.member,
self.event))
def test_event_permissions(self):
self.event.registration_start = timezone.now() - timedelta(hours=1)
self.event.registration_end = timezone.now() + timedelta(hours=1)
self.assertEqual({
"create_registration": False,
"cancel_registration": False,
"update_registration": False,
}, services.event_permissions(AnonymousUser(), self.event))
self.member.profile.event_permissions = 'nothing'
self.assertEqual({
"create_registration": False,
"cancel_registration": False,
"update_registration": False,
}, services.event_permissions(self.member, self.event))
self.member.profile.event_permissions = 'all'
self.assertEqual({
"create_registration": True,
"cancel_registration": False,
"update_registration": False,
}, services.event_permissions(self.member, self.event))
reg = Registration.objects.create(
event=self.event,
member=self.member,
date_cancelled=None
)
self.assertEqual({
"create_registration": False,
"cancel_registration": True,
"update_registration": False,
}, services.event_permissions(self.member, self.event))
RegistrationInformationField.objects.create(
event=self.event,
type=RegistrationInformationField.BOOLEAN_FIELD,
name_nl='test',
name_en='test',
required=False
)
self.assertEqual({
"create_registration": False,
"cancel_registration": True,
"update_registration": True,
}, services.event_permissions(self.member, self.event))
reg.date_cancelled = timezone.now()
reg.save()
self.assertEqual({
"create_registration": True,
"cancel_registration": False,
"update_registration": False,
}, services.event_permissions(self.member, self.event))
def test_is_organiser(self):
self.assertFalse(services.is_organiser(AnonymousUser(), self.event))
self.assertFalse(services.is_organiser(self.member, self.event))
self.member.is_superuser = True
self.assertTrue(services.is_organiser(self.member, self.event))
self.member.is_superuser = False
self._toggle_override_organiser_perm(True)
self.assertTrue(services.is_organiser(self.member, self.event))
self._toggle_override_organiser_perm(False)
self._toggle_event_change_perm(True)
self.assertFalse(services.is_organiser(self.member, self.event))
membership = CommitteeMembership.objects.create(
member=self.member, committee=self.committee)
self.assertTrue(services.is_organiser(self.member, self.event))
self.assertFalse(services.is_organiser(self.member, None))
self._toggle_event_change_perm(False)
membership.delete()
@mock.patch('events.services.event_permissions')
def test_create_registration(self, perms_mock):
self.event.registration_start = timezone.now() - timedelta(hours=2)
self.event.registration_end = timezone.now() + timedelta(hours=1)
perms_mock.return_value = {
"create_registration": False,
"cancel_registration": False,
"update_registration": False,
}
with self.assertRaises(RegistrationError):
services.create_registration(AnonymousUser(), self.event)
perms_mock.return_value["create_registration"] = True
reg = services.create_registration(self.member, self.event)
self.assertEqual(reg.event, self.event)
self.assertEqual(reg.member, self.member)
self.assertEqual(reg.date_cancelled, None)
reg.date_cancelled = datetime(2017, 9, 1)
reg.save()
reg = services.create_registration(self.member, self.event)
self.assertEqual(reg.event, self.event)
self.assertEqual(reg.member, self.member)
self.assertEqual(reg.date_cancelled, None)
self.event.cancel_deadline = timezone.now() - timedelta(hours=1)
self.event.save()
reg.date_cancelled = timezone.now()
reg.save()
with self.assertRaises(RegistrationError):
services.create_registration(self.member, self.event)
reg.date_cancelled = None
reg.save()
services.create_registration(self.member, self.event)
perms_mock.return_value["create_registration"] = False
perms_mock.return_value["cancel_registration"] = True
with self.assertRaises(RegistrationError):
services.create_registration(self.member, self.event)
@mock.patch('events.emails.notify_organiser')
@mock.patch('events.emails.notify_first_waiting')
@mock.patch('events.services.event_permissions')
def test_cancel_registration(self, perms_mock, notify_first_mock,
notify_organiser_mock):
self.event.registration_start = timezone.now() - timedelta(hours=2)
self.event.registration_end = timezone.now() + timedelta(hours=1)
self.event.max_participants = 1
self.event.save()
perms_mock.return_value = {
"create_registration": False,
"cancel_registration": False,
"update_registration": False,
}
with self.assertRaises(RegistrationError):
services.cancel_registration(None, self.member, self.event)
registration = Registration.objects.create(
event=self.event,
member=self.member,
)
with self.assertRaises(RegistrationError):
services.cancel_registration(None, self.member, self.event)
perms_mock.return_value["cancel_registration"] = True
services.cancel_registration(None, self.member, self.event)
notify_first_mock.assert_called_once_with(None, self.event)
self.event.send_cancel_email = True
self.event.save()
services.cancel_registration(None, self.member, self.event)
self.event.cancel_deadline = timezone.make_aware(datetime(2017, 1, 1))
self.event.save()
services.cancel_registration(None, self.member, self.event)
notify_organiser_mock.assert_called_once_with(self.event, registration)
registration.refresh_from_db()
self.assertIsNotNone(registration.date_cancelled)
registration.date_cancelled = None
registration.save()
Registration.objects.create(
event=self.event,
member=Member.objects.filter(username="testuser").first(),
date=datetime(2017, 9, 1)
)
services.cancel_registration(None, self.member, self.event)
@mock.patch('events.services.event_permissions')
def test_update_registration(self, perms_mock):
self.event.registration_start = timezone.now() - timedelta(hours=2)
self.event.registration_end = timezone.now() + timedelta(hours=1)
perms_mock.return_value = {
"create_registration": False,
"cancel_registration": False,
"update_registration": False,
}
with self.assertRaises(RegistrationError):
services.update_registration(self.member, self.event, None)
registration = Registration.objects.create(
event=self.event,
member=self.member,
)
services.update_registration(self.member, self.event, None)
perms_mock.return_value["update_registration"] = True
field1 = RegistrationInformationField.objects.create(
type=RegistrationInformationField.INTEGER_FIELD,