-
Notifications
You must be signed in to change notification settings - Fork 82
/
tests.py
1382 lines (1124 loc) · 46.3 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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
806
807
808
809
810
811
812
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
from unittest.mock import patch
from datetime import date, timedelta
from faker import Faker
from django.contrib.auth import logout
from django.contrib.auth.models import User, AnonymousUser
from django.conf import settings
from django.core import mail
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.management import call_command
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.test import TestCase, RequestFactory, Client
from django.utils import timezone
from django.utils.html import escape
from rest_framework.test import APIRequestFactory, force_authenticate
from TWLight.applications.factories import ApplicationFactory
from TWLight.applications.models import Application
from TWLight.resources.tests import EditorCraftRoom
from TWLight.resources.factories import PartnerFactory
from TWLight.resources.models import AccessCode, Partner
from TWLight.users.helpers.authorizations import get_all_bundle_authorizations
from TWLight.users.factories import UserFactory, EditorFactory
from TWLight.users.groups import get_coordinators
from TWLight.users.models import Authorization
import TWLight.users.views
from . import views as base_views
from .view_mixins import (
PartnerCoordinatorOrSelf,
CoordinatorsOnly,
EditorsOnly,
EligibleEditorsOnly,
SelfOnly,
ToURequired,
EmailRequired,
)
coordinators = get_coordinators()
class ObjGet(object):
"""
Some view mixins assume that the thing they're mixed with will define
self.get_object. Therefore we provide a class that does only that, and which
we can initialize to return whatever we need for the test.
"""
def __init__(self, obj=None, *args, **kwargs):
self.object = obj
super(ObjGet, self).__init__(*args, **kwargs)
def get_object(self):
return self.object
class DispatchProvider(object):
"""
All mixins assume the thing they're mixed with provides dispatch().
It doesn't need to do anything, since we're testing whether the mixin
raises PermissionDenied - it just needs to exist.
"""
def dispatch(self, request, *args, **kwargs):
return True
class TestPartnerCoordinatorOrSelf(PartnerCoordinatorOrSelf, ObjGet, DispatchProvider):
pass
class TestCoordinatorsOnly(CoordinatorsOnly, DispatchProvider):
pass
class TestEditorsOnly(EditorsOnly, DispatchProvider):
pass
class TestEligibleEditorsOnly(EligibleEditorsOnly, DispatchProvider):
pass
class TestSelfOnly(SelfOnly, ObjGet, DispatchProvider):
pass
class TestToURequired(ToURequired, DispatchProvider):
pass
class TestEmailRequired(EmailRequired, DispatchProvider):
pass
class ViewMixinTests(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
# Some mixins add messages; don't make the tests fail simply because
# MessageMiddleware is unavailable.
cls.message_patcher = patch("TWLight.applications.views.messages.add_message")
cls.message_patcher.start()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
cls.message_patcher.stop()
def tearDown(self):
for user in User.objects.all():
user.delete()
def test_coordinators_or_self_1(self):
"""
PartnerCoordinatorOrSelf should allow coordinators.
"""
user = UserFactory()
coordinators.user_set.add(user)
req = RequestFactory()
req.user = user
test = TestPartnerCoordinatorOrSelf()
# Should not raise error.
# test.dispatch(req)
pass
def test_coordinators_or_self_2(self):
"""
PartnerCoordinatorOrSelf should allow superusers.
"""
user = UserFactory(is_superuser=True)
req = RequestFactory()
req.user = user
test = TestPartnerCoordinatorOrSelf()
test.dispatch(req)
def test_coordinators_or_self_3(self):
"""
PartnerCoordinatorOrSelf should users who are the same as the view's user,
if view.get_object returns a user.
"""
user = UserFactory()
req = RequestFactory()
req.user = user
test = TestPartnerCoordinatorOrSelf(obj=user)
test.dispatch(req)
def test_coordinators_or_self_4(self):
"""
PartnerCoordinatorOrSelf should users who own the object returned by the
view's get_object.
"""
user = UserFactory()
editor = EditorFactory(user=user)
req = RequestFactory()
req.user = user
test = TestPartnerCoordinatorOrSelf(obj=editor)
test.dispatch(req)
def test_coordinators_or_self_5(self):
"""
PartnerCoordinatorOrSelf should not allow users who fail all of the above
criteria.
"""
user = UserFactory(is_superuser=False)
req = RequestFactory()
req.user = user
test = TestPartnerCoordinatorOrSelf(obj=None)
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_coordinators_only_1(self):
"""
CoordinatorsOnly should allow coordinators.
"""
user = UserFactory()
coordinators.user_set.add(user)
req = RequestFactory()
req.user = user
test = TestCoordinatorsOnly()
test.dispatch(req)
def test_coordinators_only_2(self):
"""
CoordinatorsOnly should allow superusers.
"""
user = UserFactory(is_superuser=True)
req = RequestFactory()
req.user = user
test = TestCoordinatorsOnly()
test.dispatch(req)
def test_coordinators_only_3(self):
"""
CoordinatorsOnly should disallow anyone not fitting the above two
criteria.
"""
user = UserFactory(is_superuser=False)
req = RequestFactory()
req.user = user
test = TestCoordinatorsOnly()
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_editors_only_1(self):
"""
EditorsOnly allows editors.
"""
user = UserFactory()
_ = EditorFactory(user=user)
req = RequestFactory()
req.user = user
test = TestEditorsOnly()
test.dispatch(req)
def test_editors_only_2(self):
"""
EditorsOnly does *not* allow superusers who aren't editors.
"""
user = UserFactory(is_superuser=True)
self.assertFalse(hasattr(user, "editor"))
req = RequestFactory()
req.user = user
test = TestEditorsOnly()
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_editors_only_3(self):
"""
EditorsOnly does not allow non-superusers who aren't editors.
"""
user = UserFactory(is_superuser=False)
self.assertFalse(hasattr(user, "editor"))
req = RequestFactory()
req.user = user
test = TestEditorsOnly()
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_eligible_editors_only_1(self):
"""
EligibleEditorsOnly allows eligible editors.
"""
user = UserFactory()
_ = EditorFactory(user=user)
_.wp_bundle_eligible = True
req = RequestFactory()
req.user = user
test = TestEligibleEditorsOnly()
test.dispatch(req)
def test_eligible_editors_only_2(self):
"""
EligibleEditorsOnly does *not* allow superusers who aren't editors.
"""
user = UserFactory(is_superuser=True)
self.assertFalse(hasattr(user, "editor"))
req = RequestFactory()
req.user = user
test = TestEligibleEditorsOnly()
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_eligible_editors_only_3(self):
"""
EligibleEditorsOnly does not allow non-superusers who aren't editors.
"""
user = UserFactory(is_superuser=False)
self.assertFalse(hasattr(user, "editor"))
req = RequestFactory()
req.user = user
test = TestEligibleEditorsOnly()
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_eligible_editors_only_4(self):
"""
EligibleEditorsOnly redirects ineligible editors.
"""
user = UserFactory(is_superuser=False)
self.assertFalse(hasattr(user, "editor"))
_ = EditorFactory(user=user)
_.wp_bundle_eligible = False
req = RequestFactory()
req.user = user
test = TestEligibleEditorsOnly()
resp = test.dispatch(req)
# This test doesn't deny permission; it sends people to my_library.
self.assertTrue(isinstance(resp, HttpResponseRedirect))
def test_self_only_1(self):
"""
SelfOnly allows users who are also the object returned by get_object.
"""
user = UserFactory()
req = RequestFactory()
req.user = user
test = TestSelfOnly(obj=user)
test.dispatch(req)
def test_self_only_2(self):
"""
SelfOnly allows users who own the object returned by get_object.
"""
user = UserFactory()
editor = EditorFactory(user=user)
req = RequestFactory()
req.user = user
test = TestSelfOnly(obj=editor)
test.dispatch(req)
def test_self_only_3(self):
"""
SelfOnly disallows users who fail the above criteria.
"""
# We'll need to force the usernames to be different so that the
# underlying objects will end up different, apparently.
user = UserFactory(username="alice")
req = RequestFactory()
req.user = user
test = TestSelfOnly(obj=None)
with self.assertRaises(PermissionDenied):
test.dispatch(req)
user2 = UserFactory(username="bob")
test = TestSelfOnly(obj=user2)
with self.assertRaises(PermissionDenied):
test.dispatch(req)
def test_tou_required_1(self):
"""
ToURequired allows users who have agreed with the terms of use.
"""
user = UserFactory()
# The user profile should be created by signal on user creation.
user.userprofile.terms_of_use = True
user.userprofile.save()
req = RequestFactory()
req.user = user
# ToURequired expects the request to have a path that it will use to
# construct a next parameter. Doesn't matter what it is, but it needs
# to exist.
req.path = "/"
test = TestToURequired()
test.dispatch(req)
def test_tou_required_2(self):
"""
ToURequired allows superusers.
"""
user = UserFactory(is_superuser=True)
req = RequestFactory()
req.user = user
req.path = "/"
test = TestToURequired()
test.dispatch(req)
def test_tou_required_3(self):
"""
ToURequired disallows users who have failed the above criteria.
"""
user = UserFactory(is_superuser=False)
user.userprofile.terms_of_use = False
user.userprofile.save()
req = RequestFactory()
req.user = user
req.path = "/"
test = TestToURequired()
resp = test.dispatch(req)
# This test doesn't deny permission; it asks people to agree with the
# terms of use.
self.assertTrue(isinstance(resp, HttpResponseRedirect))
def test_email_required_1(self):
"""
EmailRequired allows users who have an email on file.
"""
user = UserFactory(email="definitely@has.email.com")
req = RequestFactory()
req.user = user
# EmailRequired expects the request to have a path that it will use to
# construct a next parameter. Doesn't matter what it is, but it needs
# to exist.
req.path = "/"
test = TestEmailRequired()
test.dispatch(req)
def test_email_required_for_superuser(self):
"""
EmailRequired allows superusers (even without email)
"""
user = UserFactory(email="", is_superuser=True)
req = RequestFactory()
req.user = user
req.path = "/"
test = TestEmailRequired()
test.dispatch(req)
def test_email_required_for_normal_user(self):
"""
EmailRequired disallows users who fail the above criteria.
"""
user = UserFactory(email="", is_superuser=False)
req = RequestFactory()
req.user = user
req.path = "/"
test = TestEmailRequired()
resp = test.dispatch(req)
# This test doesn't deny permission; it asks people to add their email.
self.assertTrue(isinstance(resp, HttpResponseRedirect))
class ExampleApplicationsDataTest(TestCase):
"""
As above, but for the example applications data script.
"""
def test_command_output(self):
# Needs a superuser first.
user = UserFactory()
call_command("user_example_data", "200")
call_command("resources_example_data", "50")
call_command("applications_example_data", "300")
class UserRenewalNoticeTest(TestCase):
"""
Test the user renewal notice management command
"""
def test_command_output(self):
call_command("user_renewal_notice")
class AuthorizationBaseTestCase(TestCase):
"""
Setup class for Authorization Object tests.
Could possibly achieve the same effect via a new factory class.
"""
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.partner1 = PartnerFactory(
authorization_method=Partner.EMAIL, status=Partner.AVAILABLE
)
cls.partner2 = PartnerFactory(
authorization_method=Partner.PROXY,
status=Partner.AVAILABLE,
requested_access_duration=True,
)
cls.partner3 = PartnerFactory(
authorization_method=Partner.CODES, status=Partner.AVAILABLE
)
cls.partner4 = PartnerFactory(
authorization_method=Partner.EMAIL, status=Partner.AVAILABLE
)
cls.partner5 = PartnerFactory(
authorization_method=Partner.EMAIL,
status=Partner.AVAILABLE,
)
cls.editor1 = EditorFactory()
cls.editor1.user.email = Faker(random.choice(settings.FAKER_LOCALES)).email()
cls.editor1.user.save()
cls.editor2 = EditorFactory()
cls.editor3 = EditorFactory()
# Editor 4 is a coordinator with a session.
cls.editor4 = EditorCraftRoom(cls, Terms=True, Coordinator=True)
# Editor 4 is the designated coordinator for all partners.
cls.partner1.coordinator = cls.editor4.user
cls.partner1.account_length = timedelta(days=180)
cls.partner1.target_url = "http://test.localdomain"
cls.partner1.save()
cls.partner2.coordinator = cls.editor4.user
cls.partner2.save()
cls.partner3.coordinator = cls.editor4.user
cls.partner3.save()
cls.partner4.coordinator = cls.editor4.user
cls.partner4.save()
cls.partner5.coordinator = cls.editor4.user
cls.partner5.save()
# Editor 5 is a coordinator without a session and with no designated partners.
cls.editor5 = EditorFactory()
coordinators.user_set.add(cls.editor5.user)
# Create applications.
cls.app1 = ApplicationFactory(
editor=cls.editor1, partner=cls.partner1, status=Application.PENDING
)
cls.app2 = ApplicationFactory(
editor=cls.editor2, partner=cls.partner1, status=Application.PENDING
)
cls.app3 = ApplicationFactory(
editor=cls.editor3, partner=cls.partner1, status=Application.PENDING
)
cls.app4 = ApplicationFactory(
editor=cls.editor1, partner=cls.partner2, status=Application.PENDING
)
cls.app5 = ApplicationFactory(
editor=cls.editor2, partner=cls.partner2, status=Application.PENDING
)
cls.app6 = ApplicationFactory(
editor=cls.editor3, partner=cls.partner2, status=Application.PENDING
)
cls.app7 = ApplicationFactory(
editor=cls.editor1, partner=cls.partner3, status=Application.PENDING
)
cls.app8 = ApplicationFactory(
editor=cls.editor1, partner=cls.partner4, status=Application.PENDING
)
cls.app9 = ApplicationFactory(
editor=cls.editor2, partner=cls.partner3, status=Application.PENDING
)
cls.app10 = ApplicationFactory(
editor=cls.editor1,
partner=cls.partner5,
status=Application.PENDING,
)
cls.app11 = ApplicationFactory(
editor=cls.editor1,
partner=cls.partner5,
status=Application.PENDING,
)
# Editor 4 will update status on applications to partners 1, 2, and 5.
# Send the application
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app1.pk}),
data={"status": Application.SENT},
follow=True,
)
cls.app1.refresh_from_db()
cls.auth_app1 = Authorization.objects.get(
authorizer=cls.editor4.user, user=cls.editor1.user, partners=cls.partner1
)
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app10.pk}),
data={"status": Application.SENT},
follow=True,
)
cls.app10.refresh_from_db()
cls.auth_app10 = Authorization.objects.get(
authorizer=cls.editor4.user,
user=cls.editor1.user,
partners=cls.partner5,
)
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app11.pk}),
data={"status": Application.SENT},
follow=True,
)
cls.app11.refresh_from_db()
cls.auth_app11 = Authorization.objects.get(
authorizer=cls.editor4.user,
user=cls.editor1.user,
partners=cls.partner5,
)
# Send the application
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app2.pk}),
data={"status": Application.SENT},
follow=True,
)
cls.app2.refresh_from_db()
cls.auth_app2 = Authorization.objects.get(
authorizer=cls.editor4.user, user=cls.editor2.user, partners=cls.partner1
)
# Send the application
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app3.pk}),
data={"status": Application.SENT},
follow=True,
)
cls.app3.refresh_from_db()
cls.auth_app3 = Authorization.objects.get(
authorizer=cls.editor4.user, user=cls.editor3.user, partners=cls.partner1
)
# PROXY authorization methods don't set .SENT on the evaluate page;
# .APPROVED will automatically update them to .SENT
# This app was created with a factory, which doesn't create a revision.
# Let's update the status so that we have one.
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app4.pk}),
data={"status": Application.QUESTION},
follow=True,
)
# Approve the application
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app4.pk}),
data={"status": Application.APPROVED},
follow=True,
)
cls.app4.refresh_from_db()
cls.auth_app4 = Authorization.objects.get(
authorizer=cls.editor4.user, user=cls.editor1.user, partners=cls.partner2
)
# This app was created with a factory, which doesn't create a revision.
# Let's update the status so that we have one.
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app5.pk}),
data={"status": Application.QUESTION},
follow=True,
)
# Approve the application
cls.client.post(
reverse("applications:evaluate", kwargs={"pk": cls.app5.pk}),
data={"status": Application.APPROVED},
follow=True,
)
cls.app5.refresh_from_db()
cls.auth_app5 = Authorization.objects.get(
authorizer=cls.editor4.user, user=cls.editor2.user, partners=cls.partner2
)
# Set up an access code to distribute
cls.access_code = AccessCode(code="ABCD-EFGH-IJKL", partner=cls.partner3)
cls.access_code.save()
cls.message_patcher = patch("TWLight.applications.views.messages.add_message")
cls.message_patcher.start()
def tearDown(self):
super().tearDown()
self.partner1.delete()
self.partner2.delete()
self.partner3.delete()
self.partner4.delete()
self.partner5.delete()
self.access_code.delete()
self.editor1.delete()
self.editor2.delete()
self.editor3.delete()
self.editor4.delete()
self.app1.delete()
self.app2.delete()
self.app3.delete()
self.app4.delete()
self.app5.delete()
self.app6.delete()
self.app7.delete()
self.app8.delete()
self.app9.delete()
self.app10.delete()
self.app11.delete()
class AuthorizationTestCase(AuthorizationBaseTestCase):
"""
Tests that Authorizations are correctly created and updated based on user activity.
"""
def test_approval_sets_properties(self):
"""
Test that authorizer is correctly set.
"""
self.assertTrue(self.auth_app1)
self.assertTrue(self.auth_app2)
self.assertTrue(self.auth_app3)
self.assertTrue(self.auth_app4)
self.assertTrue(self.auth_app5)
def test_authorizations_codes(self):
# In the distribution_method == CODES case, make sure that
# an authorization object with the correct information is
# created after a coordinator marks an application as sent.
authorization_object_exists = Authorization.objects.filter(
user=self.app7.user,
authorizer=self.editor4.user,
partners=self.app7.partner,
).exists()
self.assertFalse(authorization_object_exists)
request = RequestFactory().post(
reverse("applications:send_partner", kwargs={"pk": self.app7.partner.pk}),
data={
"accesscode": [
"{app_pk}_{code}".format(
app_pk=self.app7.pk, code=self.access_code.code
)
]
},
)
request.user = self.editor4.user
_ = TWLight.applications.views.SendReadyApplicationsView.as_view()(
request, pk=self.app7.partner.pk
)
authorization_object_exists = Authorization.objects.filter(
user=self.app7.user,
authorizer=self.editor4.user,
partners=self.app7.partner,
).exists()
self.assertTrue(authorization_object_exists)
def test_authorizations_email(self):
# In the distribution_method == EMAIL case, make sure that
# an authorization object with the correct information is
# created after a coordinator marks an application as sent.
authorization_object_exists = Authorization.objects.filter(
user=self.app8.user,
authorizer=self.editor4.user,
partners=self.app8.partner,
).exists()
self.assertFalse(authorization_object_exists)
request = RequestFactory().post(
reverse("applications:send_partner", kwargs={"pk": self.app8.partner.pk}),
data={"applications": [self.app8.pk]},
)
request.user = self.editor4.user
_ = TWLight.applications.views.SendReadyApplicationsView.as_view()(
request, pk=self.app8.partner.pk
)
authorization_object_exists = Authorization.objects.filter(
user=self.app8.user,
authorizer=self.editor4.user,
partners=self.app8.partner,
).exists()
self.assertTrue(authorization_object_exists)
def test_updating_existing_authorization(self):
"""
In the case that an authorization already exists for a user,
and they apply for renewal, their authorization object should
be updated with any new information (e.g. authorizer).
"""
# Revalidate starting authorizer.
self.assertEqual(self.auth_app1.authorizer, self.editor4.user)
# Create a new application to the same partner (in reality this
# is most likely to be a renewal)
app1_renewal = ApplicationFactory(
editor=self.app1.user.editor, partner=self.app1.partner
)
app1_renewal.status = Application.APPROVED
app1_renewal.save()
# Assign a new coordinator to this partner
app1_renewal.partner.coordinator = self.editor5.user
app1_renewal.partner.save()
# And mark this one as sent, but by a different user.
request = RequestFactory().post(
reverse(
"applications:send_partner", kwargs={"pk": app1_renewal.partner.pk}
),
data={"applications": [app1_renewal.pk]},
)
request.user = self.editor5.user
_ = TWLight.applications.views.SendReadyApplicationsView.as_view()(
request, pk=app1_renewal.partner.pk
)
auth_app1_renewal = Authorization.objects.get(
user=self.app1.user,
authorizer=self.editor5.user,
partners=self.app1.partner,
)
self.assertTrue(auth_app1_renewal)
def test_access_codes_email(self):
# For access code partners, when applications are marked sent,
# access codes should be sent automatically via email.
# outbox already has messages in the outbox from creating approved
# applications during setup. So let's get a starting count.
starting_message_count = len(mail.outbox)
request = RequestFactory().post(
reverse("applications:send_partner", kwargs={"pk": self.app9.partner.pk}),
data={
"accesscode": [
"{app_pk}_{code}".format(
app_pk=self.app9.pk, code=self.access_code.code
)
]
},
)
request.user = self.editor4.user
# Mark as sent
response = TWLight.applications.views.SendReadyApplicationsView.as_view()(
request, pk=self.app9.partner.pk
)
# verify that was successful
self.assertEqual(response.status_code, 302)
# We expect one additional email should now be sent.
self.assertEqual(len(mail.outbox), starting_message_count + 1)
# The most recent email should contain the assigned access code.
self.assertTrue(self.access_code.code in mail.outbox[-1].body)
def test_authorization_expiry_date(self):
# For a partner with a set account length we should set the expiry
# date correctly for its authorizations.
expected_expiry = date.today() + self.app1.partner.account_length
self.assertEqual(self.auth_app1.date_expires, expected_expiry)
def test_authorization_expiry_date_proxy(self):
# For a proxy partner we should set the expiry
# date correctly for its authorizations.
expected_expiry = date.today() + timedelta(days=365)
self.assertEqual(self.auth_app4.date_expires, expected_expiry)
def test_authorization_backfill_expiry_date_on_partner_save(self):
# When a proxy partner is saved, and authorizations without an expiration date should have it set correctly.
# This comes up when partner authorization method is changed from one that has no expiration to proxy.
# Zero partner 2 authorizations with no expiry.
initial_partner2_auths_no_expiry_count = 0
initial_partner2_auths_no_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=True
)
for partner2_auth in initial_partner2_auths_no_expiry:
if partner2_auth.is_valid:
initial_partner2_auths_no_expiry_count += 1
# Count partner 2 apps with an expiration date.
initial_partner2_auths_with_expiry_count = 0
initial_partner2_auths_with_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=False
)
for partner2_auth in initial_partner2_auths_with_expiry:
if partner2_auth.is_valid:
initial_partner2_auths_with_expiry_count += 1
# Clear out the expiration date on those.
partner2_auth.date_expires = None
partner2_auth.save()
# Save partner 2
self.partner2.save()
self.partner2.refresh_from_db()
# Count partner 2 apps with an expiration date post_save.
post_save_partner2_auths_with_expiry_count = 0
post_save_partner2_auths_with_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=False
)
for partner2_auth in post_save_partner2_auths_with_expiry:
if partner2_auth.is_valid:
post_save_partner2_auths_with_expiry_count += 1
# All valid partner 2 authorizations have expiry set.
post_save_partner2_auths_no_expiry_count = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=True
).count()
self.assertEqual(
initial_partner2_auths_with_expiry_count
+ initial_partner2_auths_no_expiry_count,
post_save_partner2_auths_with_expiry_count,
)
def test_authorization_backfill_expiry_date_on_partner_save_with_coordinator_deletion(
self,
):
# As above, but this should still work in the case that an authorization's
# coordinator deleted their data after authorizing a user.
initial_partner2_auths_no_expiry_count = 0
initial_partner2_auths_no_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=True
)
for partner2_auth in initial_partner2_auths_no_expiry:
if partner2_auth.is_valid:
initial_partner2_auths_no_expiry_count += 1
# Count partner 2 apps with an expiration date.
initial_partner2_auths_with_expiry_count = 0
initial_partner2_auths_with_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=False
)
for partner2_auth in initial_partner2_auths_with_expiry:
if partner2_auth.is_valid:
initial_partner2_auths_with_expiry_count += 1
# Clear out the expiration date on those.
partner2_auth.date_expires = None
partner2_auth.save()
# Now have partner2's coordinator delete their data
delete_url = reverse("users:delete_data", kwargs={"pk": self.editor4.user.pk})
# Need a password so we can login
self.editor4.user.set_password("editor")
self.editor4.user.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.editor4.user, password="editor")
submit = self.client.post(delete_url)
# We get a strange error if we don't refresh the object first.
self.partner2.refresh_from_db()
# Save partner 2
self.partner2.save()
self.partner2.refresh_from_db()
# Count partner 2 apps with an expiration date post_save.
post_save_partner2_auths_with_expiry_count = 0
post_save_partner2_auths_with_expiry = Authorization.objects.filter(
partners=self.partner2, date_expires__isnull=False
)
for partner2_auth in post_save_partner2_auths_with_expiry:
if partner2_auth.is_valid:
post_save_partner2_auths_with_expiry_count += 1
# All valid partner 2 authorizations have expiry set.