-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_alert.py
More file actions
2986 lines (2764 loc) · 128 KB
/
test_alert.py
File metadata and controls
2986 lines (2764 loc) · 128 KB
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 base64
import importlib
import json
from datetime import datetime, timedelta
from unittest.mock import patch
from dateutil.tz.tz import gettz
from ddt import data, ddt, unpack
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db.models.signals import post_save
from django.test import Client, TestCase
from django.urls import reverse
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from options.models import Option
from rest_framework.test import APIClient
from alert import tasks
from alert.alerts import get_meeting_string
from alert.models import SOURCE_PCA, AddDropPeriod, Registration, RegStatus, register_for_course
from alert.tasks import get_registrations_for_alerts
from courses.models import StatusUpdate
from courses.util import (
get_add_drop_period,
get_or_create_course_and_section,
invalidate_current_semester_cache,
translate_semester,
)
from PennCourses.celery import app as celeryapp
from PennCourses.settings.base import TIME_ZONE
from tests.courses.util import create_mock_data
TEST_SEMESTER = "2019A"
celeryapp.conf.update(CELERY_ALWAYS_EAGER=True) # run asynchronous tasks synchronously
def contains_all(l1, l2):
return len(l1) == len(l2) and sorted(l1) == sorted(l2)
def set_semester():
post_save.disconnect(
receiver=invalidate_current_semester_cache,
sender=Option,
dispatch_uid="invalidate_current_semester_cache",
)
Option(key="SEMESTER", value=TEST_SEMESTER, value_type="TXT").save()
AddDropPeriod(semester=TEST_SEMESTER).save()
def override_delay(modules_names, before_func, before_kwargs):
"""
A function that makes delay()ed functions synchronous for testing. Please read the full docs
(RTFM) before using to prevent unintended behavior or errors.
See AlertRegistrationTestCase.simulate_alert for an example of how to use this function
:param modules_names: a list of 2-tuples of the form (module, name) where module is the module
in which the delay()ed function is located and name is its name. Note that each 2-tuple
corresponds to exactly one delay()ed function.
Make sure to order the delayed functions' 2-tuples in the
modules_names list in the order that they will be executed.
Also, note that each delay()ed function after the first must be
triggered by the previous one (directly or indirectly). Otherwise you could just
call this function multiple times. If this condition is not met,
an error will be thrown. For more complicated use-cases (like patching functions
between delay()ed functions), you will have to implement the functionality of this
function yourself, in a custom way tailored to your use-case.
Example of valid modules_names argument (from AlertRegistrationTestCase.simulate_alert):
[('alert.tasks', 'send_course_alerts'), ('alert.tasks', 'send_alert')]
:param before_func: a function (not its name, the actual function as a variable) which will be
executed to trigger the first delay()ed function in modules_names.
Note that this function MUST trigger the first delay()ed function in modules_names
or an error will be thrown.
Example of a valid before_func argument (from AlertRegistrationTestCase.simulate_alert):
a function simulating the webhook firing which causes send_course_alerts.delay()
to be called
:param before_kwargs: a dictionary of keyword-value arguments which will be
unpacked and passed into before_func
"""
if len(modules_names) > 0:
mn = modules_names[-1]
with patch(mn[0] + "." + mn[1] + ".delay") as mock_func:
mock_func.side_effect = getattr(importlib.import_module(mn[0]), mn[1])
if len(modules_names) == 1:
before_func(**before_kwargs)
else:
override_delay(modules_names[:-1], before_func, before_kwargs)
class RegistrationSaveAutoHeadRegistrationTest(TestCase):
def setUp(self):
set_semester()
user = User.objects.create_user(username="jacob", password="top_secret")
user.save()
self.user = user
def create_reg(self, full_code, **kwargs):
_, section, _, _ = get_or_create_course_and_section(full_code, TEST_SEMESTER)
reg = Registration(section=section, user=self.user, **kwargs)
reg.save()
return reg
def test_new(self):
a = self.create_reg("CIS-120-001")
self.assertEqual(a.head_registration, a)
def test_delete_max_id(self):
self.create_reg("CIS-120-001")
self.create_reg("CIS-160-001")
c = self.create_reg("CIS-121-001")
c.delete()
d = self.create_reg("CIS-240-001")
self.assertEqual(d.head_registration, d)
def test_delete_min_id(self):
a = self.create_reg("CIS-120-001")
self.create_reg("CIS-160-001")
self.create_reg("CIS-121-001")
a.delete()
d = self.create_reg("CIS-240-001")
self.assertEqual(d.head_registration, d)
def test_delete_all(self):
a = self.create_reg("CIS-120-001")
b = self.create_reg("CIS-160-001")
c = self.create_reg("CIS-121-001")
a.delete()
b.delete()
c.delete()
d = self.create_reg("CIS-240-001")
self.assertEqual(d.head_registration, d)
def test_update_resub_group(self):
self.create_reg("CIS-120-001")
b = self.create_reg("CIS-121-001")
c = self.create_reg("CIS-121-001", resubscribed_from=b)
d = self.create_reg("CIS-121-001", resubscribed_from=c)
b_db = Registration.objects.get(id=b.id)
c_db = Registration.objects.get(id=c.id)
d_db = Registration.objects.get(id=d.id)
self.assertEqual(d.head_registration, d)
self.assertEqual(b_db.head_registration, d_db)
self.assertEqual(c_db.head_registration, d_db)
self.assertEqual(d_db.head_registration, d_db)
@patch("alert.models.PushNotification.send_alert")
@patch("alert.models.Text.send_alert")
@patch("alert.models.Email.send_alert")
class SendAlertTestCase(TestCase):
def setUp(self):
set_semester()
_, section, _, _ = get_or_create_course_and_section("CIS-1600-001", TEST_SEMESTER)
section.capacity = 30
section.save()
self.r_legacy = Registration(email="yo@example.com", phone="+15555555555", section=section)
self.r_legacy.save()
user = User.objects.create_user(username="jacob", password="top_secret")
user.save()
self.r = Registration(
email="yo@example.com", phone="+15555555555", section=section, user=user
)
self.r.save()
def test_send_alert_legacy(self, mock_email, mock_text, mock_push_notification):
r_legacy = Registration.objects.get(id=self.r_legacy.id)
self.assertIsNone(r_legacy.user)
self.assertEquals("yo@example.com", r_legacy.email)
self.assertEquals("+15555555555", r_legacy.phone)
self.assertEquals("CIS-1600-001", r_legacy.section.full_code)
self.assertFalse(r_legacy.notification_sent)
self.assertTrue(r_legacy.is_active)
tasks.send_alert(self.r_legacy.id, False, sent_by="ADM")
self.assertTrue(mock_email.called)
self.assertTrue(mock_text.called)
self.assertFalse(mock_push_notification.called)
r_legacy = Registration.objects.get(id=self.r_legacy.id)
self.assertTrue(r_legacy.notification_sent)
self.assertEqual("ADM", r_legacy.notification_sent_by)
def send_alert_helper(self, mock_email, mock_text, mock_push_notification, push_notification):
"""
This function checks that tasks.send_alert triggers the proper Alert subclass
send_alert methods in two cases. The first case is when push notifications are enabled
on the underlying registration, and the second case is when they are not.
"""
self.r.user.profile.push_notifications = push_notification
self.r.user.profile.save()
r = Registration.objects.get(id=self.r.id)
self.assertIsNotNone(r.user)
self.assertIsNotNone(r.user.profile)
self.assertEquals("yo@example.com", r.user.profile.email)
self.assertEquals("+15555555555", r.user.profile.phone)
self.assertEquals("CIS-1600-001", r.section.full_code)
self.assertIsNone(r.email)
self.assertIsNone(r.phone)
self.assertEquals(push_notification, r.user.profile.push_notifications)
self.assertFalse(r.notification_sent)
self.assertTrue(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="O")
)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="C")
)
self.assertEquals(
0,
len(get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="X")),
)
self.assertEquals(
0,
len(get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="")),
)
tasks.send_alert(self.r.id, False, sent_by="ADM")
r = Registration.objects.get(id=self.r.id)
self.assertTrue(mock_email.called)
self.assertEquals(not push_notification, mock_text.called)
self.assertEquals(push_notification, mock_push_notification.called)
self.assertTrue(r.notification_sent)
self.assertIsNotNone("ADM", r.notification_sent_by)
self.assertEqual("ADM", r.notification_sent_by)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="O")
)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="C")
)
def test_send_alert_push(self, mock_email, mock_text, mock_push_notification):
self.send_alert_helper(
mock_email, mock_text, mock_push_notification, push_notification=True
)
def test_send_alert(self, mock_email, mock_text, mock_push_notification):
self.send_alert_helper(
mock_email, mock_text, mock_push_notification, push_notification=False
)
def send_close_notification_helper(
self,
mock_email,
mock_text,
mock_push_notification,
push_notification,
auto_resubscribe,
manual_resubscribe,
):
"""
This function checks that a call to tasks.send_alert for a close notification triggers
the proper Alert subclass send_alert methods in 6 cases. Either push notifications
are enabled or disabled (push_notification is True or False), auto resubscribe is
enabled or disabled on the underlying registration (auto_resubscribe is True or False),
and a manual resubscribe is either triggered or not triggered in the case that
auto_resubscribe is False (manual_resubscribe is True of False).
"""
self.r.user.profile.push_notifications = push_notification
self.r.user.profile.save()
if not manual_resubscribe:
self.r.auto_resubscribe = auto_resubscribe
self.r.close_notification = True
self.r.notification_sent = True
self.r.notification_sent_by = "ADM"
self.r.notification_sent_at = timezone.now()
self.r.save()
r = Registration.objects.get(id=self.r.id)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="O")
)
self.assertTrue(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="C")
)
tasks.send_alert(self.r.id, close_notification=True, sent_by="ADM")
if manual_resubscribe:
r.resubscribe()
r = Registration.objects.get(id=self.r.id)
self.assertTrue(mock_email.called)
self.assertFalse(mock_text.called)
self.assertEquals(push_notification, mock_push_notification.called)
self.assertTrue(r.notification_sent)
self.assertIsNotNone(r.notification_sent_at)
self.assertEqual("ADM", r.notification_sent_by)
self.assertTrue(r.close_notification_sent)
self.assertIsNotNone(r.close_notification_sent_at)
self.assertEqual("ADM", r.close_notification_sent_by)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="O")
)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="C")
)
def test_send_close_notification_push(self, mock_email, mock_text, mock_push_notification):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=True,
auto_resubscribe=True,
manual_resubscribe=False,
)
def test_send_close_notification_push_autoresub(
self, mock_email, mock_text, mock_push_notification
):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=True,
auto_resubscribe=False,
manual_resubscribe=False,
)
def test_send_close_notification_autoresub(self, mock_email, mock_text, mock_push_notification):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=False,
auto_resubscribe=True,
manual_resubscribe=False,
)
def test_send_close_notification(self, mock_email, mock_text, mock_push_notification):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=False,
auto_resubscribe=False,
manual_resubscribe=False,
)
def test_send_close_notification_push_resub(
self, mock_email, mock_text, mock_push_notification
):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=True,
auto_resubscribe=False,
manual_resubscribe=True,
)
def test_send_close_notification_resub(self, mock_email, mock_text, mock_push_notification):
self.send_close_notification_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=False,
auto_resubscribe=False,
manual_resubscribe=True,
)
def dont_resend_alert_helper(
self, mock_email, mock_text, mock_push_notification, close_notification
):
"""
This helper checks that tasks.send_alert does not send new alerts for a registration that
has already triggered an alert in 2 possible cases. Either it is a regular
open notification or it is a close notification (close_notification is True or False).
"""
self.r.notification_sent = True
self.r.close_notification_sent = True
self.r.save()
r = Registration.objects.get(id=self.r.id)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="O")
)
self.assertFalse(
r in get_registrations_for_alerts("CIS-1600-001", TEST_SEMESTER, course_status="C")
)
tasks.send_alert(self.r.id, close_notification=close_notification, sent_by="ADM")
self.assertFalse(mock_email.called)
self.assertFalse(mock_text.called)
self.assertFalse(mock_push_notification.called)
def test_dont_resend_alert(self, mock_email, mock_text, mock_push_notification):
self.dont_resend_alert_helper(
mock_email, mock_text, mock_push_notification, close_notification=False
)
def test_dont_resend_close_notification(self, mock_email, mock_text, mock_push_notification):
self.dont_resend_alert_helper(
mock_email, mock_text, mock_push_notification, close_notification=True
)
def resend_alert_forced_helper(
self,
mock_email,
mock_text,
mock_push_notification,
push_notification,
close_notification,
):
"""
This helper checks that calling tasks.send_alert with the forced parameter as True
will send an alert even if an alert has already been sent for that registration, in
4 possible cases. Either push notifications are enabled or disabled (push_notification
is True or False), and the alert is either normal or it is a close notification
(close_notification is True or False).
"""
self.r.user.profile.push_notifications = push_notification
self.r.user.profile.save()
self.r.close_notification = close_notification
self.r.notification_sent = True
self.r.close_notification_sent = True
self.r.save()
self.r.alert(True)
self.assertTrue(mock_email.called)
self.assertEquals(not push_notification, mock_text.called)
self.assertEquals(push_notification, mock_push_notification.called)
def test_resend_alert_forced(self, mock_email, mock_text, mock_push_notification):
self.resend_alert_forced_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=False,
close_notification=False,
)
def test_resend_alert_forced_push(self, mock_email, mock_text, mock_push_notification):
self.resend_alert_forced_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=True,
close_notification=False,
)
def test_resend_close_notification_forced(self, mock_email, mock_text, mock_push_notification):
self.resend_alert_forced_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=False,
close_notification=True,
)
def test_resend_close_notification_forced_push(
self, mock_email, mock_text, mock_push_notification
):
self.resend_alert_forced_helper(
mock_email,
mock_text,
mock_push_notification,
push_notification=True,
close_notification=True,
)
class RegisterTestCase(TestCase):
def setUp(self):
set_semester()
self.sections = []
self.sections.append(get_or_create_course_and_section("CIS-1600-001", TEST_SEMESTER)[1])
self.sections.append(get_or_create_course_and_section("CIS-1600-002", TEST_SEMESTER)[1])
self.sections.append(get_or_create_course_and_section("CIS-1200-001", TEST_SEMESTER)[1])
def test_successful_registration(self):
res, norm, _ = register_for_course(
self.sections[0].full_code, "e@example.com", "+15555555555"
)
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(1, len(Registration.objects.all()))
r = Registration.objects.get()
self.assertEqual(self.sections[0].full_code, r.section.full_code)
self.assertEqual("e@example.com", r.email)
self.assertEqual("+15555555555", r.phone)
self.assertFalse(r.notification_sent)
self.assertEqual(SOURCE_PCA, r.source)
self.assertIsNone(r.api_key)
def test_nonnormalized_course_code(self):
res, norm, _ = register_for_course("cis1600001", "e@example.com", "+15555555555")
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual("CIS-1600-001", norm)
self.assertEqual(1, len(Registration.objects.all()))
r = Registration.objects.get()
self.assertEqual("CIS-1600-001", r.section.full_code)
def test_duplicate_registration(self):
r1 = Registration(email="e@example.com", phone="+15555555555", section=self.sections[0])
r1.save()
res, norm, _ = register_for_course(
self.sections[0].full_code, "e@example.com", "+15555555555"
)
self.assertEqual(RegStatus.OPEN_REG_EXISTS, res)
self.assertEqual(1, len(Registration.objects.all()))
def test_reregister(self):
r1 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.sections[0],
notification_sent=True,
)
r1.save()
res, norm, _ = register_for_course(
self.sections[0].full_code, "e@example.com", "+15555555555"
)
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(2, len(Registration.objects.all()))
def test_sameuser_diffsections(self):
r1 = Registration(email="e@example.com", phone="+15555555555", section=self.sections[0])
r1.save()
res, norm, _ = register_for_course(
self.sections[1].full_code, "e@example.com", "+15555555555"
)
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(2, len(Registration.objects.all()))
def test_sameuser_diffcourse(self):
r1 = Registration(email="e@example.com", phone="+15555555555", section=self.sections[0])
r1.save()
res, norm, _ = register_for_course(
self.sections[2].full_code, "e@example.com", "+15555555555"
)
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(2, len(Registration.objects.all()))
def test_justemail(self):
res, norm, _ = register_for_course(self.sections[0].full_code, "e@example.com", None)
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(1, len(Registration.objects.all()))
def test_phony_course(self):
res, norm, _ = register_for_course("PHONY-100-001", "e@example.com", "+15555555555")
self.assertEqual(RegStatus.COURSE_NOT_FOUND, res)
self.assertEqual(0, Registration.objects.count())
def test_invalid_course(self):
res, norm, _ = register_for_course("econ 0-0-1", "e@example.com", "+15555555555")
self.assertEqual(RegStatus.COURSE_NOT_FOUND, res)
self.assertEqual(0, Registration.objects.count())
def test_justphone(self):
res, norm, _ = register_for_course(self.sections[0].full_code, None, "5555555555")
self.assertEqual(RegStatus.SUCCESS, res)
self.assertEqual(1, len(Registration.objects.all()))
def test_nocontact(self):
res, norm, _ = register_for_course(self.sections[0].full_code, None, None)
self.assertEqual(RegStatus.NO_CONTACT_INFO, res)
self.assertEqual(0, len(Registration.objects.all()))
def test_nocontact_new(self):
user = User.objects.create_user(username="new_jacob", password="top_secret")
user.save()
new_client = APIClient()
new_client.login(username="new_jacob", password="top_secret")
user = User.objects.get(username="new_jacob")
self.assertIsNone(user.profile.email)
self.assertIsNone(user.profile.phone)
self.assertFalse(user.profile.push_notifications)
res, norm, _ = register_for_course(self.sections[0].full_code, user=user)
self.assertEqual(RegStatus.NO_CONTACT_INFO, res)
self.assertEqual(0, len(Registration.objects.all()))
class ResubscribeTestCase(TestCase):
def setUp(self):
set_semester()
_, self.section, _, _ = get_or_create_course_and_section("CIS-1600-001", TEST_SEMESTER)
self.base_reg = Registration(
email="e@example.com", phone="+15555555555", section=self.section
)
self.base_reg.save()
def test_resubscribe(self):
self.base_reg.notification_sent = True
self.base_reg.save()
reg = self.base_reg.resubscribe()
self.assertNotEqual(reg, self.base_reg)
self.assertEqual(self.base_reg, reg.resubscribed_from)
def test_try_resubscribe_noalert(self):
reg = self.base_reg.resubscribe()
self.assertEqual(reg, self.base_reg)
self.assertIsNone(reg.resubscribed_from)
def test_resubscribe_oldlink(self):
"""following the resubscribe chain from an old link"""
self.base_reg.notification_sent = True
self.base_reg.save()
reg1 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.section,
resubscribed_from=self.base_reg,
notification_sent=True,
)
reg1.save()
reg2 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.section,
resubscribed_from=reg1,
notification_sent=True,
)
reg2.save()
self.base_reg.head_registration = reg2
self.base_reg.save()
reg1.head_registration = reg2
reg1.save()
result = self.base_reg.resubscribe()
self.assertEqual(4, len(Registration.objects.all()))
self.assertEqual(result.resubscribed_from, reg2)
def test_resubscribe_oldlink_noalert(self):
"""testing idempotence on old links"""
self.base_reg.notification_sent = True
self.base_reg.save()
reg1 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.section,
resubscribed_from=self.base_reg,
notification_sent=True,
)
reg1.save()
reg2 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.section,
resubscribed_from=reg1,
notification_sent=True,
)
reg2.save()
reg3 = Registration(
email="e@example.com",
phone="+15555555555",
section=self.section,
resubscribed_from=reg2,
notification_sent=False,
)
reg3.save()
self.base_reg.head_registration = reg3
self.base_reg.save()
reg1.head_registration = reg3
reg1.save()
reg2.head_registration = reg3
reg2.save()
result = self.base_reg.resubscribe()
self.assertEqual(4, len(Registration.objects.all()))
self.assertEqual(result, reg3)
class WebhookTriggeredAlertTestCase(TestCase):
def setUp(self):
set_semester()
_, self.section, _, _ = get_or_create_course_and_section("CIS-1600-001", TEST_SEMESTER)
self.r1 = Registration(email="e@example.com", phone="+15555555555", section=self.section)
self.r2 = Registration(email="f@example.com", phone="+15555555556", section=self.section)
self.r3 = Registration(email="g@example.com", phone="+15555555557", section=self.section)
self.r1.save()
self.r2.save()
self.r3.save()
def test_collect_all(self):
result = tasks.get_registrations_for_alerts(self.section.full_code, TEST_SEMESTER)
expected_ids = [r.id for r in [self.r1, self.r2, self.r3]]
result_ids = [r.id for r in result]
for id_ in expected_ids:
self.assertTrue(id_ in result_ids)
for id_ in result_ids:
self.assertTrue(id_ in expected_ids)
def test_collect_none(self):
get_or_create_course_and_section("CIS-1210-001", TEST_SEMESTER)
result = tasks.get_registrations_for_alerts("CIS-1210-001", TEST_SEMESTER)
self.assertTrue(len(result) == 0)
def test_collect_one(self):
self.r2.notification_sent = True
self.r3.notification_sent = True
self.r2.save()
self.r3.save()
result_ids = [
r.id for r in tasks.get_registrations_for_alerts(self.section.full_code, TEST_SEMESTER)
]
expected_ids = [self.r1.id]
for id_ in expected_ids:
self.assertTrue(id_ in result_ids)
for id_ in result_ids:
self.assertTrue(id_ in expected_ids)
def test_collect_some(self):
self.r2.notification_sent = True
self.r2.save()
result_ids = [
r.id for r in tasks.get_registrations_for_alerts(self.section.full_code, TEST_SEMESTER)
]
expected_ids = [self.r1.id, self.r3.id]
for id_ in expected_ids:
self.assertTrue(id_ in result_ids)
for id_ in result_ids:
self.assertTrue(id_ in expected_ids)
@patch("alert.views.alert_for_course")
class WebhookViewTestCase(TestCase):
def setUp(self):
set_semester()
self.client = Client()
auth = base64.standard_b64encode("webhook:password".encode("ascii"))
self.headers = {
"Authorization": f"Basic {auth.decode()}",
}
self.body = {
"section_id_normalized": "ANTH-3610-401",
"previous_status": "X",
"status": "O",
"status_code_normalized": "Open",
"term": translate_semester(TEST_SEMESTER),
}
Option.objects.update_or_create(
key="SEND_FROM_WEBHOOK", value_type="BOOL", defaults={"value": "TRUE"}
)
def test_alert_called_and_sent_intl(self, mock_alert):
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(
{
"section_id_normalized": "INTL-BUL-001",
"previous_status": "X",
"status": "O",
"status_code_normalized": "Open",
"term": translate_semester(TEST_SEMESTER),
}
),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertTrue(mock_alert.called)
self.assertEqual("INTL-BUL-001", mock_alert.call_args[0][0])
self.assertEqual("2019A", mock_alert.call_args[1]["semester"])
self.assertEqual("O", mock_alert.call_args[1]["course_status"])
self.assertTrue("sent" in json.loads(res.content)["message"])
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertTrue(u.alert_sent)
def test_alert_called_and_sent(self, mock_alert):
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertTrue(mock_alert.called)
self.assertEqual("ANTH-3610-401", mock_alert.call_args[0][0])
self.assertEqual("2019A", mock_alert.call_args[1]["semester"])
self.assertEqual("O", mock_alert.call_args[1]["course_status"])
self.assertTrue("sent" in json.loads(res.content)["message"])
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertTrue(u.alert_sent)
def test_alert_bad_json(self, mock_alert):
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data="blah",
content_type="application/json",
**self.headers,
)
self.assertEqual(400, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_alert_called_closed_course(self, mock_alert):
self.body["status"] = "C"
self.body["status_code_normalized"] = "Closed"
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertTrue("sent" in json.loads(res.content)["message"])
self.assertTrue(mock_alert.called)
self.assertEqual("C", mock_alert.call_args[1]["course_status"])
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertTrue(u.alert_sent)
def test_alert_called_wrong_sem(self, mock_alert):
self.body["term"] = "NOTRM"
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse(
"sent" in json.loads(res.content)["message"],
)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_alert_called_alerts_off(self, mock_alert):
Option.objects.update_or_create(
key="SEND_FROM_WEBHOOK", value_type="BOOL", defaults={"value": "FALSE"}
)
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse("sent" in json.loads(res.content)["message"])
self.assertFalse(mock_alert.called)
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertFalse(u.alert_sent)
def test_after_adp(self, mock_alert):
current_adp = get_add_drop_period(semester=TEST_SEMESTER)
current_adp.end = datetime.utcnow().replace(tzinfo=gettz(TIME_ZONE)) - timedelta(days=1)
current_adp.save()
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse("sent" in json.loads(res.content)["message"])
self.assertFalse(mock_alert.called)
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertFalse(u.alert_sent)
def test_not_current_semester(self, mock_alert):
self.body["term"] = "3021C"
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse("sent" in json.loads(res.content)["message"])
self.assertFalse(mock_alert.called)
self.assertEqual(1, StatusUpdate.objects.count())
u = StatusUpdate.objects.get()
self.assertFalse(u.alert_sent)
def test_bad_format(self, mock_alert):
self.body = {"hello": "world"}
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps({"hello": "world"}),
content_type="application/json",
**self.headers,
)
self.assertEqual(400, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_no_status(self, mock_alert):
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(
{
"section_id_normalized": "ANTH-3610-401",
"previous_status": "X",
"status_code_normalized": "Open",
"term": translate_semester("2019A"),
}
),
content_type="application/json",
**self.headers,
)
self.assertEqual(400, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_wrong_method(self, mock_alert):
res = self.client.get(reverse("webhook", urlconf="alert.urls"), **self.headers)
self.assertEqual(405, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_wrong_content(self, mock_alert):
res = self.client.post(reverse("webhook", urlconf="alert.urls"), **self.headers)
self.assertEqual(415, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_wrong_password(self, mock_alert):
self.headers["Authorization"] = (
"Basic " + base64.standard_b64encode("webhook:abc123".encode("ascii")).decode()
)
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
def test_wrong_user(self, mock_alert):
self.headers["Authorization"] = (
"Basic " + base64.standard_b64encode("baduser:password".encode("ascii")).decode()
)
res = self.client.post(
reverse("webhook", urlconf="alert.urls"),
data=json.dumps(self.body),
content_type="application/json",
**self.headers,
)
self.assertEqual(200, res.status_code)
self.assertFalse(mock_alert.called)
self.assertEqual(0, StatusUpdate.objects.count())
class CourseStatusUpdateTestCase(TestCase):
def setUp(self):
set_semester()
adp = get_add_drop_period(TEST_SEMESTER)
start = adp.estimated_start
end = adp.estimated_end
duration = end - start
_, cis1200_section = create_mock_data("CIS-1200-001", TEST_SEMESTER)
_, cis1600_section = create_mock_data("CIS-1600-001", TEST_SEMESTER)
self.statusUpdates = [
StatusUpdate(
created_at=start - duration / 4,
section=cis1200_section,
old_status="C",
new_status="O",
alert_sent=False,
),
StatusUpdate(
created_at=start + duration / 4,
section=cis1200_section,
old_status="O",
new_status="C",
alert_sent=False,
),
StatusUpdate(
created_at=start + duration / 2,
section=cis1200_section,
old_status="C",
new_status="O",
alert_sent=True,
),
StatusUpdate(
created_at=start + 3 * duration / 4,
section=cis1600_section,
old_status="C",
new_status="O",
alert_sent=True,
),
StatusUpdate(
created_at=end + duration / 4,
section=cis1600_section,
old_status="O",
new_status="C",
alert_sent=False,
),
]
for s in self.statusUpdates:
s.save()
self.client = APIClient()
def test_cis1200(self):
response = self.client.get(reverse("statusupdate", args=["CIS-1200-001"]))
self.assertEqual(200, response.status_code)
self.assertEqual(2, len(response.data))
self.assertEqual(response.data[0]["old_status"], "O")
self.assertEqual(response.data[0]["new_status"], "C")
self.assertEqual(response.data[0]["alert_sent"], False)
self.assertFalse(hasattr(response.data[0], "request_body"))
self.assertEqual(response.data[1]["old_status"], "C")