test_views.py 35.8 KB
Newer Older
1
2
3
from unittest import mock
from unittest.mock import MagicMock, Mock

4
from django.conf import settings
5
6
7
8
9
10
from django.contrib import messages
from django.contrib.admin.utils import model_ngettext
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
11
from django.http import HttpResponse
12
from django.template.defaultfilters import floatformat
Thalia Technicie's avatar
Thalia Technicie committed
13
from django.test import Client, TestCase, RequestFactory, override_settings
14
15
16
17
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

18
from members.models import Membership, Profile, Member
19
from registrations import views
20
from registrations.models import Entry, Registration, Renewal, Reference
21
22
23
from registrations.views import RenewalFormView


24
25
26
27
28
def _get_mock_user(is_staff=False, is_authenticated=False, perms=None):
    user = mock.MagicMock()
    user.pk = 1
    user.is_staff = is_staff
    user.is_authenticated = is_authenticated
29

30
31
32
    user.is_superuser = False
    user.user_permissions = perms
    user.has_perm = lambda x: x in perms
33

34
    return user
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


class EntryAdminViewTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.entry1 = Registration.objects.create(
            first_name='John',
            last_name='Doe',
            email='johndoe@example.com',
            programme='computingscience',
            student_number='s1234567',
            starting_year=2014,
            address_street='Heyendaalseweg 135',
            address_street2='',
            address_postal_code='6525AJ',
            address_city='Nijmegen',
52
            address_country='NL',
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
            phone_number='06123456789',
            birthday=timezone.now().replace(year=1990, day=1),
            language='en',
            length=Entry.MEMBERSHIP_YEAR,
            membership_type=Membership.MEMBER,
            status=Entry.STATUS_CONFIRM,
        )
        cls.user = get_user_model().objects.create_user(username='username')
        cls.entry2 = Renewal.objects.create(
            length=Entry.MEMBERSHIP_YEAR,
            membership_type=Membership.MEMBER,
            status=Entry.STATUS_CONFIRM,
            member=cls.user
        )

    def setUp(self):
69
        self.rf = RequestFactory()
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        self.client = Client()
        self.client.force_login(self.user)
        self.view = views.EntryAdminView()

    def _give_user_permissions(self):
        content_type = ContentType.objects.get_for_model(Entry)
        permissions = Permission.objects.filter(
            content_type__app_label=content_type.app_label,
        )
        for p in permissions:
            self.user.user_permissions.add(p)
        self.user.is_staff = True
        self.user.save()

        self.client.logout()
        self.client.force_login(self.user)

    def test_permissions(self):
88
89
        url = '/registration/admin/process/{}/'.format(self.entry1.pk)
        response = self.client.post(url)
90
91
92
93
        self.assertRedirects(response, '/admin/login/?next=%s' % url)

        self._give_user_permissions()

94
95
        url = '/registration/admin/process/{}/'.format(self.entry1.pk)
        response = self.client.post(url)
96
97
98
99
100
101
102
103
        self.assertRedirects(
            response,
            '/admin/registrations/registration/%s/change/' % self.entry1.pk
        )

    @mock.patch('registrations.services.check_unique_user')
    @mock.patch('registrations.services.accept_entries')
    @mock.patch('registrations.services.reject_entries')
104
    def test_post_accept(self, reject_entries, accept_entries,
Thom Wiggers's avatar
Thom Wiggers committed
105
                         check_unique_user):
106
107
        self.view.action = 'accept'
        for type, entry in {
108
109
110
            'registration': self.entry1,
            'renewal': self.entry2
        }.items():
111
112
113
114
115
116
117
118
119
120
121
122
            entry_qs = Entry.objects.filter(pk=entry.pk)
            check_unique_user.reset_mock()
            check_unique_user.return_value = True
            reject_entries.reset_mock()
            reject_entries.return_value = 1
            accept_entries.reset_mock()
            accept_entries.return_value = 1
            with mock.patch(
                    'registrations.models.Entry.objects.filter') as qs_mock:
                qs_mock.return_value = entry_qs
                qs_mock.get = Mock(return_value=entry_qs.get())

123
124
125
126
127
128
129
130
131
                request = self.rf.post(
                    f'/registration/admin/process/{entry.pk}/',
                    {
                        'action': 'accept',
                    }
                )
                request.user = _get_mock_user()
                request.member = request.user
                request._messages = Mock()
132
                response = self.view.post(request, pk=entry.pk)
133
134
135
136
137
138
139

                self.assertEqual(response.status_code, 302)
                self.assertEqual(
                    response.url,
                    '/admin/registrations/%s/%s/change/' % (type, entry.pk)
                )

140
                accept_entries.assert_called_once_with(1, entry_qs)
141
142
143
144
145
146
147
                self.assertFalse(reject_entries.called)

                request._messages.add.assert_called_once_with(
                    messages.SUCCESS, _('Successfully accepted %s.') %
                    model_ngettext(entry_qs.all()[0], 1), '')

                accept_entries.return_value = 0
148
                self.view.post(request, pk=entry.pk)
149
150
151
152
153
154
155

                request._messages.add.assert_any_call(
                    messages.ERROR, _('Could not accept %s.') %
                    model_ngettext(entry_qs.all()[0], 1), '')

                accept_entries.return_value = 1
                check_unique_user.return_value = False
156
                self.view.post(request, pk=entry.pk)
157
158
159
160
161
162
163
164

                request._messages.add.assert_any_call(
                    messages.ERROR, _('Could not accept %s. '
                                      'Username is not unique.') %
                    model_ngettext(entry_qs.all()[0], 1), '')

    @mock.patch('registrations.services.accept_entries')
    @mock.patch('registrations.services.reject_entries')
165
    def test_post_reject(self, reject_entries, accept_entries):
166
167
        self.view.action = 'reject'
        for type, entry in {
168
169
170
            'registration': self.entry1,
            'renewal': self.entry2
        }.items():
171
172
173
174
175
176
177
178
179
180
            accept_entries.reset_mock()
            accept_entries.return_value = 1
            reject_entries.reset_mock()
            reject_entries.return_value = 1
            entry_qs = Entry.objects.filter(pk=entry.pk)
            with mock.patch(
                    'registrations.models.Entry.objects.filter') as qs_mock:
                qs_mock.return_value = entry_qs
                qs_mock.get = Mock(return_value=entry_qs.get())

181
182
183
184
185
186
187
188
189
                request = self.rf.post(
                    f'/registration/admin/process/{entry.pk}/',
                    {
                        'action': 'reject',
                    }
                )
                request.user = _get_mock_user()
                request.member = request.user
                request._messages = Mock()
190
                response = self.view.post(request, pk=entry.pk)
191
192
193
194
195
196
197
198

                self.assertEqual(response.status_code, 302)

                self.assertEqual(
                    response.url,
                    '/admin/registrations/%s/%s/change/' % (type, entry.pk)
                )

199
                reject_entries.assert_called_once_with(1, entry_qs)
200
201
202
203
204
205
206
                self.assertFalse(accept_entries.called)

                request._messages.add.assert_called_once_with(
                    messages.SUCCESS, _('Successfully rejected %s.') %
                    model_ngettext(entry_qs.all()[0], 1), '')

                reject_entries.return_value = 0
207
                self.view.post(request, pk=entry.pk)
208
209
210
211
212

                request._messages.add.assert_any_call(
                    messages.ERROR, _('Could not reject %s.') %
                    model_ngettext(entry_qs.all()[0], 1), '')

213
214
215
216
217
218
219
220
221
222
    @mock.patch('registrations.emails.send_registration_email_confirmation')
    def test_post_resend(self, send_email):
        self.view.action = 'resend'
        for type, entry in {
            'registration': self.entry1,
            'renewal': self.entry2
        }.items():
            entry_qs = Entry.objects.filter(pk=entry.pk)
            send_email.reset_mock()
            send_email.return_value = None
Thom Wiggers's avatar
Thom Wiggers committed
223
224
            with mock.patch(
                    'registrations.models.Entry.objects.filter') as qs_mock:
225
226
227
                qs_mock.return_value = entry_qs
                qs_mock.get = Mock(return_value=entry_qs.get())

228
229
230
231
232
233
234
235
236
                request = self.rf.post(
                    f'/registration/admin/process/{entry.pk}/',
                    {
                        'action': 'resend',
                    }
                )
                request.user = _get_mock_user()
                request.member = request.user
                request._messages = Mock()
237
238
239
240
241
242
243
244
245
246
247
248
249
                response = self.view.post(request, pk=entry.pk)

                self.assertEqual(response.status_code, 302)
                self.assertEqual(
                    response.url,
                    '/admin/registrations/%s/%s/change/' % (type, entry.pk)
                )

                if type == 'registration':
                    send_email.assert_called_once_with(entry)
                elif type == 'renewal':
                    send_email.assert_not_called()

250
251
252
253
254
255
256
257
258
259
    @mock.patch('registrations.services.revert_entry')
    def test_post_revert(self, revert):
        self.view.action = 'revert'
        for type, entry in {
            'registration': self.entry1,
            'renewal': self.entry2
        }.items():
            entry_qs = Entry.objects.filter(pk=entry.pk)
            revert.reset_mock()
            revert.return_value = None
Thom Wiggers's avatar
Thom Wiggers committed
260
261
            with mock.patch(
                    'registrations.models.Entry.objects.filter') as qs_mock:
262
263
264
                qs_mock.return_value = entry_qs
                qs_mock.get = Mock(return_value=entry_qs.get())

265
266
267
268
269
270
271
272
273
                request = self.rf.post(
                    f'/registration/admin/process/{entry.pk}/',
                    {
                        'action': 'revert',
                    }
                )
                request.user = _get_mock_user()
                request.member = request.user
                request._messages = Mock()
274
275
276
277
278
279
280
281
                response = self.view.post(request, pk=entry.pk)

                self.assertEqual(response.status_code, 302)
                self.assertEqual(
                    response.url,
                    '/admin/registrations/%s/%s/change/' % (type, entry.pk)
                )

282
                revert.assert_called_once_with(1, entry.entry_ptr)
283

284
    @mock.patch('registrations.models.Entry.objects.filter')
285
    def test_post_not_exists(self, qs_mock):
286
287
288
289
290
291
292
        qs_mock.return_value = MagicMock(
            get=Mock(
                side_effect=Entry.DoesNotExist,
                return_value=4,
            )
        )

293
294
295
296
297
298
299
300
301
        request = self.rf.post(
            f'/registration/admin/process/1234/',
            {
                'action': 'accept',
            }
        )
        request.user = _get_mock_user()
        request.member = request.user
        request._messages = Mock()
302
        response = self.view.post(request, pk=4)
303
304
305
306
307
308

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('admin:index'))

    @mock.patch('registrations.services.accept_entries')
    @mock.patch('registrations.services.reject_entries')
309
    def test_post_no_action(self, reject_entries, accept_entries):
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        self.view.action = None
        for type, entry in {
            'registration': self.entry1,
            'renewal': self.entry2
        }.items():
            entry_qs = Entry.objects.filter(pk=entry.pk)
            accept_entries.reset_mock()
            accept_entries.return_value = 1
            reject_entries.reset_mock()
            reject_entries.return_value = 1
            with mock.patch(
                    'registrations.models.Entry.objects.filter') as qs_mock:
                qs_mock.return_value = entry_qs
                qs_mock.get = Mock(return_value=entry_qs.get())

325
326
327
328
329
330
                request = self.rf.post(
                    f'/registration/admin/process/{entry.pk}/',
                )
                request.user = _get_mock_user()
                request.member = request.user
                request._messages = Mock()
331
                response = self.view.post(request, pk=entry.pk)
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

                self.assertFalse(reject_entries.called)
                self.assertFalse(accept_entries.called)

                self.assertEqual(response.status_code, 302)
                self.assertEqual(
                    response.url,
                    '/admin/registrations/%s/%s/change/' % (type, entry.pk)
                )


class ConfirmEmailViewTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.entry = Registration.objects.create(
            first_name='John',
            last_name='Doe',
            email='johndoe@example.com',
            programme='computingscience',
            student_number='s1234567',
            starting_year=2014,
            address_street='Heyendaalseweg 135',
            address_street2='',
            address_postal_code='6525AJ',
            address_city='Nijmegen',
358
            address_country='NL',
359
360
361
362
363
364
365
366
367
            phone_number='06123456789',
            birthday=timezone.now().replace(year=1990, day=1),
            language='en',
            length=Entry.MEMBERSHIP_YEAR,
            membership_type=Membership.MEMBER,
            status=Entry.STATUS_CONFIRM,
        )

    def setUp(self):
368
        self.client = Client()
369
370
371
        self.view = views.ConfirmEmailView()

    @mock.patch('registrations.services.confirm_entry')
372
    @mock.patch('registrations.emails.send_references_information_message')
373
    @mock.patch('registrations.emails.send_new_registration_board_message')
374
375
    def test_get(self, board_mail, references_email, confirm_entry):
        reg_qs = Entry.objects.filter(pk=self.entry.pk)
376
        with mock.patch(
377
378
379
                'registrations.models.Registration.objects.filter') as qs_mock:
            qs_mock.return_value = reg_qs
            qs_mock.get = Mock(return_value=reg_qs.get())
380

381
382
383
            with self.subTest('Successful email confirmation'):
                response = self.client.get(reverse(
                    'registrations:confirm-email', args=(self.entry.pk,)))
384

385
386
387
388
389
                self.assertEqual(response.status_code, 200)
                self.assertEqual(
                    response.template_name,
                    ['registrations/confirm_email.html']
                )
390

391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
                confirm_entry.assert_called_once_with(reg_qs)
                board_mail.assert_called_once_with(reg_qs.get())
                self.assertFalse(references_email.called)

            with self.subTest('Successful voucher information'):
                self.entry.membership_type = Membership.BENEFACTOR
                self.entry.no_references = False
                self.entry.save()

                response = self.client.get(reverse(
                    'registrations:confirm-email', args=(self.entry.pk,)))

                self.assertEqual(response.status_code, 200)
                self.assertEqual(
                    response.template_name,
                    ['registrations/confirm_email.html']
                )

                references_email.assert_called_once_with(reg_qs.get())
410

411
412
            with self.subTest('Redirect when nothing was processed'):
                confirm_entry.return_value = 0
413

414
415
416
                response = self.client.get(reverse(
                    'registrations:confirm-email', args=(self.entry.pk,)))
                self.assertEqual(response.status_code, 302)
417
418
                self.assertEqual(response.url,
                                 '/registration/register/member/')
419

Thom Wiggers's avatar
Thom Wiggers committed
420
            with self.subTest('Redirect when registration confirm errors'):
421
                confirm_entry.side_effect = ValidationError(message='Error')
422

423
424
425
                response = self.client.get(reverse(
                    'registrations:confirm-email', args=(self.entry.pk,)))
                self.assertEqual(response.status_code, 302)
426
427
                self.assertEqual(response.url,
                                 '/registration/register/member/')
428

429
430
            with self.subTest('Redirect when no entries were processed'):
                confirm_entry.return_value = 0
431

432
433
434
435
436
                response = self.client.get(reverse(
                    'registrations:confirm-email',
                    args=('00000000-0000-0000-0000-000000000000',)
                ))
                self.assertEqual(response.status_code, 302)
437
438
                self.assertEqual(response.url,
                                 '/registration/register/member/')
439

440
441
442
    def test_get_no_mocks(self):
        response = self.client.get(reverse(
            'registrations:confirm-email', args=(self.entry.pk,)))
443
444
445
446
447
448
449
450
451
452
        self.assertEqual(response.status_code, 200)


class BecomeAMemberViewTest(TestCase):

    def setUp(self):
        self.view = views.BecomeAMemberView()

    def test_get_context_data(self):
        context = self.view.get_context_data()
453
        self.assertEqual(len(context), 3)
454
455
456
457
458
459
        self.assertEqual(context['year_fees'], floatformat(
            settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2))
        self.assertEqual(context['study_fees'], floatformat(
            settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2))


460
class BaseRegistrationFormViewTest(TestCase):
461
462

    def setUp(self):
463
464
        self.rf = RequestFactory()
        self.view = views.BaseRegistrationFormView()
465

Thalia Technicie's avatar
Thalia Technicie committed
466
    @override_settings(GOOGLE_PLACES_API_KEY='hello')
467
    def test_get_context_data(self):
468
        self.view.request = self.rf.post('/')
469
        context = self.view.get_context_data()
Thalia Technicie's avatar
Thalia Technicie committed
470
        self.assertEqual(len(context), 5)
471
472
473
474
        self.assertEqual(context['year_fees'], floatformat(
            settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2))
        self.assertEqual(context['study_fees'], floatformat(
            settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2))
Thalia Technicie's avatar
Thalia Technicie committed
475
        self.assertEqual(context['google_api_key'], 'hello')
476
477
478
479
480

    @mock.patch('django.views.generic.FormView.get')
    def test_get(self, super_get):
        super_get.return_value = HttpResponse(status=200)

481
482
483
        request = self.rf.get('/')
        request.user = _get_mock_user(is_authenticated=False)
        request.member = request.user
484
485
486
        response = self.view.get(request)
        self.assertEqual(response.status_code, 200)

487
488
489
        request = self.rf.get('/')
        request.user = _get_mock_user(is_authenticated=True)
        request.member = request.user
490
491
492
493
        response = self.view.get(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('registrations:renew'))

494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
    def test_form_valid(self):
        mock_form = MagicMock()

        return_value = self.view.form_valid(mock_form)

        mock_form.save.assert_called_once_with()
        self.assertEqual(return_value.status_code, 302)
        self.assertEqual(return_value.url,
                         reverse('registrations:register-success'))


class MemberRegistrationFormViewTest(TestCase):

    def setUp(self):
        self.rf = RequestFactory()
        self.view = views.MemberRegistrationFormView()

511
512
    @mock.patch('django.views.generic.FormView.post')
    def test_post(self, super_post):
513
        request = self.rf.post('/')
514
        request.LANGUAGE_CODE = 'nl'
515
516
        request.user = _get_mock_user()
        request.member = request.user
517
518
519
520
521
522
523
524
525
        request.member.pk = 2
        self.view.request = request

        self.view.post(request)

        request = super_post.call_args[0][0]
        self.assertEqual(request.POST['language'], 'nl')
        self.assertEqual(request.POST['membership_type'], Membership.MEMBER)

526
527
    @mock.patch('registrations.emails.send_registration_email_confirmation')
    def test_form_valid(self, send_email):
528
        mock_form = MagicMock()
529
530
531
        mock_form.instance = {
            'hello': 'world'
        }
532
533
534
535
536
537
538
539

        return_value = self.view.form_valid(mock_form)

        mock_form.save.assert_called_once_with()
        self.assertEqual(return_value.status_code, 302)
        self.assertEqual(return_value.url,
                         reverse('registrations:register-success'))

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
        send_email.assert_called_once_with(mock_form.instance)


class BenefactorRegistrationFormViewTest(TestCase):

    def setUp(self):
        self.rf = RequestFactory()
        self.view = views.BenefactorRegistrationFormView()

    @mock.patch('django.views.generic.FormView.post')
    def test_post(self, super_post):
        request = self.rf.post('/', {})
        request.LANGUAGE_CODE = 'nl'
        request.user = _get_mock_user()
        request.member = request.user
        request.member.pk = 2
        self.view.request = request

        with self.subTest('No iCIS employee'):
            self.view.post(request)

            request = super_post.call_args[0][0]
            self.assertEqual(request.POST['language'], 'nl')
            self.assertEqual(request.POST['membership_type'],
                             Membership.BENEFACTOR)
            self.assertEqual(request.POST['length'], Entry.MEMBERSHIP_YEAR)
            self.assertEqual(request.POST['remarks'], '')

        request = self.rf.post('/', {
            'icis_employee': True
        })
        request.LANGUAGE_CODE = 'nl'
        request.user = _get_mock_user()
        request.member = request.user
        request.member.pk = 2
        self.view.request = request

        with self.subTest('An iCIS employee'):
            self.view.post(request)

            request = super_post.call_args[0][0]
            self.assertEqual(request.POST['language'], 'nl')
            self.assertEqual(request.POST['membership_type'],
                             Membership.BENEFACTOR)
            self.assertEqual(request.POST['length'], Entry.MEMBERSHIP_YEAR)
            self.assertEqual(request.POST['remarks'],
                             'Registered as iCIS employee')

588
589
590
591

class RenewalFormViewTest(TestCase):

    def setUp(self):
592
        self.rf = RequestFactory()
593
594
595
596
597
598
599
600
601
        self.view = views.RenewalFormView()

    def test_get_context_data(self):
        membership = Membership(
            pk=2,
            type=Membership.MEMBER
        )
        self.view.request = MagicMock()

Thom Wiggers's avatar
Thom Wiggers committed
602
        with mock.patch('members.models.Membership.objects'
603
                        ) as _qs:  # noqa: F841
604
605
            Membership.objects.filter().exists.return_value = True
            context = self.view.get_context_data(form=MagicMock())
606
            self.assertEqual(len(context), 7)
607
608
609
610
611
612
613
614
615
            self.assertEqual(context['year_fees'], floatformat(
                settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2))
            self.assertEqual(context['study_fees'], floatformat(
                settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2))
            self.assertEqual(context['was_member'], True)

            Membership.objects.filter().exists.return_value = False
            context = self.view.get_context_data(form=MagicMock())
            self.assertEqual(context['was_member'], False)
616

617
618
            with self.subTest("With latest membership"):
                self.view.request.member.latest_membership = membership
619

620
                context = self.view.get_context_data(form=MagicMock())
621
                self.assertEqual(context['latest_membership'], membership)
622

623
624
            with self.subTest('Without latest membership'):
                self.view.request.member.latest_membership = None
625

626
                context = self.view.get_context_data(form=MagicMock())
627
                self.assertEqual(context['latest_membership'], None)
628
629

    def test_get_form(self):
630
        self.view.request = self.rf.get('/')
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658

        self.view.request.member = None
        form = self.view.get_form()
        self.assertFalse(Entry.MEMBERSHIP_YEAR in
                         form.fields['length'].choices)

        self.view.request.member = MagicMock()
        self.view.request.member.latest_membership = None
        form = self.view.get_form()
        self.assertFalse(Entry.MEMBERSHIP_YEAR in
                         form.fields['length'].choices)

        self.view.request.member.latest_membership = Membership(
            until=None
        )
        form = self.view.get_form()
        self.assertFalse(Entry.MEMBERSHIP_YEAR in
                         form.fields['length'].choices)

        self.view.request.member.latest_membership = Membership(
            until=timezone.now().date()
        )
        form = self.view.get_form()
        self.assertEqual(Entry.MEMBERSHIP_YEAR,
                         form.fields['length'].choices[1][0])

    @mock.patch('django.views.generic.FormView.post')
    def test_post(self, super_post):
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
        with mock.patch('members.models.Membership.objects'):
            Membership.objects.filter().exists.return_value = False
            with self.subTest('Member type'):
                request = self.rf.post('/', {
                    'membership_type': Membership.MEMBER
                })
                request.member = MagicMock()
                request.member.pk = 2
                self.view.request = request

                request.member.latest_membership.type = Membership.MEMBER
                self.view.post(request)

                request = super_post.call_args[0][0]
                self.assertEqual(request.POST['member'], 2)
                self.assertEqual(request.POST['remarks'], '')
675
                self.assertEqual(request.POST['no_references'], True)
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692

            with self.subTest('Forced benefactor type'):
                request = self.rf.post('/', {
                    'membership_type': Membership.MEMBER
                })
                request.member = MagicMock()
                request.member.pk = 2
                self.view.request = request

                request.member.latest_membership.type = Membership.BENEFACTOR
                self.view.post(request)

                request = super_post.call_args[0][0]
                self.assertEqual(request.POST['member'], 2)
                self.assertEqual(request.POST['membership_type'],
                                 Membership.BENEFACTOR)
                self.assertEqual(request.POST['length'], Entry.MEMBERSHIP_YEAR)
693
                self.assertEqual(request.POST['no_references'], False)
694
695
696
697
698
699
700
701
702
703
704
705
706
707

            with self.subTest('Detects old memberships'):
                request = self.rf.post('/', {
                    'membership_type': Membership.BENEFACTOR
                })
                request.member = MagicMock()
                request.member.pk = 2
                self.view.request = request

                Membership.objects.filter().exists.return_value = True
                self.view.post(request)
                request = super_post.call_args[0][0]
                self.assertEqual(request.POST['remarks'],
                                 'Was a Thalia member in the past.')
708
                self.assertEqual(request.POST['no_references'], True)
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723

            with self.subTest('Adds iCIS remark'):
                request = self.rf.post('/', {
                    'membership_type': Membership.BENEFACTOR,
                    'icis_employee': True
                })
                request.member = MagicMock()
                request.member.pk = 2
                self.view.request = request

                Membership.objects.filter().exists.return_value = False
                self.view.post(request)
                request = super_post.call_args[0][0]
                self.assertEqual(request.POST['remarks'],
                                 'Registered as iCIS employee.')
724
                self.assertEqual(request.POST['no_references'], True)
725
726
727
728
729
730
731
732
733
734
735
736

    @mock.patch('registrations.emails.send_references_information_message')
    @mock.patch('registrations.emails.send_new_renewal_board_message')
    def test_form_valid(self, board_mail, references_mail):
        mock_form = Mock(spec=RenewalFormView)
        member = Member(
            email="test@example.org",
            first_name='John',
            last_name='Doe',
            profile=Profile(
                language='en'
            )
737
        )
738

739
740
741
742
743
        renewal = Renewal(
            pk=0,
            member=member
        )
        mock_form.save = MagicMock(return_value=renewal)
744

745
746
747
748
749
        with self.subTest('No references required'):
            renewal.no_references = True
            return_value = self.view.form_valid(mock_form)
            board_mail.assert_called_once_with(renewal)
            self.assertFalse(references_mail.called)
750

751
752
753
            self.assertEqual(return_value.status_code, 302)
            self.assertEqual(return_value.url,
                             reverse('registrations:renew-success'))
754

755
        board_mail.reset_mock()
756

757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
        with self.subTest('References required'):
            renewal.no_references = False
            return_value = self.view.form_valid(mock_form)
            board_mail.assert_called_once_with(renewal)
            references_mail.assert_called_once_with(renewal)

            self.assertEqual(return_value.status_code, 302)
            self.assertEqual(return_value.url,
                             reverse('registrations:renew-success'))


class ReferenceCreateViewTest(TestCase):
    """
    Test for the ReferenceCreateView
    """
    fixtures = ['members.json']

    @classmethod
    def setUpTestData(cls):
        cls.login_user = Member.objects.filter(last_name="Wiggers").first()
        cls.registration = Registration.objects.create(
            first_name='John',
            last_name='Doe',
            email='johndoe@example.com',
            programme='computingscience',
            student_number='s1234567',
            starting_year=2014,
            address_street='Heyendaalseweg 135',
            address_street2='',
            address_postal_code='6525AJ',
            address_city='Nijmegen',
            address_country='NL',
            phone_number='06123456789',
            birthday=timezone.now().replace(year=1990, day=1),
            language='en',
            length=Entry.MEMBERSHIP_YEAR,
            membership_type=Membership.BENEFACTOR,
            status=Entry.STATUS_CONFIRM,
        )
        cls.new_user = get_user_model().objects.create_user(
            username='username',
            first_name='Johnny',
            last_name='Test'
        )
        cls.renewal = Renewal.objects.create(
            length=Entry.MEMBERSHIP_YEAR,
            membership_type=Membership.BENEFACTOR,
            status=Entry.STATUS_CONFIRM,
            member=cls.new_user
806
807
        )

808
809
810
811
812
    def setUp(self):
        self.rf = RequestFactory()
        self.view = views.ReferenceCreateView()
        self.client = Client()
        self.client.force_login(self.login_user)
813

814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    def test_not_logged_in(self):
        """
        If there is no logged-in user they should redirect
        to the authentication page
        """
        self.client.logout()

        response = self.client.get(
            reverse('registrations:reference',
                    args=(self.registration.pk,)),
            follow=True
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            [('/login/?next=' +
              reverse('registrations:reference',
                      args=(self.registration.pk,)), 302)],
            response.redirect_chain
        )

    def test_not_a_current_member(self):
        """
        If the logged-in user is not a member they should not be able to visit
        this page
        """
        self.client.logout()
        self.client.force_login(self.new_user)

        response = self.client.get(reverse('registrations:reference',
                                           args=(self.registration.pk,)))
        self.assertEqual(403, response.status_code)

    def test_entry_does_not_exist(self):
        """
        If the registration/renewal does not exist a 404 should be shown
        """
        response = self.client.get(reverse(
            'registrations:reference',
            args=('00000000-0000-0000-0000-000000000000',)
        ))
        self.assertEqual(404, response.status_code)

    def test_entry_no_references_required(self):
        """
        If the registration/renewal does not require references
        a 404 should be shown
        """
        self.registration.no_references = True
        self.registration.save()

        response = self.client.get(reverse('registrations:reference',
                                           args=(self.registration.pk,)))
        self.assertEqual(404, response.status_code)

    def test_entry_no_benefactor(self):
        """
        If the registration/renewal is not a the benefactor type
        a 404 should be shown
        """
        self.registration.membership_type = Membership.MEMBER
        self.registration.save()

        response = self.client.get(reverse('registrations:reference',
                                           args=(self.registration.pk,)))
        self.assertEqual(404, response.status_code)

    def test_entry_shows_info(self):
        """
        If everything is alright the info and submission buttons should
        be shown
        """
        with self.subTest('Registration'):
            response = self.client.get(reverse('registrations:reference',
                                               args=(self.registration.pk,)))
            self.assertEqual(200, response.status_code)
            self.assertEqual('John Doe', response.context['name'])
            self.assertEqual(False, response.context['success'])
            self.assertContains(
                response,
                '<strong>John Doe</strong> wants to become a benefactor'
            )

        with self.subTest('Renewal'):
            response = self.client.get(reverse('registrations:reference',
                                               args=(self.renewal.pk,)))
            self.assertEqual(200, response.status_code)
            self.assertEqual('Johnny Test', response.context['name'])
            self.assertEqual(False, response.context['success'])
            self.assertContains(
                response,
                '<strong>Johnny Test</strong> wants to become a benefactor'
            )

    def test_entry_saves_correctly(self):
        """
        If a entry is saved it should redirect to the success page
        which should show the right content. And the Reference object
        should be saved.
        """
        response = self.client.post(
            reverse('registrations:reference', args=(self.registration.pk,)),
            follow=True
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            [(reverse('registrations:reference-success',
                      args=(self.registration.pk,)), 302)],
            response.redirect_chain
        )
        self.assertEqual('John Doe', response.context['name'])
        self.assertEqual(True, response.context['success'])
        self.assertContains(
            response,
            'Your reference has been saved.'
        )

        self.assertTrue(
            Reference.objects.filter(
                member=self.login_user,
                entry=self.registration
            ).exists()
        )

    def test_entry_reference_exists(self):
        """
        If there is already a reference for an entry then the page should
        show an error and not redirect.
        """
        Reference.objects.create(
            member=self.login_user,
            entry=self.registration
        )

        response = self.client.post(
            reverse('registrations:reference', args=(self.registration.pk,)),
            follow=True
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            [],
            response.redirect_chain
        )
        self.assertEqual({
957
            '__all__': ['You\'ve already given a reference for this person.']
958
959
960
961
        }, response.context['form'].errors)
        self.assertEqual(False, response.context['success'])
        self.assertContains(
            response,
962
            'You&#39;ve already given a reference for this person.'
963
        )