From 0995cb3d314e20033ea3b5b0152fec77e9d1c01d Mon Sep 17 00:00:00 2001 From: Becky Smith Date: Sat, 13 Jul 2024 23:30:34 +0100 Subject: [PATCH] Speeding up studioadmin tests --- booking/tests/test_waiting_list.py | 4 +- studioadmin/tests/test_views/helpers.py | 40 +- .../test_views/test_activity_log_views.py | 126 ++-- .../tests/test_views/test_block_views.py | 81 +-- .../tests/test_views/test_disclaimer_views.py | 67 +- .../test_views/test_email_users_views.py | 75 ++- .../tests/test_views/test_event_views.py | 269 ++------ .../test_views/test_mailing_list_views.py | 13 +- .../tests/test_views/test_misc_views.py | 110 +--- .../test_views/test_notification_views.py | 2 +- .../tests/test_views/test_register_views.py | 390 ++++++------ .../tests/test_views/test_setup_views.py | 2 - .../test_views/test_ticketed_events_views.py | 593 ++++++------------ .../tests/test_views/test_timetable_views.py | 262 +++----- .../test_views/test_user_blocks_views.py | 112 +--- .../test_views/test_user_bookings_views.py | 299 +++------ .../tests/test_views/test_user_views.py | 14 +- .../tests/test_views/test_voucher_views.py | 7 +- 18 files changed, 822 insertions(+), 1644 deletions(-) diff --git a/booking/tests/test_waiting_list.py b/booking/tests/test_waiting_list.py index bdef4b2c..1de63463 100644 --- a/booking/tests/test_waiting_list.py +++ b/booking/tests/test_waiting_list.py @@ -7,9 +7,7 @@ from django.test import TestCase, override_settings from booking.models import Booking, WaitingListUser -from common.tests.helpers import _create_session, TestSetupMixin -from studioadmin.tests.test_views import TestPermissionMixin -from studioadmin.views import user_bookings_view_old +from common.tests.helpers import TestSetupMixin class WaitingListTests(TestSetupMixin, TestCase): diff --git a/studioadmin/tests/test_views/helpers.py b/studioadmin/tests/test_views/helpers.py index c3377bd6..fabd0061 100644 --- a/studioadmin/tests/test_views/helpers.py +++ b/studioadmin/tests/test_views/helpers.py @@ -1,42 +1,14 @@ -from unittest.mock import Mock, patch - -from django.test import RequestFactory -from django.contrib.auth.models import Permission, Group, User - from accounts.models import DisclaimerContent -from common.tests.helpers import set_up_fb +from common.tests.helpers import create_configured_user class TestPermissionMixin(object): - def setUp(self): - set_up_fb() - self.factory = RequestFactory() - self.user =User.objects.create_user( - username='testnonstaffuser', email='nonstaff@test.com', - password='test' - ) - self.staff_user = User.objects.create_user( - username='testuser', email='test@test.com', password='test' - ) - self.staff_user.is_staff = True - self.staff_user.save() - self.instructor_user = User.objects.create_user( - username='testinstructoruser', email='instructor@test.com', - password='test' - ) - perm = Permission.objects.get(codename="can_view_registers") - group, _ = Group.objects.get_or_create(name="instructors") - group.permissions.add(perm) - self.instructor_user.groups.add(group) + @classmethod + def setUpTestData(cls): + cls.user = create_configured_user("test", "user@example.com", "test") + cls.instructor_user = create_configured_user("instructor", "instructor@example.com", "test", instructor=True) + cls.staff_user = create_configured_user("staff", "staff@example.com", "test", staff=True) # Make sure we have a current disclaimer content DisclaimerContent.objects.create(version=None) - - mockresponse = Mock() - mockresponse.status_code = 200 - self.patcher = patch('requests.request', return_value = mockresponse) - self.mock_request = self.patcher.start() - - def tearDown(self): - self.patcher.stop() diff --git a/studioadmin/tests/test_views/test_activity_log_views.py b/studioadmin/tests/test_views/test_activity_log_views.py index 072234f0..5a887826 100644 --- a/studioadmin/tests/test_views/test_activity_log_views.py +++ b/studioadmin/tests/test_views/test_activity_log_views.py @@ -5,22 +5,25 @@ from django.urls import reverse from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from activitylog.models import ActivityLog -from common.tests.helpers import _create_session -from studioadmin.views import ActivityLogListView from studioadmin.tests.test_views.helpers import TestPermissionMixin class ActivityLogListViewTests(TestPermissionMixin, TestCase): + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:activitylog') + def setUp(self): super(ActivityLogListViewTests, self).setUp() - # 10 logs - # 3 logs when self.user, self.instructor_user and self.staff_user - # are created in setUp + # 15 logs + # 1 for DP creation + # 6 logs when self.user, self.instructor_user and self.staff_user + # are created in setUp (create user and sign DP agreement) # 1 for disclaimer content creation # 2 for empty cron jobs # 3 with log messages to test search text @@ -47,24 +50,13 @@ def setUp(self): log='Log with test date for search' ) - def _get_response(self, user, form_data={}): - url = reverse('studioadmin:activitylog') - session = _create_session() - request = self.factory.get(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = ActivityLogListView.as_view() - return view(request) - def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:activitylog') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -72,7 +64,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -81,7 +74,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -89,63 +83,50 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_empty_cron_job_logs_filtered_by_default(self): - resp = self._get_response(self.staff_user) - self.assertEqual(len(resp.context_data['logs']), 9) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) + self.assertEqual(len(resp.context_data['logs']), 13) def test_filter_out_empty_cron_job_logs(self): - resp = self._get_response( - self.staff_user, {'hide_empty_cronjobs': True} - ) - self.assertEqual(len(resp.context_data['logs']), 9) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?hide_empty_cronjobs=True") + self.assertEqual(len(resp.context_data['logs']), 13) def test_search_text(self): - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'message1'}) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search=message1") self.assertEqual(len(resp.context_data['logs']), 1) - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'message'}) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search=message") self.assertEqual(len(resp.context_data['logs']), 3) def test_search_is_case_insensitive(self): - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'Message'}) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search=Message") self.assertEqual(len(resp.context_data['logs']), 3) def test_search_date(self): - resp = self._get_response( - self.staff_user, { - 'search_submitted': 'Search', - 'search_date': '01-Jan-2015' - } - ) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search_date=01-Jan-2015") self.assertEqual(len(resp.context_data['logs']), 2) def test_invalid_search_date_format(self): """ invalid search date returns all results and a message """ - resp = self._get_response( - self.staff_user, { - 'search_submitted': 'Search', - 'search_date': '01-34-2015'} - ) - self.assertEqual(len(resp.context_data['logs']), 11) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search_date=01-34-2015") + self.assertEqual(len(resp.context_data['logs']), 15) def test_search_date_and_text(self): - resp = self._get_response( - self.staff_user, { - 'search_submitted': 'Search', - 'search_date': '01-Jan-2015', - 'search': 'test date for search'} - ) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search_date=01-Jan-2015&search=test date for search") self.assertEqual(len(resp.context_data['logs']), 1) def test_search_date_and_text_with_pagination(self): @@ -166,19 +147,14 @@ def test_search_multiple_terms(self): """ Search with multiple terms returns only logs that contain all terms """ - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'Message'}) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search=Message") self.assertEqual(len(resp.context_data['logs']), 3) - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'Message One'}) + resp = self.client.get(self.url + "?search_submitted=Search&search=Message One") self.assertEqual(len(resp.context_data['logs']), 1) - resp = self._get_response(self.staff_user, { - 'search_submitted': 'Search', - 'search': 'test one'}) + resp = self.client.get(self.url + "?search_submitted=Search&search=test one") self.assertEqual(len(resp.context_data['logs']), 1) def test_reset(self): @@ -186,20 +162,8 @@ def test_reset(self): Test that reset button resets the search text and date and excludes empty cron job messages """ - resp = self._get_response( - self.staff_user, { - 'search_submitted': 'Search', - 'search_date': '01-Jan-2015', - 'search': 'test date for search' - } - ) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url + "?search_submitted=Search&search_date=01-Jan-2015&search=test date for search") self.assertEqual(len(resp.context_data['logs']), 1) - - resp = self._get_response( - self.staff_user, { - 'search_date': '01-Jan-2015', - 'search': 'test date for search', - 'reset': 'Reset' - } - ) - self.assertEqual(len(resp.context_data['logs']), 9) + resp = self.client.get(self.url + "?search_date=01-Jan-2015&search=test date for search&reset=Reset") + self.assertEqual(len(resp.context_data['logs']), 13) diff --git a/studioadmin/tests/test_views/test_block_views.py b/studioadmin/tests/test_views/test_block_views.py index b7c98b72..c9f2e1a8 100644 --- a/studioadmin/tests/test_views/test_block_views.py +++ b/studioadmin/tests/test_views/test_block_views.py @@ -5,31 +5,26 @@ from django.urls import reverse from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from booking.models import Block -from common.tests.helpers import _create_session -from studioadmin.views import BlockListView from studioadmin.tests.test_views.helpers import TestPermissionMixin class BlockListViewTests(TestPermissionMixin, TestCase): - def _get_response(self, user, form_data={}): - url = reverse('studioadmin:blocks') - session = _create_session() - request = self.factory.get(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = BlockListView.as_view() - return view(request) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:blocks') + + def setUp(self): + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse('studioadmin:blocks') resp = self.client.get(url) redirected_url = reverse('account_login') + "?next={}".format(url) @@ -40,7 +35,9 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.logout() + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -49,7 +46,9 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user) + self.client.logout() + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -57,7 +56,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_current_blocks_returned_on_get(self): @@ -73,7 +72,7 @@ def test_current_blocks_returned_on_get(self): ) baker.make_recipe('booking.booking', block=full_block) - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual( list(resp.context_data['blocks']), list(Block.objects.filter( @@ -123,23 +122,17 @@ def test_block_status_filter(self): baker.make_recipe('booking.booking', block=block) # all blocks - resp = self._get_response( - self.staff_user, form_data={'block_status': 'all'} - ) + resp = self.client.get(self.url, {'block_status': 'all'}) self.assertCountEqual( list(resp.context_data['blocks']), list(Block.objects.all().order_by('user__first_name')) ) # unknown status returns all - resp = self._get_response( - self.staff_user, form_data={'block_status': 'foo'} - ) + resp = self.client.get(self.url, {'block_status': 'foo'}) assert len(resp.context_data['blocks']) == Block.objects.count() # active blocks are paid and not expired - resp = self._get_response( - self.staff_user, form_data={'block_status': 'active'} - ) + resp = self.client.get(self.url, {'block_status': 'active'}) active = active_blocks + transferred_blocks1 + transferred_blocks2 self.assertCountEqual( list(resp.context_data['blocks']), @@ -152,9 +145,7 @@ def test_block_status_filter(self): # unpaid blocks are unpaid but not expired; should not show any # from unpaid_expired_blocks - resp = self._get_response( - self.staff_user, form_data={'block_status': 'unpaid'} - ) + resp = self.client.get(self.url, {'block_status': 'unpaid'}) self.assertCountEqual( list(resp.context_data['blocks']), list( @@ -165,9 +156,7 @@ def test_block_status_filter(self): ) #current blocks are paid or unpaid, not expired, not full - resp = self._get_response( - self.staff_user, form_data={'block_status': 'current'} - ) + resp = self.client.get(self.url, {'block_status': 'current'}) self.assertCountEqual( list(resp.context_data['blocks']), list(Block.objects.filter( @@ -177,9 +166,7 @@ def test_block_status_filter(self): ) # expired blocks are past expiry date or full - resp = self._get_response( - self.staff_user, form_data={'block_status': 'expired'} - ) + resp = self.client.get(self.url, {'block_status': 'expired'}) expired = expired_blocks + unpaid_expired_blocks + full_blocks self.assertCountEqual( list(resp.context_data['blocks']), @@ -191,9 +178,7 @@ def test_block_status_filter(self): ) # transferred blocks - resp = self._get_response( - self.staff_user, form_data={'block_status': 'transfers'} - ) + resp = self.client.get(self.url, {'block_status': 'transfers'}) transfers = transferred_blocks1 + transferred_blocks2 self.assertCountEqual( list(resp.context_data['blocks']), @@ -211,14 +196,10 @@ def test_transferred_from_display(self): block_type__size=1, block_type__identifier='transferred', transferred_booking_id='182893429' ) - resp = self._get_response( - self.staff_user, form_data={'block_status': 'transfers'} - ) + resp = self.client.get(self.url, {'block_status': 'transfers'}) self.assertIn('(182893429)', resp.rendered_content) - resp = self._get_response( - self.staff_user, form_data={'block_status': 'all'} - ) + resp = self.client.get(self.url, {'block_status': 'all'}) self.assertNotIn('(182893429)', resp.rendered_content) def test_transferred_from_display_with_valid_booking(self): @@ -230,9 +211,7 @@ def test_transferred_from_display_with_valid_booking(self): block_type__size=1, block_type__identifier='transferred', transferred_booking_id=booking.id ) - resp = self._get_response( - self.staff_user, form_data={'block_status': 'transfers'} - ) + resp = self.client.get(self.url, {'block_status': 'transfers'}) self.assertIn( '{} {} ({})'.format( booking.event.name, booking.event.date.strftime('%d%b%y'), @@ -241,9 +220,7 @@ def test_transferred_from_display_with_valid_booking(self): resp.rendered_content ) - resp = self._get_response( - self.staff_user, form_data={'block_status': 'all'} - ) + resp = self.client.get(self.url, {'block_status': 'all'}) self.assertNotIn( '{} {} ({})'.format( booking.event.name, booking.event.date.strftime('%d%b%y'), @@ -257,11 +234,11 @@ def test_block_type_identfier_display(self): 'booking.block', paid=True, block_type__size=1, block_type__identifier='transferred', ) - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertIn('(transfer)', resp.rendered_content) baker.make_recipe( 'booking.block', paid=True, block_type__identifier='other id' ) - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertIn('(other id)', resp.rendered_content) diff --git a/studioadmin/tests/test_views/test_disclaimer_views.py b/studioadmin/tests/test_views/test_disclaimer_views.py index f2e6840e..1d201ff9 100644 --- a/studioadmin/tests/test_views/test_disclaimer_views.py +++ b/studioadmin/tests/test_views/test_disclaimer_views.py @@ -11,23 +11,17 @@ from django.core.exceptions import ValidationError from django.urls import reverse from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from accounts.models import DisclaimerContent, NonRegisteredDisclaimer, OnlineDisclaimer -from common.tests.helpers import _create_session, format_content +from common.tests.helpers import format_content from studioadmin.utils import int_str, chaffify -from studioadmin.views import ( - user_disclaimer, - DisclaimerDeleteView, - DisclaimerUpdateView -) from studioadmin.tests.test_views.helpers import TestPermissionMixin class UserDisclamersTests(TestPermissionMixin, TestCase): def setUp(self): - super(UserDisclamersTests, self).setUp() + super().setUp() self.user.set_password('password') self.user.save() self.disclaimer = baker.make( @@ -56,38 +50,15 @@ def setUp(self): 'age_over_18_confirmed': True, 'password': 'password' } + self.client.force_login(self.staff_user) def _get_user_disclaimer(self, user, encoded_user_id): + self.client.force_login(user) url = reverse('studioadmin:user_disclaimer', args=[encoded_user_id]) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return user_disclaimer(request, encoded_user_id=encoded_user_id) - - def _get_response(self, url, view, user, encoded_user_id): - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = view.as_view() - return view(request, encoded_user_id=encoded_user_id) - - def _post_response(self, url, view, user, encoded_user_id, form_data): - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = view.as_view() - return view(request, encoded_user_id=encoded_user_id) + return self.client.get(url) def test_only_staff_or_instructor_can_access_user_disclaimer(self): + self.client.logout() # no logged in user encoded_user_id = int_str(chaffify(self.user.id)) resp = self.client.get( @@ -122,6 +93,7 @@ def test_only_staff_or_instructor_can_access_user_disclaimer(self): def test_only_staff_or_instructor_can_access_update_user_disclaimer(self): # no logged in user + self.client.logout() encoded_user_id = int_str(chaffify(self.user.id)) url = reverse( 'studioadmin:update_user_disclaimer', args=[encoded_user_id] @@ -148,6 +120,7 @@ def test_only_staff_or_instructor_can_access_update_user_disclaimer(self): def test_only_staff_can_access_delete_user_disclaimer(self): # no logged in user + self.client.logout() encoded_user_id = int_str(chaffify(self.user.id)) url = reverse( 'studioadmin:delete_user_disclaimer', args=[encoded_user_id] @@ -203,10 +176,7 @@ def test_user_password_required_to_update_disclaimer(self): update_url = reverse( 'studioadmin:update_user_disclaimer', args=[encoded_user_id] ) - resp = self._post_response( - update_url, DisclaimerUpdateView, self.staff_user, encoded_user_id, - self.post_data - ) + resp = self.client.post(update_url, self.post_data) self.disclaimer.refresh_from_db() self.assertEqual(self.disclaimer.address, '1 test st') @@ -231,10 +201,7 @@ def test_update_dislaimer_sets_date_updated(self): update_url = reverse( 'studioadmin:update_user_disclaimer', args=[encoded_user_id] ) - resp = self._post_response( - update_url, DisclaimerUpdateView, self.staff_user, encoded_user_id, - self.post_data - ) + resp = self.client.post(update_url, self.post_data) self.disclaimer.refresh_from_db() self.assertIsNotNone(self.disclaimer.date_updated) @@ -244,10 +211,7 @@ def test_update_dislaimer(self): update_url = reverse( 'studioadmin:update_user_disclaimer', args=[encoded_user_id] ) - resp = self._post_response( - update_url, DisclaimerUpdateView, self.staff_user, encoded_user_id, - self.post_data - ) + resp = self.client.post(update_url, self.post_data) self.disclaimer.refresh_from_db() self.assertEqual(self.disclaimer.home_phone, '123445') @@ -256,9 +220,7 @@ def test_get_delete_disclaimer_view(self): delete_url = reverse( 'studioadmin:delete_user_disclaimer', args=[encoded_user_id] ) - resp = self._get_response( - delete_url, DisclaimerDeleteView, self.staff_user, encoded_user_id, - ) + resp = self.client.get(delete_url) self.assertEqual(resp.context_data['user'], self.user) def test_delete_disclaimer(self): @@ -267,10 +229,7 @@ def test_delete_disclaimer(self): delete_url = reverse( 'studioadmin:delete_user_disclaimer', args=[encoded_user_id] ) - resp = self._post_response( - delete_url, DisclaimerDeleteView, self.staff_user, encoded_user_id, - self.post_data - ) + resp = self.client.post(delete_url, self.post_data) self.assertEqual(OnlineDisclaimer.objects.count(), 0) def test_no_changes_made(self): diff --git a/studioadmin/tests/test_views/test_email_users_views.py b/studioadmin/tests/test_views/test_email_users_views.py index 716669b0..100bbe29 100644 --- a/studioadmin/tests/test_views/test_email_users_views.py +++ b/studioadmin/tests/test_views/test_email_users_views.py @@ -5,14 +5,10 @@ from django.core import mail from django.test import TestCase from django.contrib.auth.models import Group, User -from django.contrib.messages.storage.fallback import FallbackStorage from activitylog.models import ActivityLog from booking.models import Booking from common.tests.helpers import _create_session -from studioadmin.views import ( - email_users_view, -) from studioadmin.views.helpers import url_with_querystring from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -22,7 +18,7 @@ class ChooseUsersToEmailTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): - super(ChooseUsersToEmailTests, cls).setUpTestData() + super().setUpTestData() cls.url = reverse('studioadmin:choose_email_users') def formset_data(self, extra_data={}): @@ -452,46 +448,44 @@ def test_get_users_to_email(self): class EmailUsersTests(TestPermissionMixin, TestCase): + def setUp(self): + self.client.force_login(self.staff_user) + def _get_response( - self, user, users_to_email, event_ids=[], lesson_ids=[] + self, users_to_email, event_ids=[], lesson_ids=[] ): url = url_with_querystring( reverse('studioadmin:email_users_view'), events=event_ids, lessons=lesson_ids ) session = _create_session() - request = self.factory.get(url) - request.session = session - request.session['users_to_email'] = users_to_email - request.session['events'] = event_ids - request.session['lessons'] = lesson_ids - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return email_users_view(request) + session = self.client.session + session['users_to_email'] = users_to_email + session['events'] = event_ids + session['lessons'] = lesson_ids + session.save() + return self.client.get(url) def _post_response( - self, user, users_to_email, form_data, event_ids=[], lesson_ids=[] + self, users_to_email, form_data, event_ids=[], lesson_ids=[] ): url = url_with_querystring( reverse('studioadmin:email_users_view'), events=event_ids, lessons=lesson_ids ) session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.session['users_to_email'] = users_to_email - request.session['events'] = event_ids - request.session['lessons'] = lesson_ids - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return email_users_view(request) + session = self.client.session + session['users_to_email'] = users_to_email + session['events'] = event_ids + session['lessons'] = lesson_ids + session.save() + return self.client.post(url, form_data) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse('studioadmin:email_users_view') resp = self.client.get(url) redirected_url = reverse('account_login') + "?next={}".format(url) @@ -502,7 +496,9 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, [self.user.id]) + self.client.logout() + self.client.force_login(self.user) + resp = self._get_response([self.user.id]) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -511,7 +507,10 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, [self.user.id]) + self.client.logout() + self.client.force_login(self.instructor_user) + url = reverse('studioadmin:email_users_view') + resp = self.client.get(url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -519,14 +518,14 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, [self.user.id]) + resp = self._get_response([self.user.id]) self.assertEqual(resp.status_code, 200) def test_users_and_events_in_context(self): event = baker.make_recipe('booking.future_EV', name='Test Event') lesson = baker.make_recipe('booking.future_PC', name='Test Class') resp = self._get_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[event.id], lesson_ids=[lesson.id] ) self.assertEqual([ev for ev in resp.context_data['events']], [event]) @@ -541,7 +540,7 @@ def test_subject_is_autopoulated(self): event = baker.make_recipe('booking.future_EV', name='Workshop') lesson = baker.make_recipe('booking.future_PC', name='Class') resp = self._get_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[event.id], lesson_ids=[lesson.id] ) form = resp.context_data['form'] @@ -557,7 +556,7 @@ def test_emails_sent(self): event = baker.make_recipe('booking.future_EV') user = baker.make_recipe('booking.user', email='other@test.com') self._post_response( - self.staff_user, [self.user.id, user.id], + [self.user.id, user.id], event_ids=[event.id], lesson_ids=[], form_data={ 'subject': 'Test email', @@ -569,7 +568,7 @@ def test_emails_sent(self): self.assertIn('Test message', email.body) self.assertEqual(email.to, []) self.assertEqual(email.reply_to, ['test@test.com']) - self.assertEqual(sorted(email.bcc), [self.user.email, user.email]) + self.assertEqual(set(email.bcc), {self.user.email, user.email}) self.assertEqual( email.subject, 'Test email' ) @@ -579,7 +578,7 @@ def test_email_errors(self, mock_send): mock_send.side_effect = Exception('Error sending email') event = baker.make_recipe('booking.future_EV') self._post_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[event.id], lesson_ids=[], form_data={ 'subject': 'Test email', @@ -599,7 +598,7 @@ def test_email_errors(self, mock_send): def test_cc_email_sent(self): self._post_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[], lesson_ids=[], form_data={ 'subject': 'Test email', @@ -612,7 +611,7 @@ def test_cc_email_sent(self): def test_reply_to_set_to_from_address(self): self._post_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[], lesson_ids=[], form_data={ 'subject': 'Test email', @@ -625,7 +624,7 @@ def test_reply_to_set_to_from_address(self): def test_with_form_errors(self): resp = self._post_response( - self.staff_user, [self.user.id], + [self.user.id], event_ids=[], lesson_ids=[], form_data={ 'subject': 'Test email', @@ -698,7 +697,7 @@ def test_email_mailing_list_for_more_than_100_users(self): self.assertEqual(len(mail.outbox[1].bcc), 51) self._post_response( - self.staff_user, [user.id for user in User.objects.all()], + [user.id for user in User.objects.all()], event_ids=[], lesson_ids=[], form_data=form_data ) @@ -738,7 +737,7 @@ def test_unsubscribe_link_in_mailing_list_emails_only(self): # bulk email self._post_response( - self.staff_user, [self.user.id], event_ids=[], lesson_ids=[], + [self.user.id], event_ids=[], lesson_ids=[], form_data=form_data ) self.assertEqual(len(mail.outbox), 2) # mailing list email is first diff --git a/studioadmin/tests/test_views/test_event_views.py b/studioadmin/tests/test_views/test_event_views.py index a5e273bc..ed3bdea3 100644 --- a/studioadmin/tests/test_views/test_event_views.py +++ b/studioadmin/tests/test_views/test_event_views.py @@ -14,18 +14,11 @@ from django.core import mail from django.contrib.sites.models import Site from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from django.utils import timezone from booking.models import Block, BlockType, Event, Booking, FilterCategory from common.tests.helpers import ( - _add_user_email_addresses, _create_session, format_content -) -from studioadmin.views import ( - cancel_event_view, - event_admin_list, - EventAdminCreateView, - EventAdminUpdateView, + _add_user_email_addresses, format_content, create_configured_user ) from studioadmin.tests.test_views.helpers import TestPermissionMixin from stripe_payments.tests.mock_connector import MockConnector @@ -36,28 +29,10 @@ class EventAdminListViewTests(TestPermissionMixin, TestCase): def setUp(self): super(EventAdminListViewTests, self).setUp() self.event = baker.make_recipe('booking.future_EV', cost=7) - - def _get_response(self, user, ev_type, url=None): - if not url: - url = reverse('studioadmin:events') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return event_admin_list(request, ev_type=ev_type) - - def _post_response(self, user, ev_type, form_data, url=None): - if not url: - url = reverse('studioadmin:events') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return event_admin_list(request, ev_type=ev_type) + self.url = reverse('studioadmin:events') + self.lesson_url = reverse('studioadmin:lessons') + self.room_hire_url = reverse('studioadmin:room_hires') + self.client.force_login(self.staff_user) def formset_data(self, extra_data=None): extra_data = extra_data or {} @@ -80,6 +55,7 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse('studioadmin:events') resp = self.client.get(url) redirected_url = reverse('account_login') + "?next={}".format(url) @@ -90,7 +66,9 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, ev_type='events') + self.client.logout() + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -99,7 +77,9 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, ev_type='events') + self.client.logout() + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -107,13 +87,13 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, ev_type='events') + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_events_url_shows_only_events(self): events = baker.make_recipe('booking.future_EV', _quantity=5) events.append(self.event) - resp = self._get_response(self.staff_user, ev_type='events') + resp = self.client.get(self.url) eventsformset = resp.context_data['eventformset'] @@ -126,7 +106,7 @@ def test_events_url_shows_only_events(self): def test_classes_url_shows_excludes_events(self): classes = baker.make_recipe('booking.future_PC', _quantity=5) url = reverse('studioadmin:lessons') - resp = self._get_response(self.staff_user, ev_type='lessons', url=url) + resp = self.client.get(self.lesson_url) eventsformset = resp.context_data['eventformset'] self.assertEqual( @@ -139,7 +119,7 @@ def test_room_hire_and_classes(self): classes = baker.make_recipe('booking.future_PC', _quantity=5) room_hires = baker.make_recipe('booking.future_RH', _quantity=5) url = reverse('studioadmin:lessons') - resp = self._get_response(self.staff_user, ev_type='lessons', url=url) + resp = self.client.get(self.lesson_url) eventsformset = resp.context_data['eventformset'] self.assertEqual( @@ -150,7 +130,7 @@ def test_room_hire_and_classes(self): self.assertEqual(eventsformset.queryset.count(), 5) self.assertIn('Scheduled Classes', resp.rendered_content) - resp = self._get_response(self.staff_user, ev_type='room_hires', url=url) + resp = resp = self.client.get(self.room_hire_url) eventsformset = resp.context_data['eventformset'] self.assertEqual( @@ -162,9 +142,7 @@ def test_room_hire_and_classes(self): def test_past_filter(self): past_evs = baker.make_recipe('booking.past_event', _quantity=5) - resp = self._post_response( - self.staff_user, 'events', {'past': 'Show past'} - ) + resp = self.client.post(self.url, {'past': 'Show past'}) eventsformset = resp.context_data['eventformset'] self.assertEqual( @@ -179,9 +157,7 @@ def test_past_filter(self): def test_classes_past_filter(self): past_classes = baker.make_recipe('booking.past_class', _quantity=5) - resp = self._post_response( - self.staff_user, 'lessons', {'past': 'Show past'} - ) + resp = self.client.post(self.lesson_url, {'past': 'Show past'}) eventsformset = resp.context_data['eventformset'] self.assertEqual( @@ -197,9 +173,7 @@ def test_classes_past_filter(self): def test_upcoming_filter(self): past_evs = baker.make_recipe('booking.past_event', _quantity=5) - resp = self._post_response( - self.staff_user, 'events', {'upcoming': 'Show upcoming'} - ) + resp = resp = self.client.post(self.url, {'upcoming': 'Show upcoming'}) eventsformset = resp.context_data['eventformset'] self.assertEqual( sorted([ev.id for ev in eventsformset.queryset]), @@ -214,10 +188,6 @@ def test_upcoming_filter(self): def test_pagination(self): baker.make_recipe('booking.future_PC', _quantity=35) url = reverse('studioadmin:lessons') - self.client.login( - username=self.staff_user.username, password='test' - ) - self.assertEqual( Event.objects.filter( event_type__event_type='CL').count(), 35 @@ -247,9 +217,6 @@ def test_pagination(self): def test_past_pagination(self): baker.make_recipe('booking.past_class', _quantity=35) url = reverse('studioadmin:lessons') - self.client.login( - username=self.staff_user.username, password='test' - ) self.assertEqual(Event.objects.count(), 36) # get only shows future by default @@ -276,7 +243,6 @@ def test_cancel_button_shown_for_events_with_bookings(self): baker.make_recipe('booking.booking', event=event) assert event.bookings.all().count() == 1 assert self.event.bookings.all().count() == 0 - self.client.login(username=self.staff_user.username, password="test") resp = self.client.get(reverse("studioadmin:events")) assert 'id="DELETE_0"' in resp.rendered_content assert 'id="DELETE_1"' not in resp.rendered_content @@ -287,7 +253,7 @@ def test_can_delete(self): formset_data = self.formset_data({ 'form-0-DELETE': 'on' }) - self._post_response(self.staff_user, 'events', formset_data) + self.client.post(self.url, formset_data) self.assertEqual(Event.objects.all().count(), 0) def test_can_update_existing_event(self): @@ -295,21 +261,16 @@ def test_can_update_existing_event(self): formset_data = self.formset_data({ 'form-0-booking_open': 'false' }) - self._post_response(self.staff_user, 'events', formset_data) + self.client.post(self.url, formset_data) self.event.refresh_from_db() self.assertFalse(self.event.booking_open) def test_submitting_valid_form_redirects_back_to_correct_url(self): - resp = self._post_response( - self.staff_user, 'events', self.formset_data() - ) + resp = self.client.post(self.url, self.formset_data()) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:events')) - resp = self._post_response( - self.staff_user, 'lessons', self.formset_data(), - url=reverse('studioadmin:lessons') - ) + resp = self.client.post(self.lesson_url, self.formset_data()) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:lessons')) @@ -322,36 +283,10 @@ def setUp(self): 'booking.future_EV', date=timezone.now().replace(second=0, microsecond=0) + timedelta(2) ) - - def _get_response(self, user, event_slug, ev_type, url=None): - if url is None: - url = reverse( - 'studioadmin:edit_event', kwargs={'slug': event_slug} - ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = EventAdminUpdateView.as_view() - return view(request, slug=event_slug, ev_type=ev_type) - - def _post_response(self, user, event_slug, ev_type, form_data={}, url=None): - if url is None: - url = reverse( - 'studioadmin:edit_event', kwargs={'slug': event_slug} + self.url = reverse( + 'studioadmin:edit_event', kwargs={'slug': self.event.slug} ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = EventAdminUpdateView.as_view() - return view(request, slug=event_slug, ev_type=ev_type) + self.client.force_login(self.staff_user) def form_data(self, event, extra_data={}): data = { @@ -378,6 +313,7 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse( 'studioadmin:edit_event', kwargs={'slug': self.event.slug} ) @@ -390,7 +326,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.event.slug, 'event') + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -399,7 +336,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.event.slug, 'event') + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -407,11 +345,11 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.event.slug, 'event') + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_edit_event_refers_to_events_on_page_and_menu(self): - resp = self._get_response(self.staff_user, self.event.slug, 'event') + resp = self.client.get(self.url) self.assertEqual(resp.context_data['sidenav_selection'], 'events') self.assertEqual(resp.context_data['type'], 'event') resp.render() @@ -421,10 +359,7 @@ def test_edit_event_refers_to_events_on_page_and_menu(self): def test_edit_class_refers_to_classes_on_page_and_menu(self): event = baker.make_recipe('booking.future_PC') - resp = self._get_response( - self.staff_user, event.slug, 'lesson', - url=reverse('studioadmin:edit_lesson', kwargs={'slug': event.slug}) - ) + resp = self.client.get(reverse('studioadmin:edit_lesson', kwargs={'slug': event.slug})) self.assertEqual(resp.context_data['sidenav_selection'], 'lessons') self.assertEqual(resp.context_data['type'], 'class') resp.render() @@ -434,10 +369,7 @@ def test_edit_class_refers_to_classes_on_page_and_menu(self): def test_edit_class_refers_to_room_hires_on_page_and_menu(self): event = baker.make_recipe('booking.future_RH') - resp = self._get_response( - self.staff_user, event.slug, 'room_hire', - url=reverse('studioadmin:edit_room_hire', kwargs={'slug': event.slug}) - ) + resp = self.client.get(reverse('studioadmin:edit_room_hire', kwargs={'slug': event.slug})) self.assertEqual(resp.context_data['sidenav_selection'], 'room_hires') self.assertEqual(resp.context_data['type'], 'room hire') resp.render() @@ -447,19 +379,15 @@ def test_edit_class_refers_to_room_hires_on_page_and_menu(self): def test_submitting_valid_event_form_redirects_back_to_events_list(self): form_data = self.form_data(event=self.event) - resp = self._post_response( - self.staff_user, self.event.slug, 'event', form_data - ) + resp = self.client.post(self.url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:events')) def test_submitting_valid_class_form_redirects_back_to_classes_list(self): event = baker.make_recipe('booking.future_PC') form_data = self.form_data(event=event) - resp = self._post_response( - self.staff_user, event.slug, 'lesson', form_data, - url=reverse('studioadmin:edit_lesson', kwargs={'slug': event.slug}) - ) + url = reverse('studioadmin:edit_lesson', kwargs={'slug': event.slug}) + resp = self.client.post(url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:lessons')) @@ -467,19 +395,15 @@ def test_submitting_valid_class_form_redirects_back_to_classes_list(self): def test_submitting_valid_room_hire_form_redirects_back_to_room_hires_list(self): event = baker.make_recipe('booking.future_RH') form_data = self.form_data(event=event) - resp = self._post_response( - self.staff_user, event.slug, 'room_hire', form_data, - url=reverse('studioadmin:edit_room_hire', kwargs={'slug': event.slug}) - ) + url = reverse('studioadmin:edit_room_hire', kwargs={'slug': event.slug}) + resp = self.client.post(url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:room_hires')) def test_post_with_events_page(self): form_data = self.form_data(event=self.event) form_data['from_page'] = '2' - resp = self._post_response( - self.staff_user, self.event.slug, 'event', form_data - ) + resp = self.client.post(self.url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:events') + '?page=2') @@ -492,11 +416,6 @@ def test_no_changes(self): 'allowed_group': self.event.allowed_group.id, } ) - self.assertTrue( - self.client.login( - username=self.staff_user.username, password='test' - ) - ) url = reverse( 'studioadmin:edit_event', kwargs={'slug': self.event.slug} ) @@ -508,9 +427,7 @@ def test_can_edit_event_data(self): form_data = self.form_data( event=self.event, extra_data={'booking_open': False} ) - resp = self._post_response( - self.staff_user, self.event.slug, 'event', form_data - ) + self.client.post(self.url, form_data) event = Event.objects.get(id=self.event.id) self.assertFalse(event.booking_open) @@ -520,11 +437,7 @@ def test_edit_with_categories(self): category = baker.make(FilterCategory, category="test xyz") assert not pole_class.categories.exists() data = self.form_data(event=self.event, extra_data={'categories': [category.id]}) - self.client.login(username=self.staff_user.username, password="test") - self.client.post( - reverse('studioadmin:edit_event', kwargs={'slug': pole_class.slug}), - data=data - ) + self.client.post(reverse('studioadmin:edit_event', kwargs={'slug': pole_class.slug}), data) pole_class = Event.objects.get(id=pole_class.id) assert FilterCategory.objects.count() == 1 assert pole_class.categories.first().category == "test xyz" @@ -536,21 +449,14 @@ def test_edit_with_new_category(self): data = self.form_data( event=self.event, extra_data={'new_category': "Test 1a"} ) - self.client.login(username=self.staff_user.username, password="test") - self.client.post( - reverse('studioadmin:edit_event', kwargs={'slug': pole_class.slug}), - data=data - ) + self.client.post(reverse('studioadmin:edit_event', kwargs={'slug': pole_class.slug}), data) pole_class.refresh_from_db() assert FilterCategory.objects.count() == 2 assert pole_class.categories.first().category == "Test 1a" def test_submitting_with_no_changes_does_not_change_event(self): form_data = self.form_data(self.event) - - resp = self._post_response( - self.staff_user, self.event.slug, 'event', form_data - ) + self.client.post(self.url, form_data) event = Event.objects.get(id=self.event.id) self.assertEqual(self.event.id, event.id) self.assertEqual(self.event.name, event.name) @@ -575,10 +481,7 @@ def test_update_paypal_email_to_non_default(self): } ) self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:edit_event', kwargs={'slug': self.event.slug}), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertIn( "You have changed the paypal receiver email. If you haven't used " @@ -599,7 +502,7 @@ def test_update_paypal_email_to_non_default(self): } ) resp = self.client.post( - reverse('studioadmin:edit_event', kwargs={'slug': self.event.slug}), + self.url, form_data, follow=True ) self.assertNotIn( @@ -617,32 +520,8 @@ def setUp(self): self.event_type_OE = baker.make_recipe('booking.event_type_OE') self.event_type_PC = baker.make_recipe('booking.event_type_PC') self.event_type_RH = baker.make_recipe('booking.event_type_RH') - - def _get_response(self, user, ev_type, url=None): - if url is None: - url = reverse('studioadmin:add_event') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = EventAdminCreateView.as_view() - return view(request, ev_type=ev_type) - - def _post_response(self, user, ev_type, form_data, url=None): - if url is None: - url = reverse('studioadmin:add_event') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = EventAdminCreateView.as_view() - return view(request, ev_type=ev_type) + self.url = reverse('studioadmin:add_event') + self.client.force_login(self.staff_user) def form_data(self, extra_data={}): data = { @@ -665,6 +544,7 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse('studioadmin:add_event') resp = self.client.get(url) redirected_url = reverse('account_login') + "?next={}".format(url) @@ -675,7 +555,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, 'event') + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -684,7 +565,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, 'event') + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -692,11 +574,11 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, 'event') + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_add_event_refers_to_events_on_page(self): - resp = self._get_response(self.staff_user, 'event') + resp = self.client.get(self.url) self.assertEqual(resp.context_data['sidenav_selection'], 'add_event') self.assertEqual(resp.context_data['type'], 'event') resp.render() @@ -705,9 +587,7 @@ def test_add_event_refers_to_events_on_page(self): ) def test_add_class_refers_to_classes_on_page(self): - resp = self._get_response( - self.staff_user, 'lesson', url=reverse('studioadmin:add_lesson') - ) + resp = self.client.get(reverse('studioadmin:add_lesson')) self.assertEqual(resp.context_data['sidenav_selection'], 'add_lesson') self.assertEqual(resp.context_data['type'], 'class') resp.render() @@ -716,9 +596,7 @@ def test_add_class_refers_to_classes_on_page(self): ) def test_add_room_hire_refers_to_classes_on_page(self): - resp = self._get_response( - self.staff_user, 'room_hire', url=reverse('studioadmin:add_room_hire') - ) + resp = self.client.get(reverse('studioadmin:add_room_hire')) self.assertEqual(resp.context_data['sidenav_selection'], 'add_room_hire') self.assertEqual(resp.context_data['type'], 'room hire') resp.render() @@ -728,7 +606,7 @@ def test_add_room_hire_refers_to_classes_on_page(self): def test_submitting_valid_event_form_redirects_back_to_events_list(self): form_data = self.form_data() - resp = self._post_response(self.staff_user, 'event', form_data) + resp = self.client.post(self.url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:events')) @@ -736,10 +614,7 @@ def test_submitting_valid_class_form_redirects_back_to_classes_list(self): form_data = self.form_data( extra_data={'event_type': self.event_type_PC.id} ) - resp = self._post_response( - self.staff_user, 'lesson', form_data, - url=reverse('studioadmin:add_lesson') - ) + resp = self.client.post(reverse('studioadmin:add_lesson'), form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:lessons')) @@ -747,17 +622,14 @@ def test_submitting_valid_room_hire_form_redirects_back_to_room_hire_list(self): form_data = self.form_data( extra_data={'event_type': self.event_type_RH.id} ) - resp = self._post_response( - self.staff_user, 'room_hire', form_data, - url=reverse('studioadmin:add_room_hire') - ) + resp = self.client.post(reverse('studioadmin:add_room_hire'), form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:room_hires')) def test_can_add_event(self): self.assertEqual(Event.objects.count(), 0) form_data = self.form_data() - resp = self._post_response(self.staff_user, 'event', form_data) + resp = self.client.post(self.url, form_data) self.assertEqual(Event.objects.count(), 1) event = Event.objects.first() self.assertEqual(event.name, 'test_event') @@ -765,7 +637,7 @@ def test_can_add_event(self): def test_submitting_form_with_errors_formats_field_names(self): self.assertEqual(Event.objects.count(), 0) form_data = self.form_data({'contact_email': 'test.com'}) - resp = self._post_response(self.staff_user, 'event', form_data) + resp = self.client.post(self.url, form_data) self.assertEqual(Event.objects.count(), 0) self.assertIn( 'Enter a valid email address.', resp.rendered_content @@ -778,12 +650,7 @@ def test_create_event_with_non_default_paypal_email(self): 'paypal_email_check': 'testpaypal@test.com' } ) - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:add_event'), - form_data, follow=True - ) - + resp = self.client.post(self.url, form_data, follow=True) self.assertIn( "You have changed the paypal receiver email from the default value. " "If you haven't used " @@ -797,10 +664,7 @@ def test_create_event_with_non_default_paypal_email(self): self.assertEqual(event.paypal_email, 'testpaypal@test.com') form_data = self.form_data() - resp = self.client.post( - reverse('studioadmin:add_event'), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertNotIn( "You have changed the paypal receiver email from the default value.", resp.rendered_content @@ -809,7 +673,6 @@ def test_create_event_with_non_default_paypal_email(self): self.assertEqual(event1.paypal_email, settings.DEFAULT_PAYPAL_EMAIL) -from common.tests.helpers import create_configured_user class CancelEventTests(TestCase): @classmethod diff --git a/studioadmin/tests/test_views/test_mailing_list_views.py b/studioadmin/tests/test_views/test_mailing_list_views.py index 7da032e3..5a280a2c 100644 --- a/studioadmin/tests/test_views/test_mailing_list_views.py +++ b/studioadmin/tests/test_views/test_mailing_list_views.py @@ -1,6 +1,6 @@ -from model_bakery import baker +from unittest.mock import Mock, patch -import pytest +from model_bakery import baker from django.contrib.auth.models import Group, User from django.urls import reverse @@ -18,6 +18,15 @@ def setUpTestData(cls): super(MailingListViewTests, cls).setUpTestData() cls.subscribed = baker.make(Group, name='subscribed') + def setUp(self): + mockresponse = Mock() + mockresponse.status_code = 200 + self.patcher = patch('requests.request', return_value = mockresponse) + self.mock_request = self.patcher.start() + + def tearDown(self): + self.patcher.stop() + def test_staff_login_required(self): url = reverse('studioadmin:mailing_list') resp = self.client.get(url) diff --git a/studioadmin/tests/test_views/test_misc_views.py b/studioadmin/tests/test_views/test_misc_views.py index 37b78af5..b7dc4455 100644 --- a/studioadmin/tests/test_views/test_misc_views.py +++ b/studioadmin/tests/test_views/test_misc_views.py @@ -3,18 +3,11 @@ import pytest from django.urls import reverse -from django.contrib.auth.models import User from django.core import mail from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from django.contrib.sites.models import Site from booking.models import Booking, Block, TicketBooking, Ticket -from common.tests.helpers import _create_session -from studioadmin.views import ( - ConfirmPaymentView, - ConfirmRefundView, -) from stripe_payments.models import Invoice from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -27,38 +20,16 @@ def setUp(self): 'booking.booking', user=self.user, paid=False, payment_confirmed=False) - - def _get_response(self, user, booking): - url = reverse('studioadmin:confirm-payment', args=[booking.id]) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = ConfirmPaymentView.as_view() - return view(request, pk=booking.id) - - def _post_response(self, user, booking, form_data): - url = reverse('studioadmin:confirm-payment', args=[booking.id]) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = ConfirmPaymentView.as_view() - return view(request, pk=booking.id) + self.url = reverse('studioadmin:confirm-payment', args=[self.booking.id]) + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:confirm-payment', args=[self.booking.id]) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + redirected_url = reverse('account_login') + "?next={}".format(self.url) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -66,7 +37,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.booking) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -75,7 +47,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.booking) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -83,7 +56,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.booking) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_with_unpaid_booking(self): @@ -97,7 +70,7 @@ def test_with_unpaid_booking(self): 'paid': 'true', 'payment_confirmed': 'true' } - resp = self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertTrue(booking.paid) self.assertTrue(booking.payment_confirmed) @@ -116,7 +89,7 @@ def test_confirm_payment(self): form_data = { 'payment_confirmed': 'true' } - resp = self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertTrue(booking.paid) self.assertTrue(booking.payment_confirmed) @@ -140,7 +113,7 @@ def test_changing_paid_to_unpaid(self): 'paid': 'false', 'payment_confirmed': 'true' } - resp = self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertFalse(booking.paid) self.assertFalse(booking.payment_confirmed) @@ -162,7 +135,7 @@ def test_changing_payment_confirmed_only(self): 'paid': 'false', 'payment_confirmed': 'true' } - self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertTrue(booking.paid) self.assertTrue(booking.payment_confirmed) @@ -172,7 +145,7 @@ def test_payment_not_confirmed(self): 'paid': 'true', 'payment_confirmed': 'false' } - self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertTrue(booking.paid) self.assertFalse(booking.payment_confirmed) @@ -186,7 +159,7 @@ def test_no_changes(self): 'paid': 'false', 'payment_confirmed': 'false' } - resp = self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:users')) @@ -202,7 +175,7 @@ def test_confirm_payment_with_email_errors(self, mock_send_mail): form_data = { 'payment_confirmed': 'true' } - self._post_response(self.staff_user, self.booking, form_data) + resp = self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.booking.id) self.assertTrue(booking.paid) self.assertTrue(booking.payment_confirmed) @@ -218,35 +191,14 @@ def setUp(self): 'booking.booking', user=self.user, paid=True, payment_confirmed=True) - - def _get_response(self, user, booking): - url = reverse('studioadmin:confirm-refund', args=[booking.id]) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = ConfirmRefundView.as_view() - return view(request, pk=booking.id) - - def _post_response(self, user, booking, form_data): - url = reverse('studioadmin:confirm-refund', args=[booking.id]) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = ConfirmRefundView.as_view() - return view(request, pk=booking.id) + self.url = reverse('studioadmin:confirm-refund', args=[self.booking.id]) + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ + self.client.logout() url = reverse('studioadmin:confirm-refund', args=[self.booking.id]) resp = self.client.get(url) redirected_url = reverse('account_login') + "?next={}".format(url) @@ -257,7 +209,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.booking) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -266,7 +219,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.booking) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -274,7 +228,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.booking) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_confirm_refund_for_paid_booking(self): @@ -283,9 +237,7 @@ def test_confirm_refund_for_paid_booking(self): """ self.assertTrue(self.booking.paid) self.assertTrue(self.booking.payment_confirmed) - resp = self._post_response( - self.staff_user, self.booking, form_data={'confirmed': ['Confirm']} - ) + resp = self.client.post(self.url, {'confirmed': ['Confirm']}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:users')) booking = Booking.objects.get(id=self.booking.id) @@ -302,9 +254,7 @@ def test_confirm_refund_for_free_booking(self): self.assertTrue(self.booking.paid) self.assertTrue(self.booking.payment_confirmed) - resp = self._post_response( - self.staff_user, self.booking, form_data={'confirmed': ['Confirm']} - ) + resp = self.client.post(self.url, {'confirmed': ['Confirm']}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:users')) booking = Booking.objects.get(id=self.booking.id) @@ -325,9 +275,7 @@ def test_cancel_confirm_form(self): """ self.assertTrue(self.booking.paid) self.assertTrue(self.booking.payment_confirmed) - resp = self._post_response( - self.staff_user, self.booking, form_data={'cancelled': ['Cancel']} - ) + resp = self.client.post(self.url, {'cancelled': ['Cancel']}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:users')) booking = Booking.objects.get(id=self.booking.id) @@ -372,7 +320,7 @@ def test_post_created_paypal_form(self): self.assertEqual(paypal_data['amount'], 0.01) self.assertEqual( paypal_data['custom'], - 'obj=paypal_test ids=0 inv={} pp=testpp@test.com usr=test@test.com'.format( + 'obj=paypal_test ids=0 inv={} pp=testpp@test.com usr=staff@example.com'.format( paypal_data['invoice'] ) ) diff --git a/studioadmin/tests/test_views/test_notification_views.py b/studioadmin/tests/test_views/test_notification_views.py index 5d3112cb..59ba8c38 100644 --- a/studioadmin/tests/test_views/test_notification_views.py +++ b/studioadmin/tests/test_views/test_notification_views.py @@ -1,4 +1,4 @@ -from django.contrib.auth.models import Group, User, Permission +from django.contrib.auth.models import Group, User from django.urls import reverse import pytest diff --git a/studioadmin/tests/test_views/test_register_views.py b/studioadmin/tests/test_views/test_register_views.py index 1ef318c6..2f532733 100644 --- a/studioadmin/tests/test_views/test_register_views.py +++ b/studioadmin/tests/test_views/test_register_views.py @@ -7,38 +7,36 @@ from model_bakery import baker from django.contrib.auth.models import User -from django.contrib.messages.storage.fallback import FallbackStorage from django.core import mail from django.urls import reverse from django.utils import timezone -from django.test import TestCase +from django.test import TestCase, RequestFactory from booking.models import Event, Block, BlockType, WaitingListUser -from common.tests.helpers import _create_session, format_content -from studioadmin.views.register import EventRegisterListView, process_event_booking_updates, register_print_day +from common.tests.helpers import format_content +from studioadmin.views.register import process_event_booking_updates from studioadmin.forms.register_forms import AddRegisterBookingForm from studioadmin.tests.test_views.helpers import TestPermissionMixin class EventRegisterListViewTests(TestPermissionMixin, TestCase): - def _get_response(self, user, ev_type, url=None): - if not url: - url = reverse('studioadmin:event_register_list') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - view = EventRegisterListView.as_view() - return view(request, ev_type=ev_type) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:event_register_list') + cls.lessons_url = reverse('studioadmin:class_register_list') + + def setUp(self): + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:event_register_list') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -46,11 +44,12 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, 'events') + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.user, 'lessons') + resp = self.client.get(self.lessons_url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -58,7 +57,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_can_access_class_registers_if_instructor(self): @@ -66,14 +65,15 @@ def test_can_access_class_registers_if_instructor(self): test that the page can be accessed by a non staff user if in the instructors group for both classes and events """ - resp = self._get_response(self.instructor_user, 'events') + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) - resp = self._get_response(self.instructor_user, 'lessons') + resp = self.client.get(self.lessons_url) self.assertEqual(resp.status_code, 200) def test_event_context(self): - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.context_data['type'], 'events') self.assertEqual( @@ -82,8 +82,7 @@ def test_event_context(self): self.assertIn("Events", resp.rendered_content) def test_lesson_context(self): - url = reverse('studioadmin:class_register_list') - resp = self._get_response(self.staff_user, 'lessons', url=url) + resp = self.client.get(self.lessons_url) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.context_data['type'], 'lessons') self.assertEqual( @@ -94,27 +93,26 @@ def test_lesson_context(self): def test_event_register_list_shows_future_events_only(self): baker.make_recipe('booking.future_EV', _quantity=4) baker.make_recipe('booking.past_event', _quantity=4) - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertEqual(len(resp.context_data['events']), 4) def test_event_register_list_shows_todays_events(self): baker.make_recipe('booking.future_EV', _quantity=4) baker.make_recipe('booking.past_event', _quantity=4) past_today = baker.make_recipe('booking.past_event', date=timezone.now().replace(hour=0, minute=1)) - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertEqual(len(resp.context_data['events']), 5) def test_event_register_list_shows_events_only(self): baker.make_recipe('booking.future_EV', _quantity=4) baker.make_recipe('booking.future_PC', _quantity=5) - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertEqual(len(resp.context_data['events']), 4) def test_class_register_list_excludes_events(self): baker.make_recipe('booking.future_EV', _quantity=4) baker.make_recipe('booking.future_PC', _quantity=5) - url = reverse('studioadmin:class_register_list') - resp = self._get_response(self.staff_user, 'lessons', url=url) + resp = self.client.get(self.lessons_url) self.assertEqual(len(resp.context_data['events']), 5) def test_class_register_list_shows_room_hire_with_classes(self): @@ -122,8 +120,7 @@ def test_class_register_list_shows_room_hire_with_classes(self): baker.make_recipe('booking.future_PC', _quantity=5) baker.make_recipe('booking.future_RH', _quantity=5) - url = reverse('studioadmin:class_register_list') - resp = self._get_response(self.staff_user, 'lessons', url=url) + resp = self.client.get(self.lessons_url) self.assertEqual(len(resp.context_data['events']), 10) def test_event_register_list_shows_correct_booking_count(self): @@ -131,7 +128,7 @@ def test_event_register_list_shows_correct_booking_count(self): baker.make_recipe('booking.booking', event=event, _quantity=2) baker.make_recipe('booking.booking', event=event, status='CANCELLED') baker.make_recipe('booking.booking', event=event, no_show=True) - resp = self._get_response(self.staff_user, 'events') + resp = self.client.get(self.url) self.assertIn( '{} {} 2'.format( event.date.astimezone( @@ -385,7 +382,8 @@ def test_already_open_booking(self, mock_messages): baker.make_recipe('booking.booking', user=self.user, event=self.pc, status='OPEN') # try to process the form - request = self.factory.get(self.pc_url) + factory = RequestFactory() + request = factory.get(self.pc_url) process_event_booking_updates(form, self.pc, request) mock_messages.assert_called_once_with(request, 'Open booking for this user already exists') @@ -826,33 +824,21 @@ def test_ajax_toggle_attended_no_show_booking_full_event(self): class RegisterByDateTests(TestPermissionMixin, TestCase): - def _get_response(self, user): - url = reverse('studioadmin:register-day') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return register_print_day(request) - - def _post_response(self, user,form_data): - url = reverse('studioadmin:register-day') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return register_print_day(request) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:register-day') + + def setUp(self): + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:register-day') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -860,7 +846,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -868,7 +855,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) @patch('studioadmin.forms.register_forms.date') @@ -876,6 +863,7 @@ def test_can_access_as_staff_user(self): def test_events_and_classes_in_form_for_instructors( self, mock_tz, mock_date ): + self.client.force_login(self.instructor_user) mock_tz.now.return_value = datetime( year=2015, month=9, day=7, hour=10, tzinfo=dt_timezone.utc ) @@ -896,7 +884,7 @@ def test_events_and_classes_in_form_for_instructors( ), _quantity=3 ) - resp = self._get_response(self.instructor_user) + resp = self.client.get(self.url) form = resp.context_data['form'] self.assertEqual(len(form.events), 6) @@ -925,14 +913,13 @@ def test_show_events_by_selected_date(self): ), _quantity=3 ) - - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'show': 'show'} - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'show': 'show' + } + resp = self.client.post(self.url, data) self.assertEqual(Event.objects.count(), 6) form = resp.context_data['form'] @@ -945,6 +932,7 @@ def test_show_events_by_selected_date(self): ) def test_show_events_by_selected_date_for_instructor(self): + self.client.force_login(self.instructor_user) events = baker.make_recipe( 'booking.future_EV', date=datetime( @@ -978,13 +966,14 @@ def test_show_events_by_selected_date_for_instructor(self): _quantity=3 ) - resp = self._post_response( - self.instructor_user, { + data = { 'register_date': 'Mon 07 Sep 2015', 'exclude_ext_instructor': True, 'register_format': 'full', - 'show': 'show'} - ) + 'show': 'show' + } + resp = self.client.post(self.url, data) + self.assertEqual(Event.objects.count(), 12) form = resp.context_data['form'] @@ -1007,18 +996,13 @@ def test_no_events_on_selected_date(self): _quantity=3 ) - url = reverse('studioadmin:register-day') - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - url, - { - 'register_date': 'Mon 06 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'show': 'show' - }, - follow=True - ) + data = { + 'register_date': 'Mon 06 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'show': 'show' + } + resp = self.client.post(self.url, data, follow=True) self.assertEqual(Event.objects.count(), 3) content = format_content(resp.rendered_content) @@ -1038,17 +1022,13 @@ def test_no_events_selected_to_print(self): ) url = reverse('studioadmin:register-day') - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - url, - { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print' - }, - follow=True - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print' + } + resp = self.client.post(self.url, data, follow=True) self.assertEqual(Event.objects.count(), 3) content = format_content(resp.rendered_content) @@ -1067,14 +1047,14 @@ def test_print_selected_events(self): _quantity=3 ) - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [events[0].id, events[1].id]} - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [events[0].id, events[1].id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 2) for event in resp.context_data['events']: @@ -1096,15 +1076,14 @@ def test_print_unselected_events(self): _quantity=3 ) - resp = self._post_response( - self.staff_user, { + data = { 'register_date': 'Mon 07 Sep 2015', 'exclude_ext_instructor': True, 'register_format': 'full', 'print': 'print', 'select_events': [event.id for event in events] - } - ) + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 3) for event in resp.context_data['events']: @@ -1144,15 +1123,14 @@ def test_print_open_bookings_for_events(self): _quantity=2 ) - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event1.id, event2.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event1.id, event2.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 2) @@ -1184,15 +1162,14 @@ def test_print_extra_lines(self): ) # event has max_participants; extra lines are max - open bookings - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event1.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event1.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) self.assertEqual(resp.context_data['events'][0]['extra_lines'], 8) @@ -1201,30 +1178,28 @@ def test_print_extra_lines(self): event1.save() # event has no max_participants and <15 bookings; extra lines are # 15 - open bookings - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event1.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event1.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) self.assertEqual(resp.context_data['events'][0]['extra_lines'], 13) baker.make_recipe('booking.booking', event=event1, _quantity=14) # event has no max_participants and >15 bookings; extra lines = 2 - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event1.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event1.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) self.assertEqual(resp.context_data['events'][0]['extra_lines'], 2) @@ -1239,15 +1214,14 @@ def test_print_format_no_available_blocktype(self): ), ) - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) # check correct headings are present @@ -1257,15 +1231,14 @@ def test_print_format_no_available_blocktype(self): self.assertIn('>Deposit Paid<', resp.rendered_content) self.assertIn('>Fully Paid<', resp.rendered_content) - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'namesonly', - 'print': 'print', - 'select_events': [event.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'namesonly', + 'print': 'print', + 'select_events': [event.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) # check correct headings are present @@ -1290,49 +1263,55 @@ def test_print_format_with_available_blocktype(self): event_type=event.event_type ) - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print', - 'select_events': [event.id] - } - ) + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print', + 'select_events': [event.id] + } + resp = self.client.post(self.url, data) self.assertEqual(len(resp.context_data['events']), 1) # check correct headings are present - self.assertIn('>Attended<', resp.rendered_content) - self.assertIn('>Status<', resp.rendered_content) - self.assertIn('>User<', resp.rendered_content) - self.assertIn('>Deposit Paid<', resp.rendered_content) - self.assertIn('>Fully Paid<', resp.rendered_content) - self.assertIn('>Booked with
block<', resp.rendered_content) - self.assertIn('>User\'s block
expiry date<', resp.rendered_content) - self.assertIn('>Block size<', resp.rendered_content) - self.assertIn('>Block bookings
used<', resp.rendered_content) - - resp = self._post_response( - self.staff_user, { - 'register_date': 'Mon 07 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'namesonly', - 'print': 'print', - 'select_events': [event.id] - } - ) + headings = [ + '>Attended<', + '>Status<', + '>Disclaimer<', + '>User<', + '>Deposit Paid<', + '>Fully Paid<', + '>Booked with
block<', + '>User\'s block
expiry date<', + '>Block size<', + '>Block bookings
used<' + ] + for heading in headings: + assert heading in resp.rendered_content + data = { + 'register_date': 'Mon 07 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'namesonly', + 'print': 'print', + 'select_events': [event.id] + } + resp = self.client.post(self.url, data, follow=True) self.assertEqual(len(resp.context_data['events']), 1) # check correct headings are present - self.assertIn('>Attended<', resp.rendered_content) - self.assertIn('>User<', resp.rendered_content) - self.assertNotIn('>Status<', resp.rendered_content) - self.assertNotIn('>Deposit Paid<', resp.rendered_content) - self.assertNotIn('>Fully Paid<', resp.rendered_content) - self.assertNotIn('>Book with
available block<', resp.rendered_content) - self.assertNotIn('>User\'s block
expiry date<', resp.rendered_content) - self.assertNotIn('>Block size<', resp.rendered_content) - self.assertNotIn('>Bookings used<', resp.rendered_content) + for heading in ['>Attended<', '>User<', '>Disclaimer<']: + assert heading in resp.rendered_content + + for heading in [ + '>Status<', + '>Deposit Paid<', + '>Fully Paid<', + '>Booked with
block<', + '>User\'s block
expiry date<', + '>Block size<', + '>Block bookings
used<' + ]: + assert heading not in resp.rendered_content def test_print_with_invalid_date_format(self): baker.make_recipe( @@ -1342,18 +1321,13 @@ def test_print_with_invalid_date_format(self): hour=18, minute=0, tzinfo=dt_timezone.utc ), ) - url = reverse('studioadmin:register-day') - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - url, - { - 'register_date': 'Mon 33 Sep 2015', - 'exclude_ext_instructor': True, - 'register_format': 'full', - 'print': 'print' - }, - follow=True - ) + data = { + 'register_date': 'Mon 33 Sep 2015', + 'exclude_ext_instructor': True, + 'register_format': 'full', + 'print': 'print' + } + resp = self.client.post(self.url, data, follow=True) content = format_content(resp.rendered_content) self.assertIn( diff --git a/studioadmin/tests/test_views/test_setup_views.py b/studioadmin/tests/test_views/test_setup_views.py index ae6ff0ad..efc1ad2c 100644 --- a/studioadmin/tests/test_views/test_setup_views.py +++ b/studioadmin/tests/test_views/test_setup_views.py @@ -1,11 +1,9 @@ -from django.contrib.auth.models import Group, User, Permission from django.urls import reverse import pytest from model_bakery import baker -from notices.models import Notice from booking.models import AllowedGroup pytestmark = pytest.mark.django_db diff --git a/studioadmin/tests/test_views/test_ticketed_events_views.py b/studioadmin/tests/test_views/test_ticketed_events_views.py index 4fcd9a4f..317e19eb 100644 --- a/studioadmin/tests/test_views/test_ticketed_events_views.py +++ b/studioadmin/tests/test_views/test_ticketed_events_views.py @@ -8,28 +8,21 @@ from django.urls import reverse from django.core import mail from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from django.utils import timezone from booking.models import TicketedEvent, TicketBooking, Ticket from common.tests.helpers import ( - _add_user_email_addresses, _create_session, format_content + _add_user_email_addresses, format_content ) -from studioadmin.views import ( - ConfirmTicketBookingRefundView, - TicketedEventAdminCreateView, TicketedEventAdminListView, - TicketedEventAdminUpdateView, TicketedEventBookingsListView, - cancel_ticketed_event_view, print_tickets_list -) from studioadmin.tests.test_views.helpers import TestPermissionMixin class TicketedEventAdminListViewTests(TestPermissionMixin, TestCase): def setUp(self): - super(TicketedEventAdminListViewTests, self).setUp() + super().setUp() self.ticketed_event = baker.make_recipe( 'booking.ticketed_event_max10', date=timezone.now() + timedelta(2) @@ -38,28 +31,8 @@ def setUp(self): 'booking.ticketed_event_max10', date=timezone.now() - timedelta(2) ) - - def _get_response(self, user): - url = reverse('studioadmin:ticketed_events') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminListView.as_view() - return view(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:ticketed_events') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminListView.as_view() - return view(request) + self.url = reverse('studioadmin:ticketed_events') + self.client.force_login(self.staff_user) def formset_data(self, extra_data={}): @@ -75,22 +48,24 @@ def formset_data(self, extra_data={}): return data def test_cannot_access_without_login(self): - url = reverse('studioadmin:ticketed_events') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_get_shows_upcoming_events(self): - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) formset = resp.context_data['ticketed_event_formset'] self.assertEqual( @@ -99,13 +74,13 @@ def test_get_shows_upcoming_events(self): ) def test_side_nav_selection_in_context(self): - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual( resp.context_data['sidenav_selection'], 'ticketed_evs' ) def test_show_ticketed_events_by_past_or_upcoming(self): - resp = self._post_response(self.staff_user, {'past': 'Show past events'}) + resp = self.client.post(self.url, {'past': 'Show past events'}) self.assertEqual(resp.status_code, 200) formset = resp.context_data['ticketed_event_formset'] self.assertEqual( @@ -113,9 +88,7 @@ def test_show_ticketed_events_by_past_or_upcoming(self): [self.past_ticketed_event.id] ) - resp = self._post_response( - self.staff_user, {'upcoming': 'Show upcoming events'} - ) + resp = self.client.post(self.url, {'upcoming': 'Show upcoming events'}) self.assertEqual(resp.status_code, 200) formset = resp.context_data['ticketed_event_formset'] self.assertEqual( @@ -129,7 +102,7 @@ def test_include_cancelled_events(self): date=timezone.now() + timedelta(2), cancelled=True ) - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) formset = resp.context_data['ticketed_event_formset'] self.assertEqual(formset.queryset.count(), 2) @@ -144,7 +117,7 @@ def test_can_delete(self): 'form-0-DELETE': 'on', 'formset_submitted': 'Save changes' }) - resp = self._post_response(self.staff_user, formset_data) + resp = self.client.post(self.url, formset_data) self.assertEqual(TicketedEvent.objects.all().count(), 1) def test_cancel_button_shown_for_events_with_bookings(self): @@ -161,7 +134,7 @@ def test_cancel_button_shown_for_events_with_bookings(self): purchase_confirmed=True ) - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertIn( 'id="DELETE_0"', resp.rendered_content ) @@ -181,7 +154,7 @@ def test_can_edit_event(self): 'form-0-advance_payment_required': False, 'formset_submitted': 'Save changes' }) - self._post_response(self.staff_user, formset_data) + resp = self.client.post(self.url, formset_data) self.ticketed_event.refresh_from_db() self.assertFalse(self.ticketed_event.show_on_site) self.assertFalse(self.ticketed_event.payment_open) @@ -197,9 +170,6 @@ def test_save_with_no_changes(self): 'formset_submitted': 'Save changes' } ) - self.assertTrue(self.client.login( - username=self.staff_user.username, password='test') - ) resp = self.client.post( reverse('studioadmin:ticketed_events'), formset_data, @@ -224,32 +194,13 @@ def setUp(self): 'booking.ticketed_event_max10', date=timezone.now() - timedelta(2) ) - - def _get_response(self, user, ticketed_event): - url = reverse( - 'studioadmin:edit_ticketed_event', kwargs={'slug': ticketed_event.slug} - ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminUpdateView.as_view() - return view(request, slug=ticketed_event.slug) - - def _post_response(self, user, ticketed_event, form_data): - url = reverse( - 'studioadmin:edit_ticketed_event', kwargs={'slug': ticketed_event.slug} + self.url = reverse( + 'studioadmin:edit_ticketed_event', kwargs={'slug': self.ticketed_event.slug} ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminUpdateView.as_view() - return view(request, slug=ticketed_event.slug) + self.past_url = reverse( + 'studioadmin:edit_ticketed_event', kwargs={'slug': self.past_ticketed_event.slug} + ) + self.client.force_login(self.staff_user) def form_data(self, extra_data={}): # make the date uk time before stringifying for form input @@ -271,21 +222,20 @@ def form_data(self, extra_data={}): return data def test_cannot_access_without_login(self): - url = reverse( - 'studioadmin:edit_ticketed_event', - kwargs={'slug': self.ticketed_event.slug} - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user, self.ticketed_event) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user, self.ticketed_event) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_can_edit_event(self): @@ -296,8 +246,9 @@ def test_can_edit_event(self): self.assertEqual( self.ticketed_event.contact_email, settings.DEFAULT_STUDIO_EMAIL ) - resp = self._post_response( - self.staff_user, self.ticketed_event, self.form_data( + resp = self.client.post( + self.url, + self.form_data( { 'ticket_cost': 5, 'location': 'Test location', @@ -317,10 +268,6 @@ def test_can_edit_event(self): def test_submit_form_without_changes(self): self.ticketed_event.payment_time_allowed = 8 self.ticketed_event.save() - url = reverse( - 'studioadmin:edit_ticketed_event', - kwargs={'slug': self.ticketed_event.slug} - ) form_data = self.form_data( { @@ -344,14 +291,14 @@ def test_submit_form_without_changes(self): username=self.staff_user.username, password='test') ) resp = self.client.post( - url, form_data, follow=True + self.url, form_data, follow=True ) self.assertIn( 'No changes made', format_content(resp.rendered_content) ) def test_side_nav_selection_in_context(self): - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) self.assertEqual( resp.context_data['sidenav_selection'], 'ticketed_evs' ) @@ -364,12 +311,8 @@ def test_update_paypal_email_to_non_default(self): 'paypal_email_check': 'testpaypal@test.com' } ) - self.client.login(username=self.staff_user.username, password='test') resp = self.client.post( - reverse( - 'studioadmin:edit_ticketed_event', - kwargs={'slug': self.ticketed_event.slug}), - form_data, follow=True + self.url, form_data, follow=True ) self.assertIn( @@ -391,11 +334,7 @@ def test_update_paypal_email_to_non_default(self): } ) resp = self.client.post( - reverse( - 'studioadmin:edit_ticketed_event', - kwargs={'slug': self.ticketed_event.slug} - ), - form_data, follow=True + self.url, form_data, follow=True ) self.assertNotIn( "You have changed the paypal receiver email.", @@ -409,45 +348,33 @@ def test_update_paypal_email_to_non_default(self): class TicketedEventAdminCreateViewTests(TestPermissionMixin, TestCase): - def _get_response(self, user): - url = reverse('studioadmin:add_ticketed_event') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminCreateView.as_view() - return view(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:add_ticketed_event') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventAdminCreateView.as_view() - return view(request) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:add_ticketed_event') + + def setUp(self): + self.client.force_login(self.staff_user) def test_cannot_access_without_login(self): - url = reverse('studioadmin:add_ticketed_event') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_side_nav_selection_in_context(self): - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual( resp.context_data['sidenav_selection'], 'add_ticketed_ev' ) @@ -463,7 +390,7 @@ def test_can_create_event(self): 'ticket_cost': 5, 'paypal_email': settings.DEFAULT_PAYPAL_EMAIL, } - self._post_response(self.staff_user, data) + resp = self.client.post(self.url, data) self.assertEqual(TicketedEvent.objects.count(), 1) def test_create_ticketed_event_with_non_default_paypal_email(self): @@ -477,11 +404,7 @@ def test_create_ticketed_event_with_non_default_paypal_email(self): 'paypal_email': 'testpaypal@test.com', 'paypal_email_check': 'testpaypal@test.com' } - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:add_ticketed_event'), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertIn( "You have changed the paypal receiver email from the default value. " @@ -501,10 +424,7 @@ def test_create_ticketed_event_with_non_default_paypal_email(self): 'paypal_email_check': '' } ) - resp = self.client.post( - reverse('studioadmin:add_ticketed_event'), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertNotIn( "You have changed the paypal receiver email from the default value.", resp.rendered_content @@ -518,7 +438,7 @@ def test_create_ticketed_event_with_non_default_paypal_email(self): class TicketedEventBookingsListViewTests(TestPermissionMixin, TestCase): def setUp(self): - super(TicketedEventBookingsListViewTests, self).setUp() + super().setUp() self.ticketed_event = baker.make_recipe( 'booking.ticketed_event_max10', date=timezone.now() + timedelta(2) @@ -532,34 +452,11 @@ def setUp(self): ) for tb in [self.ticket_booking, self.ticket_booking1]: baker.make(Ticket, ticket_booking=tb) - - def _get_response(self, user, ticketed_event): - url = reverse( - 'studioadmin:ticketed_event_bookings', - kwargs={'slug': ticketed_event.slug} - ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventBookingsListView.as_view() - return view(request, slug=ticketed_event.slug) - - def _post_response(self, user, ticketed_event, form_data): - url = reverse( + self.client.force_login(self.staff_user) + self.url = reverse( 'studioadmin:ticketed_event_bookings', - kwargs={'slug': ticketed_event.slug} + kwargs={'slug': self.ticketed_event.slug} ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TicketedEventBookingsListView.as_view() - return view(request, slug=ticketed_event.slug) def formset_data(self, extra_data={}): @@ -575,28 +472,27 @@ def formset_data(self, extra_data={}): return data def test_cannot_access_without_login(self): - url = reverse( - 'studioadmin:ticketed_event_bookings', - kwargs={'slug': self.ticketed_event.slug} - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user, self.ticketed_event) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user, self.ticketed_event) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_show_only_ticket_bookings_on_event(self): """ confirmed bookings for other events are not shown """ - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) formset = resp.context_data['ticket_booking_formset'] self.assertEqual( [tb.id for tb in formset.queryset], @@ -611,7 +507,7 @@ def test_does_not_show_unconfirmed_ticket_bookings(self): baker.make(Ticket, ticket_booking=tb) self.assertEqual(self.ticketed_event.ticket_bookings.count(), 2) - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) formset = resp.context_data['ticket_booking_formset'] # tb is not shown as not confirmed @@ -625,7 +521,7 @@ def test_does_not_show_ticket_bookings_with_no_tickets(self): tb = baker.make(TicketBooking, ticketed_event=self.ticketed_event) self.assertEqual(self.ticketed_event.ticket_bookings.count(), 2) - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) formset = resp.context_data['ticket_booking_formset'] # tb is not shown as no tickets attached @@ -642,7 +538,7 @@ def test_exclude_cancelled_bookings(self): ) baker.make(Ticket, ticket_booking=tb) self.assertEqual(self.ticketed_event.ticket_bookings.count(), 2) - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) formset = resp.context_data['ticket_booking_formset'] # tb is not shown as cancelled @@ -659,9 +555,7 @@ def test_show_cancelled_if_ticked(self): ) baker.make(Ticket, ticket_booking=tb) self.assertEqual(self.ticketed_event.ticket_bookings.count(), 2) - resp = self._post_response( - self.staff_user, self.ticketed_event, {'show_cancelled': True} - ) + resp = self.client.post(self.url, {'show_cancelled': True}) formset = resp.context_data['ticket_booking_formset'] # tb is not shown as cancelled @@ -673,15 +567,15 @@ def test_show_cancelled_if_ticked(self): self.assertTrue(resp.context_data['show_cancelled_ctx']) def test_side_nav_selection_in_context(self): - resp = self._get_response(self.staff_user, self.ticketed_event) + resp = self.client.get(self.url) self.assertEqual( resp.context_data['sidenav_selection'], 'ticketed_evs' ) def test_update_booking(self): self.assertFalse(self.ticket_booking.paid) - resp = self._post_response( - self.staff_user, self.ticketed_event, + resp = self.client.post( + self.url, self.formset_data( { @@ -694,11 +588,6 @@ def test_update_booking(self): self.assertTrue(self.ticket_booking.paid) def test_submit_form_without_changes(self): - - url = reverse( - 'studioadmin:ticketed_event_bookings', - kwargs={'slug': self.ticketed_event.slug} - ) data = self.formset_data( { 'ticket_bookings-0-paid': self.ticket_booking.paid, @@ -710,7 +599,7 @@ def test_submit_form_without_changes(self): username=self.staff_user.username, password='test' ) ) - resp = self.client.post(url, data, follow=True) + resp = self.client.post(self.url, data, follow=True) self.assertIn( 'No changes were made', format_content(resp.rendered_content) @@ -718,11 +607,6 @@ def test_submit_form_without_changes(self): def test_submit_form_without_changes_send_confirmation_ticked(self): - - url = reverse( - 'studioadmin:ticketed_event_bookings', - kwargs={'slug': self.ticketed_event.slug} - ) data = self.formset_data( { 'ticket_bookings-0-paid': self.ticket_booking.paid, @@ -730,12 +614,7 @@ def test_submit_form_without_changes_send_confirmation_ticked(self): 'formset_submitted': 'Save changes' } ) - self.assertTrue( - self.client.login( - username=self.staff_user.username, password='test' - ) - ) - resp = self.client.post(url, data, follow=True) + resp = self.client.post(self.url, data, follow=True) self.assertIn( "'Send confirmation' checked for '{}' but no " @@ -746,8 +625,8 @@ def test_submit_form_without_changes_send_confirmation_ticked(self): def test_cancel_booking(self): self.assertFalse(self.ticket_booking.cancelled) - resp = self._post_response( - self.staff_user, self.ticketed_event, + resp = self.client.post( + self.url, self.formset_data( { @@ -766,9 +645,9 @@ def test_reopen_booking(self): user=self.user ) baker.make(Ticket, ticket_booking=cancelled_tb) - resp = self._post_response( - self.staff_user, self.ticketed_event, - form_data=self.formset_data( + resp = self.client.post( + self.url, + self.formset_data( { 'ticket_bookings-TOTAL_FORMS': 2, 'ticket_bookings-INITIAL_FORMS': 2, @@ -796,7 +675,8 @@ def test_reopen_booking_not_enough_tickets_left(self): baker.make(Ticket, ticket_booking=cancelled_tb, _quantity=2) tb = baker.make( TicketBooking, ticketed_event=ticketed_event, - purchase_confirmed=True + purchase_confirmed=True, + user=self.user ) # make tickets for the event so there is only 1 left baker.make( @@ -804,10 +684,6 @@ def test_reopen_booking_not_enough_tickets_left(self): ) self.assertEqual(ticketed_event.tickets_left(), 1) - url = reverse( - 'studioadmin:ticketed_event_bookings', - kwargs={'slug': ticketed_event.slug} - ) data = { 'ticket_bookings-TOTAL_FORMS': 2, 'ticket_bookings-INITIAL_FORMS': 2, @@ -817,10 +693,9 @@ def test_reopen_booking_not_enough_tickets_left(self): 'show_cancelled': True, 'formset_submitted': 'Save changes', } - self.assertTrue( - self.client.login( - username=self.staff_user.username, password='test' - ) + url = reverse( + 'studioadmin:ticketed_event_bookings', + kwargs={'slug': ticketed_event.slug} ) resp = self.client.post(url, data, follow=True) content = format_content(resp.rendered_content) @@ -837,8 +712,8 @@ def test_reopen_booking_not_enough_tickets_left(self): def test_send_confirmation_to_user_on_update(self): self.assertFalse(self.ticket_booking.paid) - resp = self._post_response( - self.staff_user, self.ticketed_event, + resp = self.client.post( + self.url, self.formset_data( { @@ -865,8 +740,8 @@ def test_send_confirmation_to_user_on_update(self): def test_send_confirmation_email_errors(self, mock_send): mock_send.side_effect = Exception('Error sending email') self.assertFalse(self.ticket_booking.paid) - self._post_response( - self.staff_user, self.ticketed_event, + resp = self.client.post( + self.url, self.formset_data( { @@ -891,8 +766,8 @@ def test_send_confirmation_email_errors(self, mock_send): def test_send_confirmation_to_user_on_cancel(self): self.assertFalse(self.ticket_booking.cancelled) - resp = self._post_response( - self.staff_user, self.ticketed_event, + resp = self.client.post( + self.url, self.formset_data( { @@ -923,22 +798,20 @@ def test_send_confirmation_to_user_on_reopen(self): user=self.user ) baker.make(Ticket, ticket_booking=cancelled_tb) - resp = self._post_response( - self.staff_user, self.ticketed_event, - form_data=self.formset_data( + resp = self.client.post( + self.url, + self.formset_data( { 'ticket_bookings-TOTAL_FORMS': 2, 'ticket_bookings-INITIAL_FORMS': 2, 'ticket_bookings-1-id': cancelled_tb.id, 'ticket_bookings-1-reopen': True, + 'ticket_bookings-1-send_confirmation': True, 'show_cancelled': True, 'formset_submitted': 'Save changes', - 'ticket_bookings-1-send_confirmation': True, } ) - ) - cancelled_tb.refresh_from_db() self.assertFalse(cancelled_tb.cancelled) self.assertEqual(len(mail.outbox), 1) @@ -971,56 +844,37 @@ def setUp(self): 'booking.ticketed_event_max10', date=timezone.now() + timedelta(2) ) - - def _get_response(self, user, ticketed_event): - url = reverse( + self.url_with_booking = reverse( 'studioadmin:cancel_ticketed_event', - kwargs={'slug': ticketed_event.slug} + kwargs={'slug': self.ticketed_event_with_booking.slug} ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return cancel_ticketed_event_view(request, slug=ticketed_event.slug) - - def _post_response(self, user, ticketed_event, form_data): - url = reverse( + self.url_without_booking = reverse( 'studioadmin:cancel_ticketed_event', - kwargs={'slug': ticketed_event.slug} + kwargs={'slug': self.ticketed_event_without_booking.slug} ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return cancel_ticketed_event_view(request, slug=ticketed_event.slug) + + self.client.force_login(self.staff_user) def test_cannot_access_without_login(self): - url = reverse( - 'studioadmin:cancel_ticketed_event', - kwargs={'slug': self.ticketed_event_with_booking.slug} - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url_with_booking) + redirected_url = reverse('account_login') + "?next={}".format(self.url_with_booking) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user, self.ticketed_event_with_booking) + self.client.force_login(self.user) + resp = self.client.get(self.url_with_booking) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user, self.ticketed_event_with_booking) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url_with_booking) self.assertEqual(resp.status_code, 200) def test_get_cancel_page_with_no_bookings(self): # no bookings displayed on page - resp = self._get_response( - self.staff_user, self.ticketed_event_without_booking - ) + resp = self.client.get(self.url_without_booking) self.assertEqual(resp.context_data['open_paid_ticket_bookings'], []) self.assertEqual(resp.context_data['open_unpaid_ticket_bookings'], []) @@ -1041,18 +895,14 @@ def test_get_cancel_page_with_cancelled_bookings_only(self): for tb in TicketBooking.objects.all(): baker.make(Ticket, ticket_booking=tb) - resp = self._get_response( - self.staff_user, self.ticketed_event_without_booking - ) + resp = self.client.get(self.url_without_booking) self.assertEqual(resp.context_data['open_paid_ticket_bookings'], []) self.assertEqual(resp.context_data['open_unpaid_ticket_bookings'], []) def test_get_cancel_page_open_unpaid_bookings(self): # open bookings displayed on page, not in due_refunds list self.assertFalse(self.ticket_booking.paid) - resp = self._get_response( - self.staff_user, self.ticketed_event_with_booking - ) + resp = self.client.get(self.url_with_booking) self.assertEqual(resp.context_data['open_paid_ticket_bookings'], []) self.assertEqual( resp.context_data['open_unpaid_ticket_bookings'], @@ -1062,9 +912,7 @@ def test_get_cancel_page_open_unpaid_bookings(self): def test_get_cancel_page_open_paid_bookings(self): self.ticket_booking.paid = True self.ticket_booking.save() - resp = self._get_response( - self.staff_user, self.ticketed_event_with_booking - ) + resp = self.client.get(self.url_with_booking) self.assertEqual( resp.context_data['open_paid_ticket_bookings'], [self.ticket_booking] @@ -1095,9 +943,7 @@ def test_get_cancel_page_multiple_bookings(self): for tb in TicketBooking.objects.all(): baker.make(Ticket, ticket_booking=tb) - resp = self._get_response( - self.staff_user, self.ticketed_event_with_booking - ) + resp = self.client.get(self.url_with_booking) self.assertEqual( resp.context_data['open_paid_ticket_bookings'], [paid_tb] @@ -1116,10 +962,7 @@ def test_cancelled_event_sets_attributes(self): self.assertTrue(self.ticketed_event_with_booking.payment_open) self.assertFalse(self.ticketed_event_with_booking.cancelled) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) self.ticketed_event_with_booking.refresh_from_db() self.assertFalse(self.ticketed_event_with_booking.show_on_site) self.assertFalse(self.ticketed_event_with_booking.payment_open) @@ -1152,10 +995,7 @@ def test_all_bookings_on_event_cancelled(self): ticketed_event=self.ticketed_event_with_booking ).count(), 5 ) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) self.ticketed_event_with_booking.refresh_from_db() self.assertEqual( TicketBooking.objects.filter( @@ -1189,10 +1029,7 @@ def test_unconfirmed_bookings_cancelled(self): self.assertEqual( self.ticketed_event_with_booking.ticket_bookings.count(), 2 ) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) self.ticketed_event_with_booking.refresh_from_db() self.ticket_booking.refresh_from_db() @@ -1212,10 +1049,8 @@ def test_emails_sent_to_all_users_for_open_bookings(self): for tb in TicketBooking.objects.all(): baker.make(Ticket, ticket_booking=tb) _add_user_email_addresses(TicketBooking) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) + # send 1 email per booking, plus 1 to studio if there are open paid bkgs self.assertEqual(len(mail.outbox), 3) @@ -1232,10 +1067,7 @@ def test_send_email_errors(self, mock_send): for tb in TicketBooking.objects.all(): baker.make(Ticket, ticket_booking=tb) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) # send 1 email per booking, plus 1 to studio if there are open paid bkgs # 3 error emails @@ -1267,10 +1099,7 @@ def test_emails_not_sent_to_users_for_cancelled_bookings(self): for tb in TicketBooking.objects.all(): baker.make(Ticket, ticket_booking=tb) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) # send 1 email per open booking(1); no email to studio as # self.ticket_booking is unpaid @@ -1286,10 +1115,7 @@ def test_emails_not_sent_to_users_for_unconfirmed_bookings(self): paid=True, ) - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) # send 1 email per confirmed booking(1); no email to studio as # self.ticket_booking is unpaid @@ -1300,11 +1126,8 @@ def test_email_only_sent_to_studio_for_open_bookings(self): self.ticket_booking.paid = True self.ticket_booking.save() - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'confirm': 'Yes, cancel this event'} - ) - + self.client.post(self.url_with_booking, {'confirm': 'Yes, cancel this event'}) + # send 1 email per confirmed booking(1); 1 email to studio as # self.ticket_booking is paid self.assertEqual(len(mail.outbox), 2) @@ -1321,10 +1144,7 @@ def test_email_only_sent_to_studio_for_open_bookings(self): ) def test_can_abort_cancel_event_request(self): - self._post_response( - self.staff_user, self.ticketed_event_with_booking, - {'cancel': 'No, take me back'} - ) + self.client.post(self.url_with_booking, {'cancel': 'No, take me back'}) self.ticketed_event_with_booking.refresh_from_db() self.assertFalse(self.ticketed_event_with_booking.cancelled) for tb in self.ticketed_event_with_booking.ticket_bookings.all(): @@ -1345,59 +1165,34 @@ def setUp(self): cancelled=True ) baker.make(Ticket, ticket_booking=self.ticket_booking) - - - def _get_response(self, user, ticket_booking): - url = reverse( - 'studioadmin:confirm_ticket_booking_refund', - args=[ticket_booking.id] - ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = ConfirmTicketBookingRefundView.as_view() - return view(request, pk=ticket_booking.pk) - - def _post_response(self, user, ticket_booking, form_data): - url = reverse( + self.client.force_login(self.staff_user) + self.url = reverse( 'studioadmin:confirm_ticket_booking_refund', - args=[ticket_booking.id] + args=[self.ticket_booking.id] ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = ConfirmTicketBookingRefundView.as_view() - return view(request, pk=ticket_booking.pk) def test_cannot_access_without_login(self): - url = reverse( - 'studioadmin:confirm_ticket_booking_refund', - args=[self.ticket_booking.pk] - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user, self.ticket_booking) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user, self.ticket_booking) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_shows_already_confirmed_msg_for_already_refunded(self): self.ticket_booking.paid = False self.ticket_booking.save() - resp = self._get_response(self.staff_user, self.ticket_booking) + resp = self.client.get(self.url) self.assertIn( 'This ticket booking is unpaid or payment has already been ' 'refunded.', @@ -1406,24 +1201,18 @@ def test_shows_already_confirmed_msg_for_already_refunded(self): def test_confirm_refund_for_paid_booking(self): self.assertTrue(self.ticket_booking.paid) - self._post_response( - self.staff_user, self.ticket_booking, {'confirmed': True} - ) + self.client.post(self.url, {'confirmed': True}) self.ticket_booking.refresh_from_db() self.assertFalse(self.ticket_booking.paid) def test_email_sent_to_user(self): self.assertTrue(self.ticket_booking.paid) - self._post_response( - self.staff_user, self.ticket_booking, {'confirmed': True} - ) + self.client.post(self.url, {'confirmed': True}) self.assertEqual(len(mail.outbox), 1) def test_cancel_confirm_form(self): self.assertTrue(self.ticket_booking.paid) - self._post_response( - self.staff_user, self.ticket_booking, {'cancelled': True} - ) + self.client.post(self.url, {'cancelled': True}) self.ticket_booking.refresh_from_db() self.assertTrue(self.ticket_booking.paid) self.assertEqual(len(mail.outbox), 0) @@ -1463,40 +1252,24 @@ def setUp(self): 10 - i, tb.user.first_name ), ) - - def _get_response(self, user): - url = reverse('studioadmin:print_tickets_list',) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return print_tickets_list(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:print_tickets_list',) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return print_tickets_list(request) + self.client.force_login(self.staff_user) + self.url = reverse('studioadmin:print_tickets_list') def test_cannot_access_without_login(self): - url = reverse('studioadmin:print_tickets_list',) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) def test_cannot_access_unless_staff_user(self): - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) - resp = self._get_response(self.staff_user) + self.client.force_login(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_selecting_event_shows_its_extra_info_fields(self): @@ -1505,7 +1278,7 @@ def test_selecting_event_shows_its_extra_info_fields(self): "ticketed_event" and updates the order_field and show_fields with the event's extra_ticket_info if available """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual( resp.context_data['form'].fields['show_fields'].widget.choices, [ @@ -1516,8 +1289,9 @@ def test_selecting_event_shows_its_extra_info_fields(self): ] ) - post_resp = self._post_response( - self.staff_user, { + resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_user', 'show_date_booked', 'show_booking_reference'], @@ -1525,7 +1299,7 @@ def test_selecting_event_shows_its_extra_info_fields(self): } ) self.assertEqual( - post_resp.context_data['form'].fields['show_fields'].widget.choices, + resp.context_data['form'].fields['show_fields'].widget.choices, [ ('show_booking_user', 'User who made the booking'), ('show_date_booked', 'Date booked'), @@ -1537,15 +1311,16 @@ def test_selecting_event_shows_its_extra_info_fields(self): ) def test_side_nav_selection_in_context(self): - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) self.assertEqual( resp.context_data['sidenav_selection'], 'print_tickets_list' ) def test_print_event_ticket_list(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_user', 'show_date_booked', 'show_booking_reference'], @@ -1570,8 +1345,9 @@ def test_print_event_ticket_list_with_no_open_bookings(self): tb.purchase_confirmed = False tb.save() - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_user', 'show_date_booked', 'show_booking_reference'], @@ -1587,8 +1363,9 @@ def test_print_event_ticket_list_with_no_open_bookings(self): ) def test_print_event_ticket_list_with_form_errors(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['user'], 'order_field': 'ticket_booking__user__first_name', @@ -1621,8 +1398,9 @@ def test_print_list_only_shows_confirmed_and_open_tickets(self): Ticket, ticket_booking=tb, ) - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_user', 'show_date_booked', 'show_booking_reference'], @@ -1650,8 +1428,9 @@ def test_print_list_only_shows_confirmed_and_open_tickets(self): ) def test_print_event_ticket_list_shows_only_selected_fields(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'ticket_booking__user__first_name', @@ -1675,8 +1454,9 @@ def test_print_event_ticket_list_shows_only_selected_fields(self): self.assertNotIn("Extra provided info", post_resp.rendered_content) - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': [ 'show_extra_ticket_info', 'show_extra_ticket_info1' @@ -1696,8 +1476,9 @@ def test_print_event_ticket_list_shows_only_selected_fields(self): ) def test_order_tickets_by_date_booked(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'ticket_booking__date_booked', @@ -1714,8 +1495,9 @@ def test_order_tickets_by_date_booked(self): ) def test_order_tickets_by_booking_user_first_name(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'ticket_booking__user__first_name', @@ -1732,8 +1514,9 @@ def test_order_tickets_by_booking_user_first_name(self): ) def test_order_tickets_by_booking_reference(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'ticket_booking__booking_reference', @@ -1750,8 +1533,9 @@ def test_order_tickets_by_booking_reference(self): ) def test_order_tickets_by_extra_info_fields(self): - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'extra_ticket_info', @@ -1765,8 +1549,9 @@ def test_order_tickets_by_extra_info_fields(self): [tck.id for tck in ordered_tickets] ) - post_resp = self._post_response( - self.staff_user, { + post_resp = self.client.post( + self.url, + { 'ticketed_event': self.ticketed_event.id, 'show_fields': ['show_booking_reference'], 'order_field': 'extra_ticket_info1', diff --git a/studioadmin/tests/test_views/test_timetable_views.py b/studioadmin/tests/test_views/test_timetable_views.py index 1082312a..fb3fb2d6 100644 --- a/studioadmin/tests/test_views/test_timetable_views.py +++ b/studioadmin/tests/test_views/test_timetable_views.py @@ -9,16 +9,9 @@ from django.conf import settings from django.urls import reverse from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from booking.models import Event, FilterCategory -from common.tests.helpers import _create_session, format_content -from studioadmin.views import ( - timetable_admin_list, - TimetableSessionUpdateView, - TimetableSessionCreateView, - upload_timetable_view, -) +from common.tests.helpers import format_content from timetable.models import Session from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -29,26 +22,8 @@ class TimetableAdminListViewTests(TestPermissionMixin, TestCase): def setUp(self): super(TimetableAdminListViewTests, self).setUp() self.session = baker.make_recipe('booking.mon_session', cost=10) - - def _get_response(self, user): - url = reverse('studioadmin:timetable') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return timetable_admin_list(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:timetable') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return timetable_admin_list(request) + self.client.force_login(self.staff_user) + self.url = reverse('studioadmin:timetable') def formset_data(self, extra_data={}): @@ -70,9 +45,9 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:timetable') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -80,7 +55,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -89,7 +65,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -97,7 +74,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_can_delete_sessions(self): @@ -119,14 +96,13 @@ def test_can_delete_sessions(self): data['form-0-DELETE'] = 'on' - self._post_response(self.staff_user, data) + resp = self.client.post(self.url, data) self.assertEqual(Session.objects.count(), 4) def test_can_update_existing_session(self): self.assertEqual(self.session.advance_payment_required, True) - self._post_response( - self.staff_user, self.formset_data( + self.client.post(self.url, self.formset_data( extra_data={'form-0-advance_payment_required': False} ) ) @@ -134,9 +110,7 @@ def test_can_update_existing_session(self): self.assertEqual(self.session.advance_payment_required, False) def test_submitting_valid_form_redirects_back_to_timetable(self): - resp = self._post_response( - self.staff_user, self.formset_data() - ) + resp = self.client.post(self.url, self.formset_data()) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:timetable')) @@ -146,29 +120,8 @@ class TimetableSessionUpdateViewTests(TestPermissionMixin, TestCase): def setUp(self): super(TimetableSessionUpdateViewTests, self).setUp() self.session = baker.make_recipe('booking.mon_session') - - def _get_response(self, user, ttsession): - url = reverse('studioadmin:edit_session', args=[ttsession.id]) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - view = TimetableSessionUpdateView.as_view() - return view(request, pk=ttsession.id) - - def _post_response(self, user, ttsession, form_data): - url = reverse('studioadmin:edit_session', args=[ttsession.id]) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = TimetableSessionUpdateView.as_view() - return view(request, pk=ttsession.id) + self.url = reverse('studioadmin:edit_session', args=[self.session.id]) + self.client.force_login(self.staff_user) def form_data(self, ttsession, extra_data={}): data = { @@ -194,9 +147,9 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:edit_session', args=[self.session.id]) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -204,7 +157,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.session) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -213,7 +167,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.session) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -221,27 +176,22 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.session) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_submitting_valid_session_form_redirects_back_to_timetable(self): - resp = self._post_response( - self.staff_user, self.session, self.form_data(self.session) - ) + resp = self.client.post(self.url, self.form_data(self.session)) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:timetable')) def test_context_data(self): - resp = self._get_response(self.staff_user, self.session) + resp = self.client.get(self.url) self.assertEqual(resp.context_data['sidenav_selection'], 'timetable') self.assertEqual(resp.context_data['session_day'], 'Monday') def test_can_edit_session_data(self): self.assertEqual(self.session.day, '01MON') - resp = self._post_response( - self.staff_user, self.session, - self.form_data(self.session, extra_data={'day': '03WED'}) - ) + resp = self.client.post(self.url, self.form_data(self.session, extra_data={'day': '03WED'})) session = Session.objects.get(id=self.session.id) self.assertEqual(session.day, '03WED') @@ -252,11 +202,7 @@ def test_edit_with_categories(self): form_data = self.form_data( ttsession=session, extra_data={'categories': [category.id]} ) - self.client.login(username=self.staff_user.username, password="test") - self.client.post( - reverse('studioadmin:edit_session', args=[session.id]), - data=form_data - ) + resp = self.client.post(reverse('studioadmin:edit_session', args=[session.id]), form_data) session.refresh_from_db() assert FilterCategory.objects.count() == 1 assert session.categories.first().category == "test ghi" @@ -266,19 +212,13 @@ def test_edit_with_new_category(self): form_data = self.form_data( ttsession=self.session, extra_data={'new_category': "Test 1b"} ) - self.client.login(username=self.staff_user.username, password="test") - self.client.post( - reverse('studioadmin:edit_session', args=[self.session.id]), - data=form_data - ) + resp = self.client.post(self.url, form_data) self.session.refresh_from_db() assert FilterCategory.objects.count() == 2 assert self.session.categories.first().category == "Test 1b" def test_submitting_with_no_changes_does_not_change_session(self): - self._post_response( - self.staff_user, self.session, self.form_data(self.session) - ) + resp = self.client.post(self.url, self.form_data(self.session)) ttsession = Session.objects.get(id=self.session.id) self.assertEqual(self.session.id, ttsession.id) @@ -305,11 +245,7 @@ def test_update_paypal_email_to_non_default(self): 'paypal_email_check': 'testpaypal@test.com' } ) - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:edit_session', args=[self.session.id]), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertIn( "You have changed the paypal receiver email. If you haven't used " @@ -336,10 +272,7 @@ def test_update_paypal_email_to_default(self): 'paypal_email_check': settings.DEFAULT_PAYPAL_EMAIL } ) - resp = self.client.post( - reverse('studioadmin:edit_session', args=[self.session.id]), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertNotIn( "You have changed the paypal receiver email.", format_content(str(resp.content)).replace('\\', '') @@ -359,38 +292,19 @@ def test_update_no_changes(self): 'advance_payment_required': self.session.advance_payment_required, } ) - resp = self.client.post( - reverse('studioadmin:edit_session', args=[self.session.id]), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertIn('No changes made', format_content(str(resp.content))) class TimetableSessionCreateViewTests(TestPermissionMixin, TestCase): - def _get_response(self, user): - url = reverse('studioadmin:add_session') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = TimetableSessionCreateView.as_view() - return view(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:add_session') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - - view = TimetableSessionCreateView.as_view() - return view(request) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:add_session') + + def setUp(self): + self.client.force_login(self.staff_user) def form_data(self, extra_data={}): ev_type = baker.make_recipe('booking.event_type_PC') @@ -415,9 +329,9 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:add_session') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -425,7 +339,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -434,7 +349,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -442,21 +358,21 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_submitting_valid_session_form_redirects_back_to_timetable(self): - resp = self._post_response(self.staff_user, self.form_data()) + resp = self.client.post(self.url, self.form_data()) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('studioadmin:timetable')) def test_context_data(self): - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.context_data['sidenav_selection'], 'add_session') def test_can_add_event(self): self.assertEqual(Session.objects.count(), 0) - resp = self._post_response(self.staff_user, self.form_data()) + resp = self.client.post(self.url, self.form_data()) self.assertEqual(Session.objects.count(), 1) ttsession = Session.objects.first() self.assertEqual(ttsession.name, 'test_event') @@ -468,11 +384,7 @@ def test_create_event_with_non_default_paypal_email(self): 'paypal_email_check': 'testpaypal@test.com' } ) - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:add_session'), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertIn( "You have changed the paypal receiver email from the default value. " @@ -490,10 +402,7 @@ def test_create_event_with_non_default_paypal_email(self): self.assertEqual(session.paypal_email, 'testpaypal@test.com') form_data = self.form_data() - resp = self.client.post( - reverse('studioadmin:add_session'), - form_data, follow=True - ) + resp = self.client.post(self.url, form_data, follow=True) self.assertNotIn( "You have changed the paypal receiver email from the default value.", format_content(str(resp.content)).replace('\\', '') @@ -504,33 +413,21 @@ def test_create_event_with_non_default_paypal_email(self): class UploadTimetableTests(TestPermissionMixin, TestCase): - def _get_response(self, user): - url = reverse('studioadmin:upload_timetable') - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return upload_timetable_view(request) - - def _post_response(self, user, form_data): - url = reverse('studioadmin:upload_timetable') - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return upload_timetable_view(request) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse('studioadmin:upload_timetable') + + def setUp(self): + self.client.force_login(self.staff_user) def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse('studioadmin:upload_timetable') - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -538,7 +435,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -547,15 +445,15 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user) - self.assertEqual(resp.status_code, 302) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.url, reverse('booking:permission_denied')) def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) @patch('studioadmin.forms.timetable_forms.timezone') @@ -573,7 +471,7 @@ def test_events_are_created(self, mock_tz): 'override_options_booking_open': "default", 'override_options_payment_open': "default", } - self._post_response(self.staff_user, form_data) + self.client.post(self.url, form_data) self.assertEqual(Event.objects.count(), 5) event_names = [event.name for event in Event.objects.all()] session_names = [session.name for session in Session.objects.all()] @@ -594,7 +492,7 @@ def test_events_are_created_with_overridden_settings(self, mock_tz): 'override_options_booking_open': "0", 'override_options_payment_open': "0", } - self._post_response(self.staff_user, form_data) + self.client.post(self.url, form_data) self.assertEqual(Event.objects.filter(booking_open=False, payment_open=False, visible_on_site=False).count(), 5) @patch('studioadmin.forms.timetable_forms.timezone') @@ -612,7 +510,7 @@ def test_does_not_create_duplicate_sessions(self, mock_tz): 'override_options_booking_open': "default", 'override_options_payment_open': "default", } - self._post_response(self.staff_user, form_data) + self.client.post(self.url, form_data) self.assertEqual(Event.objects.count(), 5) baker.make_recipe('booking.tue_session', _quantity=2) @@ -620,7 +518,7 @@ def test_does_not_create_duplicate_sessions(self, mock_tz): {'sessions': [session.id for session in Session.objects.all()]} ) self.assertEqual(Session.objects.count(), 7) - self._post_response(self.staff_user, form_data) + self.client.post(self.url, form_data) self.assertEqual(Event.objects.count(), 7) @patch('studioadmin.forms.timetable_forms.timezone') @@ -656,10 +554,7 @@ def test_upload_timetable_with_duplicate_existing_classes(self, mock_tz): 'override_options_booking_open': "default", 'override_options_payment_open': "default", } - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:upload_timetable'), data=form_data - ) + resp = self.client.post(self.url, form_data) # no new classes created self.assertEqual(Event.objects.count(), 2) @@ -680,8 +575,7 @@ def test_get_upload_timetable_multiple_locations(self): session_dm = baker.make_recipe( 'booking.tue_session', name='test1', location="Davidson's Mains" ) - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.get(reverse('studioadmin:upload_timetable')) + resp = self.client.get(self.url) # returns 3 location form with all locations, BP and DM self.assertEqual( @@ -736,10 +630,7 @@ def test_upload_timetable_with_invalid_form_returns_all_locations(self): 'override_options_payment_open': "default", } - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post( - reverse('studioadmin:upload_timetable'), data=form_data - ) + resp = self.client.post(self.url, form_data) # returns one location form with all locations self.assertEqual( @@ -778,8 +669,7 @@ def test_events_are_created_with_categories(self, mock_tz): 'override_options_payment_open': "default", } - self.client.login(username=self.staff_user.username, password="test") - self.client.post(reverse('studioadmin:upload_timetable'), data=form_data) + self.client.post(self.url, form_data) assert Event.objects.count() == 3 mon = Event.objects.get(name="Mon") assert list(mon.categories.all()) == [cat1] diff --git a/studioadmin/tests/test_views/test_user_blocks_views.py b/studioadmin/tests/test_views/test_user_blocks_views.py index e2ec100f..e9c4f92c 100644 --- a/studioadmin/tests/test_views/test_user_blocks_views.py +++ b/studioadmin/tests/test_views/test_user_blocks_views.py @@ -3,12 +3,10 @@ from django.urls import reverse from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from django.utils import timezone from booking.models import Block -from common.tests.helpers import _create_session, format_content -from studioadmin.views import user_blocks_view +from common.tests.helpers import format_content from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -17,32 +15,11 @@ class UserBlocksViewTests(TestPermissionMixin, TestCase): def setUp(self): super(UserBlocksViewTests, self).setUp() self.block = baker.make_recipe('booking.block', user=self.user) - - def _get_response(self, user, user_id): - url = reverse( - 'studioadmin:user_blocks_list', - kwargs={'user_id': user_id} - ) - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return user_blocks_view(request, user_id) - - def _post_response(self, user, user_id, form_data): - url = reverse( + self.url = reverse( 'studioadmin:user_blocks_list', - kwargs={'user_id': user_id} + kwargs={'user_id': self.user.id} ) - session = _create_session() - request = self.factory.post(url, form_data, follow=True) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return user_blocks_view(request, user_id) + self.client.force_login(self.staff_user) def formset_data(self, extra_data={}): @@ -64,12 +41,9 @@ def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse( - 'studioadmin:user_blocks_list', - kwargs={'user_id': self.user.id} - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -77,7 +51,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.user.id) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -86,7 +61,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.user.id) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -94,7 +70,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.user.id) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_view_users_blocks(self): @@ -106,7 +82,11 @@ def test_view_users_blocks(self): 'booking.block', user=new_user, _quantity=2 ) self.assertEqual(Block.objects.count(), 3) - resp = self._get_response(self.staff_user, new_user.id) + url = reverse( + 'studioadmin:user_blocks_list', + kwargs={'user_id': new_user.id} + ) + resp = self.client.get(url) # get all but last form (last form is the empty extra one) block_forms = resp.context_data['userblockformset'].forms[:-1] self.assertEqual(len(block_forms), 2) @@ -119,8 +99,8 @@ def test_view_users_blocks(self): def test_can_update_block(self): self.assertFalse(self.block.paid) - self._post_response( - self.staff_user, self.user.id, + self.client.post( + self.url, self.formset_data({'blocks-0-paid': True}) ) block = Block.objects.get(id=self.block.id) @@ -129,8 +109,8 @@ def test_can_update_block(self): def test_can_create_block(self): block_type = baker.make_recipe('booking.blocktype') self.assertEqual(Block.objects.count(), 1) - self._post_response( - self.staff_user, self.user.id, + self.client.post( + self.url, self.formset_data( { 'blocks-TOTAL_FORMS': 2, @@ -143,8 +123,8 @@ def test_can_create_block(self): def test_can_create_block_without_start_date(self): block_type = baker.make_recipe('booking.blocktype') self.assertEqual(Block.objects.count(), 1) - self._post_response( - self.staff_user, self.user.id, + self.client.post( + self.url, self.formset_data( { 'blocks-TOTAL_FORMS': 2, @@ -162,8 +142,8 @@ def test_formset_unchanged(self): """ test formset submitted unchanged redirects back to user block list """ - resp = self._post_response( - self.staff_user, self.user.id, self.formset_data() + resp = self.client.post( + self.url, self.formset_data() ) self.assertEqual(resp.status_code, 302) self.assertEqual( @@ -176,8 +156,8 @@ def test_formset_unchanged(self): def test_delete_block(self): self.assertFalse(self.block.paid) - self._post_response( - self.staff_user, self.user.id, + self.client.post( + self.url, self.formset_data({'blocks-0-DELETE': True}) ) with self.assertRaises(Block.DoesNotExist): @@ -193,12 +173,7 @@ def test_submitting_with_form_errors_shows_messages(self): 'blocks-1-start_date': '34 Jan 2023' } ) - url = reverse( - 'studioadmin:user_blocks_list', - kwargs={'user_id': self.user.id} - ) - self.client.login(username=self.staff_user.username, password='test') - resp = self.client.post(url, data) + resp = self.client.post(self.url, data) self.assertIn( 'There were errors in the following fields:start_date', @@ -216,46 +191,29 @@ def test_block_pagination(self): self.assertEqual(Block.objects.filter(user=self.user).count(), 21) - self.client.login(username=self.staff_user.username, password='test') # no page in url, shows first page - resp = self.client.get( - reverse( - 'studioadmin:user_blocks_list', args=[self.user.id] - ) - ) + resp = self.client.get(self.url) blocks = resp.context_data['userblockformset'].queryset self.assertEqual(blocks.count(), 10) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 1) # page 1 - resp = self.client.get( - reverse( - 'studioadmin:user_blocks_list', args=[self.user.id] - ) + '?page=1' - ) + resp = self.client.get(self.url + '?page=1') blocks = resp.context_data['userblockformset'].queryset self.assertEqual(blocks.count(), 10) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 1) # page number > max pages gets last page - resp = self.client.get( - reverse( - 'studioadmin:user_blocks_list', args=[self.user.id] - ) + '?page=4' - ) + resp = self.client.get(self.url + '?page=4') blocks = resp.context_data['userblockformset'].queryset self.assertEqual(blocks.count(), 1) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 3) # page not a number > gets first page - resp = self.client.get( - reverse( - 'studioadmin:user_blocks_list', args=[self.user.id] - ) + '?page=foo' - ) + resp = self.client.get(self.url + '?page=foo') blocks = resp.context_data['userblockformset'].queryset self.assertEqual(blocks.count(), 10) paginator = resp.context_data['page_obj'] @@ -266,8 +224,6 @@ def test_post_with_page(self): new_blocks = baker.make_recipe('booking.block', user=self.user, _quantity=15) self.assertEqual(Block.objects.filter(user=self.user).count(), 16) - self.client.login(username=self.staff_user.username, password='test') - data = self.formset_data( { 'blocks-INITIAL_FORMS': 16, @@ -285,9 +241,7 @@ def test_post_with_page(self): data['blocks-{}-paid'.format(i)] = self.block.paid resp = self.client.post( - reverse( - 'studioadmin:user_blocks_list', args=[self.user.id] - ), data + self.url, data ) self.assertEqual( diff --git a/studioadmin/tests/test_views/test_user_bookings_views.py b/studioadmin/tests/test_views/test_user_bookings_views.py index 39b3f314..c08a73ce 100644 --- a/studioadmin/tests/test_views/test_user_bookings_views.py +++ b/studioadmin/tests/test_views/test_user_bookings_views.py @@ -7,14 +7,12 @@ from django.urls import reverse from django.core import mail from django.test import TestCase -from django.contrib.messages.storage.fallback import FallbackStorage from django.utils import timezone from booking.models import Booking, Block, BlockType, EventType, \ WaitingListUser -from common.tests.helpers import _create_session, format_content +from common.tests.helpers import format_content from payments.helpers import create_booking_paypal_transaction -from studioadmin.views import user_bookings_view_old, user_modal_bookings_view from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -59,6 +57,18 @@ def setUp(self): payment_confirmed=True, event=event, ) for event in future_classes3 ] + self.client.force_login(self.staff_user) + + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': cls.user.id} + ) + cls.past_url = reverse( + 'studioadmin:user_past_bookings_list', + kwargs={'user_id': cls.user.id} + ) def formset_data(self, extra_data={}): data = { @@ -80,50 +90,13 @@ def formset_data(self, extra_data={}): return data - def _get_response(self, user, user_id, booking_status='future'): - kwargs = {} - if booking_status == 'future': - url = reverse( - 'studioadmin:user_bookings_list', kwargs={'user_id': user_id} - ) - view = user_bookings_view_old - else: - url = reverse( - 'studioadmin:user_past_bookings_list', - kwargs={'user_id': user_id} - ) - view = user_modal_bookings_view - kwargs['past'] = True - session = _create_session() - request = self.factory.get(url) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return view(request, user_id, **kwargs) - - def _post_response(self, user, user_id, form_data): - url = reverse( - 'studioadmin:user_bookings_list', kwargs={'user_id': user_id} - ) - session = _create_session() - request = self.factory.post(url, form_data) - request.session = session - request.user = user - messages = FallbackStorage(request) - request._messages = messages - return user_bookings_view_old(request, user_id) - def test_cannot_access_if_not_logged_in(self): """ test that the page redirects if user is not logged in """ - url = reverse( - 'studioadmin:user_bookings_list', - kwargs={'user_id': self.user.id} - ) - resp = self.client.get(url) - redirected_url = reverse('account_login') + "?next={}".format(url) + self.client.logout() + resp = self.client.get(self.url) + redirected_url = reverse('account_login') + "?next={}".format(self.url) self.assertEqual(resp.status_code, 302) self.assertIn(redirected_url, resp.url) @@ -131,7 +104,8 @@ def test_cannot_access_if_not_staff(self): """ test that the page redirects if user is not a staff user """ - resp = self._get_response(self.user, self.user.id) + self.client.force_login(self.user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -140,7 +114,8 @@ def test_instructor_group_cannot_access(self): test that the page redirects if user is in the instructor group but is not a staff user """ - resp = self._get_response(self.instructor_user, self.user.id) + self.client.force_login(self.instructor_user) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, reverse('booking:permission_denied')) @@ -148,7 +123,7 @@ def test_can_access_as_staff_user(self): """ test that the page can be accessed by a staff user """ - resp = self._get_response(self.staff_user, self.user.id) + resp = self.client.get(self.url) self.assertEqual(resp.status_code, 200) def test_view_users_bookings(self): @@ -156,7 +131,7 @@ def test_view_users_bookings(self): Test only user's bookings for future events shown by default """ self.assertEqual(Booking.objects.count(), 10) - resp = self._get_response(self.staff_user, self.user.id) + resp = self.client.get(self.url) # get all but last form (last form is the empty extra one) booking_forms = resp.context_data['userbookingformset'].forms[:-1] # show future bookings, both open and cancelled @@ -176,7 +151,7 @@ def test_view_users_bookings(self): def test_filter_bookings_by_booking_status(self): # future bookings - resp = self._get_response(self.staff_user, self.user.id, 'future') + resp = self.client.get(self.url) # get all but last form (last form is the empty extra one) booking_forms = resp.context_data['userbookingformset'].forms[:-1] self.assertEqual(len(booking_forms), 4) @@ -186,7 +161,7 @@ def test_filter_bookings_by_booking_status(self): ) # past bookings - resp = self._get_response(self.staff_user, self.user.id, 'past') + resp = self.client.get(self.past_url) # no formset in past list self.assertNotIn('userbookingformset', resp.context_data) bookings = resp.context_data['bookings'] @@ -205,7 +180,7 @@ def test_can_update_booking(self): form_data = self.formset_data({'bookings-0-paid': False, 'formset_submitted': 'Submit'}) - self._post_response(self.staff_user, self.user.id, form_data=form_data) + self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.future_user_bookings[0].id) self.assertFalse(booking.deposit_paid) self.assertFalse(booking.paid) @@ -234,7 +209,7 @@ def test_can_update_booking_deposit_paid(self): form_data = self.formset_data(extra_data) - self._post_response(self.staff_user, self.user.id, form_data=form_data) + self.client.post(self.url, form_data) unpaid_booking.refresh_from_db() self.assertTrue(unpaid_booking.deposit_paid) self.assertFalse(unpaid_booking.paid) @@ -250,9 +225,7 @@ def test_can_add_booking(self): 'bookings-2-status': 'OPEN' } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) self.assertEqual(Booking.objects.count(), 11) bookings = Booking.objects.filter(event=event) @@ -270,9 +243,7 @@ def test_changing_booking_status_updates_payment_status_also(self): 'bookings-0-status': 'CANCELLED' } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking = Booking.objects.get(id=self.future_user_bookings[0].id) self.assertEqual(booking.status, 'CANCELLED') @@ -301,9 +272,7 @@ def test_changing_booking_status_to_cancelled_removed_block(self): } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking.refresh_from_db() self.assertEqual(booking.status, 'CANCELLED') @@ -334,9 +303,7 @@ def test_can_assign_booking_to_available_block(self): 'bookings-2-block': block.id } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking = Booking.objects.get(id=booking.id) self.assertEqual(booking.block, block) @@ -358,9 +325,7 @@ def test_create_new_block_booking(self): 'bookings-2-block': block1.id } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking = Booking.objects.get(event=event1) self.assertEqual(booking.block, block1) @@ -385,9 +350,7 @@ def test_cannot_create_new_block_booking_with_wrong_blocktype(self): 'bookings-2-block': block2.id } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) errors = resp.context_data['userbookingformset'].errors self.assertIn( { @@ -420,9 +383,7 @@ def test_cannot_overbook_block(self): ) # create new booking with this block - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) self.assertEqual(Booking.objects.count(), 11) bookings = Booking.objects.filter(event=event) self.assertEqual(len(bookings), 1) @@ -446,9 +407,7 @@ def test_cannot_overbook_block(self): } ) # try to create new booking with this block - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) errors = resp.context_data['userbookingformset'].errors self.assertIn( { @@ -476,9 +435,7 @@ def test_cannot_create_new_block_booking_when_no_available_blocktype(self): 'bookings-2-block': block1.id } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) errors = resp.context_data['userbookingformset'].errors self.assertIn( { @@ -502,9 +459,7 @@ def test_cannot_add_booking_to_full_event(self): 'bookings-2-status': 'OPEN' } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) self.assertIn( 'Please correct the following errors:__all__Attempting to create ' @@ -536,9 +491,7 @@ def test_cannot_make_block_booking_unpaid(self): } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) errors = resp.context_data['userbookingformset'].errors self.assertIn( { @@ -553,8 +506,9 @@ def test_formset_unchanged(self): """ test formset submitted unchanged redirects back to user bookings list """ - resp = self._post_response( - self.staff_user, self.user.id, form_data=self.formset_data( + resp = self.client.post( + self.url, + self.formset_data( {'formset_submitted': 'Submit'} ) ) @@ -585,9 +539,7 @@ def test_create_new_booking_as_free_class(self): 'bookings-2-free_class': True } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking = Booking.objects.get(event=event1) self.assertTrue(booking.free_class) self.assertTrue(booking.paid) @@ -611,9 +563,7 @@ def test_cannot_assign_free_class_to_normal_block(self): 'bookings-2-free_class': True } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) errors = resp.context_data['userbookingformset'].errors self.assertIn( { @@ -630,9 +580,7 @@ def test_confirmation_email_sent_if_data_changed(self): 'bookings-0-send_confirmation': 'on', } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) self.assertEqual(len(mail.outbox), 1) def test_confirmation_email_not_sent_if_data_unchanged(self): @@ -640,9 +588,7 @@ def test_confirmation_email_not_sent_if_data_unchanged(self): {'formset_submitted': 'Submit', 'bookings-0-send_confirmation': 'on'} ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) self.assertEqual(len(mail.outbox), 0) def test_cannot_assign_cancelled_booking_to_available_block(self): @@ -669,9 +615,7 @@ def test_cannot_assign_cancelled_booking_to_available_block(self): 'bookings-2-block': block.id } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertFalse(booking.block) @@ -714,9 +658,7 @@ def test_cannot_assign_booking_for_cancelled_event_to_available_block( 'bookings-2-block': block.id } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertFalse(booking.block) @@ -752,9 +694,7 @@ def test_reopen_booking_for_cancelled_event(self): 'bookings-2-status':'OPEN', } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertEqual(booking.status, 'CANCELLED') @@ -790,9 +730,7 @@ def test_open_no_show_booking_for_cancelled_event(self): 'bookings-2-no_show': False } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertEqual(booking.status, 'OPEN') @@ -826,9 +764,7 @@ def test_assign_booking_for_cancelled_event_to_free_class(self): 'bookings-2-status': booking.status } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertFalse(booking.free_class) @@ -863,9 +799,7 @@ def test_assign_booking_for_cancelled_event_as_paid(self): 'bookings-2-status': booking.status } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertFalse(booking.paid) @@ -901,9 +835,7 @@ def test_assign_booking_for_cancelled_event_as_deposit_paid(self): 'bookings-2-status': booking.status } ) - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + resp = self.client.post(self.url, form_data) booking.refresh_from_db() self.assertFalse(booking.paid) @@ -941,9 +873,7 @@ def test_can_assign_free_class_to_free_class_block(self): 'bookings-2-free_class': True } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) bookings = Booking.objects.filter(event=event1) self.assertEqual(len(bookings), 1) @@ -961,9 +891,7 @@ def test_reopen_cancelled_booking(self): 'bookings-0-status': 'OPEN' } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking.refresh_from_db() self.assertEqual(booking.status, 'OPEN') @@ -992,15 +920,14 @@ def test_cannot_reopen_booking_for_full_event(self): 'bookings-0-no_show': booking.no_show } - resp = self._post_response( - self.staff_user, self.user.id, form_data=data + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} ) - + resp = self.client.post(url, data) booking.refresh_from_db() self.assertEqual(booking.status, 'CANCELLED') self.assertIn( - 'Please correct the following errors:__all__Attempting to create ' - 'booking for full event', + 'Attempting to reopen booking for full event', format_content(resp.rendered_content) ) @@ -1025,9 +952,7 @@ def test_cannot_reopen_no_show_booking_for_full_event(self): 'bookings-0-no_show': False } - resp = self._post_response( - self.staff_user, self.user.id, form_data=data - ) + resp = self.client.post(self.url, data) booking.refresh_from_db() self.assertIn( @@ -1052,9 +977,7 @@ def test_remove_block_from_booking(self): 'bookings-0-block': '' } ) - self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) booking.refresh_from_db() self.assertEqual(booking.block, None) @@ -1095,11 +1018,7 @@ def test_new_booking_uses_last_in_free_class_assigned_block(self): 'booking_status': 'OPEN' } ) - self.client.login(username=self.staff_user.username, password='test') - url = reverse( - 'studioadmin:user_bookings_list', kwargs={'user_id': self.user.id} - ) - resp = self.client.post(url, form_data, follow=True) + resp = self.client.post(self.url, form_data, follow=True) booking = Booking.objects.last() self.assertEqual(booking.block, block) @@ -1151,12 +1070,7 @@ def test_using_last_in_free_class_assigned_block_free_block_already_exists(self) 'booking_status': 'OPEN' } ) - self.client.login(username=self.staff_user.username, password='test') - url = reverse( - 'studioadmin:user_bookings_list', - kwargs={'user_id': self.user.id} - ) - resp = self.client.post(url, form_data, follow=True) + resp = self.client.post(self.url, form_data, follow=True) booking = Booking.objects.last() self.assertEqual(booking.block, block) @@ -1179,9 +1093,7 @@ def test_email_errors_when_sending_confirmation(self, mock_send_emails): ) booking = self.future_user_bookings[0] self.assertEqual(booking.status, 'OPEN') - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) # email to support only self.assertEqual(len(mail.outbox), 1) @@ -1205,9 +1117,7 @@ def test_email_errors_when_sending_confirmation_and_support_mail( ) booking = self.future_user_bookings[0] self.assertEqual(booking.status, 'OPEN') - resp = self._post_response( - self.staff_user, self.user.id, form_data=form_data - ) + self.client.post(self.url, form_data) # no email self.assertEqual(len(mail.outbox), 0) @@ -1236,10 +1146,10 @@ def test_cancel_booking_for_full_event_emails_waiting_list(self): 'bookings-0-status': 'CANCELLED', 'bookings-0-paid': booking.paid, } - - resp = self._post_response( - self.staff_user, user.id, form_data=data + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} ) + self.client.post(url, data) booking.refresh_from_db() # booking now cancelled @@ -1272,10 +1182,10 @@ def test_cancel_booking_for_non_full_event_emails_waiting_list(self): 'bookings-0-paid': booking.paid, } - self.client.force_login(self.staff_user) - self.client.post( - reverse('studioadmin:user_bookings_list', kwargs={'user_id': user.id}), data) - + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} + ) + self.client.post(url, data) booking.refresh_from_db() # booking now cancelled assert booking.status == 'CANCELLED' @@ -1312,9 +1222,10 @@ def test_make_booking_no_show_for_full_event_emails_waiting_list(self): 'bookings-0-no_show': True } - resp = self._post_response( - self.staff_user, user.id, form_data=data + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} ) + self.client.post(url, data) booking.refresh_from_db() # booking now no-show, still open and paid @@ -1358,9 +1269,10 @@ def test_email_errors_when_sending_waiting_list_email(self, mock_send): 'bookings-0-paid': booking.paid, } - resp = self._post_response( - self.staff_user, user.id, form_data=data + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} ) + self.client.post(url, data) booking.refresh_from_db() # booking now cancelled @@ -1404,9 +1316,10 @@ def test_email_errors_when_sending_waiting_list_email_and_support( 'bookings-0-paid': booking.paid, } - resp = self._post_response( - self.staff_user, user.id, form_data=data + url = reverse( + 'studioadmin:user_bookings_list', kwargs={'user_id': user.id} ) + self.client.post(url, data) # no email sent self.assertEqual(len(mail.outbox), 0) @@ -1455,11 +1368,7 @@ def test_cancel_direct_paid_CL_or_RH_creates_transfer_block(self): } ) - self.client.login(username=self.staff_user.username, password='test') - self.client.post( - reverse('studioadmin:user_bookings_list', args=[self.user.id]), - data - ) + self.client.post(self.url, data) self.assertTrue( BlockType.objects.filter(identifier='transferred').exists() @@ -1546,13 +1455,7 @@ def test_cancel_free_non_block_CL_or_RH_creates_transfer_block(self): } ) - self.client.login(username=self.staff_user.username, password='test') - self.client.post( - reverse( - 'studioadmin:user_bookings_list', args=[self.user.id] - ), - data, follow=True - ) + self.client.post(self.url, data, follow=True) self.assertTrue( BlockType.objects.filter(identifier='transferred').exists() ) @@ -1619,11 +1522,7 @@ def test_cancel_block_booked_CL_does_not_creates_transfer_block(self): } ) - self.client.login(username=self.staff_user.username, password='test') - self.client.post( - reverse('studioadmin:user_bookings_list', args=[self.user.id]), - data - ) + self.client.post(self.url, data) self.assertFalse( BlockType.objects.filter(identifier='transferred').exists() @@ -1662,11 +1561,7 @@ def test_cancel_free_block_booked_CL_does_not_creates_transfer_block(self): } ) - self.client.login(username=self.staff_user.username, password='test') - self.client.post( - reverse('studioadmin:user_bookings_list', args=[self.user.id]), - data - ) + self.client.post(self.url, data) self.assertFalse( BlockType.objects.filter(identifier='transferred').exists() @@ -1698,46 +1593,29 @@ def test_past_bookings_pagination(self): 24 ) - self.client.login(username=self.staff_user.username, password='test') # no page in url, shows first page - resp = self.client.get( - reverse( - 'studioadmin:user_past_bookings_list', args=[self.user.id] - ) - ) + resp = self.client.get(self.past_url) bookings = resp.context_data['bookings'] self.assertEqual(bookings.count(), 20) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 1) # page 1 - resp = self.client.get( - reverse( - 'studioadmin:user_past_bookings_list', args=[self.user.id] - ) + '?page=1' - ) + resp = self.client.get(self.past_url + '?page=1') bookings = resp.context_data['bookings'] self.assertEqual(bookings.count(), 20) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 1) # page number > max pages gets last page - resp = self.client.get( - reverse( - 'studioadmin:user_past_bookings_list', args=[self.user.id] - ) + '?page=4' - ) + resp = self.client.get(self.past_url + '?page=4') bookings = resp.context_data['bookings'] self.assertEqual(bookings.count(), 4) paginator = resp.context_data['page_obj'] self.assertEqual(paginator.number, 2) # page not a number > gets first page - resp = self.client.get( - reverse( - 'studioadmin:user_past_bookings_list', args=[self.user.id] - ) + '?page=foo' - ) + resp = self.client.get(self.past_url + '?page=foo') bookings = resp.context_data['bookings'] self.assertEqual(bookings.count(), 20) paginator = resp.context_data['page_obj'] @@ -1770,8 +1648,7 @@ def test_create_booking_for_user_on_waiting_list(self): assert event.bookings.count() == 0 assert WaitingListUser.objects.count() == 1 - url = reverse('studioadmin:user_bookings_list', kwargs={'user_id': self.user.id}) - self.client.post(url, data) + self.client.post(self.url, data) assert event.bookings.count() == 1 assert WaitingListUser.objects.count() == 0 diff --git a/studioadmin/tests/test_views/test_user_views.py b/studioadmin/tests/test_views/test_user_views.py index b62ec26d..bf50f508 100644 --- a/studioadmin/tests/test_views/test_user_views.py +++ b/studioadmin/tests/test_views/test_user_views.py @@ -1,5 +1,6 @@ from datetime import datetime from datetime import timezone as dt_timezone +from unittest.mock import Mock, patch from model_bakery import baker import pytest @@ -7,15 +8,13 @@ from django.urls import reverse from django.db.models import Q from django.test import TestCase -from django.contrib.auth.models import Group, User, Permission -from django.contrib.messages.storage.fallback import FallbackStorage +from django.contrib.auth.models import Group, User from django.core import mail from django.utils import timezone from accounts.models import DisclaimerContent, OnlineDisclaimer, PrintDisclaimer -from common.tests.helpers import _create_session, assert_mailchimp_post_data +from common.tests.helpers import assert_mailchimp_post_data from studioadmin.utils import int_str, chaffify -from studioadmin.views import UserListView from studioadmin.views.users import NAME_FILTERS from studioadmin.tests.test_views.helpers import TestPermissionMixin @@ -26,6 +25,13 @@ def setUp(self): super().setUp() self.url = reverse('studioadmin:users') self.client.force_login(self.staff_user) + mockresponse = Mock() + mockresponse.status_code = 200 + self.patcher = patch('requests.request', return_value = mockresponse) + self.mock_request = self.patcher.start() + + def tearDown(self): + self.patcher.stop() def test_cannot_access_if_not_logged_in(self): """ diff --git a/studioadmin/tests/test_views/test_voucher_views.py b/studioadmin/tests/test_views/test_voucher_views.py index 6457d5c1..60b8fa4e 100644 --- a/studioadmin/tests/test_views/test_voucher_views.py +++ b/studioadmin/tests/test_views/test_voucher_views.py @@ -18,6 +18,7 @@ class VoucherListViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): + super().setUpTestData() cls.pc_event_type = baker.make_recipe('booking.event_type_PC') cls.url = reverse('studioadmin:vouchers') @@ -115,6 +116,7 @@ class GiftVoucherListViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): + super().setUpTestData() cls.pc_event_type = baker.make_recipe('booking.event_type_PC') cls.block_type = baker.make_recipe('booking.blocktype') cls.url = reverse('studioadmin:gift_vouchers') @@ -155,6 +157,7 @@ class VoucherCreateViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): + super().setUpTestData() cls.pc_event_type = baker.make_recipe('booking.event_type_PC') cls.url = reverse('studioadmin:add_voucher') @@ -281,6 +284,7 @@ class VoucherUpdateViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): + super().setUpTestData() cls.pc_event_type = baker.make_recipe('booking.event_type_PC') cls.block_type = baker.make_recipe('booking.blocktype') @@ -438,6 +442,7 @@ class BlockVoucherListViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): + super().setUpTestData() cls.block_type = baker.make_recipe('booking.blocktype') cls.url = reverse('studioadmin:block_vouchers') @@ -536,7 +541,7 @@ class VoucherUsesViewTests(TestPermissionMixin, TestCase): @classmethod def setUpTestData(cls): - super(VoucherUsesViewTests, cls).setUpTestData() + super().setUpTestData() cls.voucher = baker.make(EventVoucher) cls.block_voucher = baker.make(BlockVoucher) cls.voucher_url = reverse(