-
Notifications
You must be signed in to change notification settings - Fork 81
/
tests.py
2604 lines (2180 loc) · 96.7 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
# -*- coding: utf-8 -*-
import copy
from datetime import datetime, date, timedelta
import json
import re
from unittest.mock import patch, Mock
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User, AnonymousUser
from django.core import mail
from django.core.exceptions import (
PermissionDenied,
SuspiciousOperation,
ValidationError,
)
from django.urls import resolve, reverse
from django.core.management import call_command
from django.test import TestCase, Client, RequestFactory
from django.utils.translation import get_language
from django.utils.html import escape
from django.utils.timezone import now
from TWLight.applications.factories import ApplicationFactory
from TWLight.applications.models import Application
from TWLight.resources.factories import PartnerFactory
from TWLight.resources.filters import INSTANT, MULTI_STEP
from TWLight.resources.models import Partner
from TWLight.resources.tests import EditorCraftRoom
from . import views
from .oauth import OAuthBackend
from .helpers.validation import validate_partners
from .helpers.authorizations import get_all_bundle_authorizations
from .helpers.wiki_list import WIKIS, LANGUAGE_CODES
from .factories import EditorFactory, UserFactory
from .groups import get_coordinators, get_restricted
from .models import UserProfile, Editor, Authorization
from .views import MyLibraryView
from TWLight.users.helpers.editor_data import (
editor_valid,
editor_account_old_enough,
editor_enough_edits,
editor_not_blocked,
editor_reg_date,
editor_bundle_eligible,
editor_make_block_dict,
editor_compare_hashes,
)
FAKE_IDENTITY_DATA = {"query": {"userinfo": {"options": {"disablemail": 0}}}}
FAKE_IDENTITY = {
"editcount": 5000,
"registered": "20151106154629", # Well before first commit.
"blocked": False,
"iss": urlparse(settings.TWLIGHT_OAUTH_PROVIDER_URL).scheme
+ urlparse(settings.TWLIGHT_OAUTH_PROVIDER_URL).netloc,
"sub": 567823,
"rights": ["deletion", "spaceflight", "autoconfirmed"],
"groups": ["charismatic megafauna"],
"email": "alice@example.com",
"username": "alice",
}
FAKE_MERGED_ACCOUNTS = [
{
"wiki": "enwiki",
"url": "https://en.wikipedia.org",
"timestamp": "2015-11-06T15:46:29Z",
"method": "login",
"editcount": 100,
"registration": "2015-11-06T15:46:29Z",
"groups": ["extendedconfirmed"],
}
]
FAKE_MERGED_ACCOUNTS_BLOCKED = [
{
"wiki": "enwiki",
"url": "https://en.wikipedia.org",
"timestamp": "2015-11-06T15:46:29Z",
"method": "login",
"editcount": 100,
"registration": "2015-11-06T15:46:29Z",
"groups": ["extendedconfirmed"],
"blocked": {"expiry": "infinity", "reason": "bad editor!"},
}
]
FAKE_GLOBAL_USERINFO = {
"home": "enwiki",
"id": 567823,
"registration": "2015-11-06T15:46:29Z", # Well before first commit.
"name": "alice",
"editcount": 5000,
"merged": copy.copy(FAKE_MERGED_ACCOUNTS),
}
# CSRF middleware is helpful for site security, but not helpful for testing
# the rendered output of a page.
def remove_csrfmiddlewaretoken(rendered_html):
csrfmiddlewaretoken_pattern = (
r"<input type=\"hidden\" name=\"csrfmiddlewaretoken\" value=\".+\">"
)
return re.sub(csrfmiddlewaretoken_pattern, "", rendered_html)
class ViewsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.client = Client()
# User 1: regular Editor
cls.username1 = "alice"
cls.user_editor = UserFactory(username=cls.username1)
cls.editor1 = EditorFactory(user=cls.user_editor)
cls.editor1.wp_bundle_eligible = True
cls.editor1.save()
cls.url1 = reverse("users:editor_detail", kwargs={"pk": cls.editor1.pk})
# User 2: regular Editor
cls.username2 = "bob"
cls.user_editor2 = UserFactory(username=cls.username2)
cls.editor2 = EditorFactory(user=cls.user_editor2)
cls.url2 = reverse("users:editor_detail", kwargs={"pk": cls.editor2.pk})
# User 3: Site administrator
cls.username3 = "carol"
cls.user_superuser = UserFactory(username=cls.username3)
cls.user_superuser.is_superuser = True
cls.user_superuser.save()
cls.editor3 = EditorFactory(user=cls.user_superuser)
# User 4: Coordinator
cls.username4 = "eve"
cls.user_coordinator = UserFactory(username=cls.username4)
cls.editor4 = EditorFactory(user=cls.user_coordinator)
get_coordinators().user_set.add(cls.user_coordinator)
# We should mock out any call to messages call in the view, since
# RequestFactory (unlike Client) doesn't run middleware. If you
# actually want to test that messages are displayed, use Client(),
# and stop/restart the patcher.
cls.message_patcher = patch("TWLight.applications.views.messages.add_message")
cls.message_patcher.start()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
cls.user_editor.delete()
cls.editor1.delete()
cls.user_editor2.delete()
cls.editor2.delete()
cls.user_superuser.delete()
cls.editor3.delete()
cls.user_coordinator.delete()
cls.editor4.delete()
cls.message_patcher.stop()
def test_editor_detail_url_resolves(self):
"""
The EditorDetailView resolves.
"""
_ = resolve(self.url1)
def test_anon_user_cannot_see_editor_details(self):
"""
If an AnonymousUser hits an editor page, they are redirected to login.
"""
response = self.client.get(self.url1)
self.assertEqual(response.status_code, 302)
self.assertEqual(urlparse(response.url).path, settings.LOGIN_URL)
def test_editor_can_see_own_page(self):
"""Check that editors can see their own pages."""
factory = RequestFactory()
request = factory.get(self.url1)
request.user = self.user_editor
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
self.assertEqual(response.status_code, 200)
def test_user_view_no_coordinators(self):
"""Check that users with no coordinators can see their own pages."""
get_coordinators().user_set.remove(self.user_coordinator)
factory = RequestFactory()
request = factory.get(self.url1)
request.user = self.user_editor
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
self.assertEqual(response.status_code, 200)
def test_editor_cannot_see_other_editor_page(self):
"""Editors cannot see other editors' pages."""
factory = RequestFactory()
request = factory.get(self.url2)
request.user = self.user_editor
# Make sure the editor is not a coordinator, because coordinators *can*
# see others' pages!
coordinators = get_coordinators()
try:
assert self.user_editor not in coordinators.user_set.all()
except AssertionError:
coordinators.user_set.remove(self.user_editor)
with self.assertRaises(PermissionDenied):
_ = views.EditorDetailView.as_view()(request, pk=self.editor2.pk)
def test_coordinator_access(self):
"""Coordinators can see someone else's page."""
factory = RequestFactory()
request = factory.get(self.url1)
request.user = self.user_coordinator
# Define a partner
partner = PartnerFactory()
# Editor applies to the partner
app = ApplicationFactory(
status=Application.PENDING, editor=self.editor1, partner=partner
)
app.save()
# Editor details should not be visible to just any coordinator
try:
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
self.fail("Editor details should not be visible to just any coordinator.")
except PermissionDenied:
pass
# Designate the coordinator
partner.coordinator = request.user
partner.save()
# Editor details should be visible to the designated coordinator
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
self.assertEqual(response.status_code, 200)
def test_site_admin_can_see_other_editor_page(self):
"""Site admins can see someone else's page."""
factory = RequestFactory()
request = factory.get(self.url1)
request.user = self.user_superuser
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
self.assertEqual(response.status_code, 200)
def test_editor_page_has_editor_data(self):
"""Expected editor personal data is in their page."""
factory = RequestFactory()
request = factory.get(self.url1)
request.user = self.user_editor
response = views.EditorDetailView.as_view()(request, pk=self.editor1.pk)
content = response.render().content.decode("utf-8")
# This uses default data from EditorFactory, except for the username,
# which is randomly generated (hence has no default).
self.assertIn(self.editor1.wp_username, content)
self.assertIn("42", content)
self.assertIn("Cat floofing, telemetry, fermentation", content)
def test_my_applications_page_has_application_history(self):
"""Expected editor application oauth_data is in their page."""
app1 = ApplicationFactory(
status=Application.PENDING, editor=self.user_editor.editor
)
app2 = ApplicationFactory(
status=Application.QUESTION, editor=self.user_editor.editor
)
app3 = ApplicationFactory(
status=Application.APPROVED, editor=self.user_editor.editor
)
app4 = ApplicationFactory(
status=Application.NOT_APPROVED, editor=self.user_editor.editor
)
# Bundle applications shouldn't be listed on this page
app5 = ApplicationFactory(
status=Application.APPROVED,
partner=PartnerFactory(authorization_method=Partner.BUNDLE),
editor=self.user_editor.editor,
)
app6 = ApplicationFactory(
status=Application.PENDING,
partner=PartnerFactory(authorization_method=Partner.BUNDLE),
editor=self.user_editor.editor,
)
app7 = ApplicationFactory(
status=Application.INVALID,
partner=PartnerFactory(authorization_method=Partner.BUNDLE),
editor=self.user_editor.editor,
)
factory = RequestFactory()
request = factory.get(
reverse("users:my_applications", kwargs={"pk": self.editor1.pk})
)
request.user = self.user_editor
response = views.ListApplicationsUserView.as_view()(request, pk=self.editor1.pk)
self.assertEqual(
set(response.context_data["object_list"]), {app1, app2, app3, app4}
)
content = response.render().content.decode("utf-8")
self.assertIn(escape(app1.partner.company_name), content)
self.assertIn(escape(app2.partner.company_name), content)
self.assertIn(escape(app3.partner.company_name), content)
self.assertIn(escape(app4.partner.company_name), content)
# No Bundle applications
self.assertNotIn(escape(app5.partner.company_name), content)
self.assertNotIn(escape(app6.partner.company_name), content)
self.assertNotIn(escape(app7.partner.company_name), content)
# We can't use assertTemplateUsed with RequestFactory (only with
# Client), and testing that the rendered content is equal to an
# expected string is too fragile.
def test_withdraw_application(self):
app = ApplicationFactory(
status=Application.PENDING,
partner=PartnerFactory(authorization_method=Partner.BUNDLE),
editor=self.user_editor.editor,
)
factory = RequestFactory()
request = factory.get(
reverse("users:withdraw", kwargs={"pk": self.editor1.pk, "id": app.pk})
)
request.user = self.user_editor
response = views.WithdrawApplication.as_view()(
request, pk=self.editor1.pk, id=app.pk
)
app.refresh_from_db()
# withdrawing application should set date closed
self.assertNotEqual(app.date_closed, None)
self.assertEqual(app.status, Application.INVALID)
def test_sent_application(self):
app = ApplicationFactory(
status=Application.SENT,
partner=PartnerFactory(authorization_method=Partner.BUNDLE),
editor=self.user_editor.editor,
sent_by=self.user_coordinator,
)
factory = RequestFactory()
request = factory.get(
reverse("users:my_applications", kwargs={"pk": self.editor1.pk})
)
request.user = self.user_editor
response = views.ListApplicationsUserView.as_view()(
request,
pk=self.editor1.pk,
)
app.refresh_from_db()
self.assertNotIn("Withdraw", response.render().content.decode("utf-8"))
def test_return_authorization(self):
# Simulate a valid user trying to return their access
editor = EditorCraftRoom(self, Terms=True, Coordinator=False)
partner = PartnerFactory(authorization_method=Partner.PROXY)
app = ApplicationFactory(
status=Application.SENT,
editor=editor,
partner=partner,
sent_by=self.user_coordinator,
)
authorization = Authorization.objects.get(user=editor.user, partners=partner)
self.assertEqual(authorization.get_latest_app(), app)
return_url = reverse(
"users:return_authorization", kwargs={"pk": authorization.pk}
)
response = self.client.get(return_url, follow=True)
return_form = response.context["form"]
self.client.post(return_url, return_form.initial)
yesterday = datetime.now().date() - timedelta(days=1)
authorization.refresh_from_db()
self.assertEqual(authorization.date_expires, yesterday)
# Simulate an invalid user trying to return access of some other user
someday = yesterday + timedelta(days=30)
authorization.date_expires = someday
authorization.save()
EditorCraftRoom(self, Terms=True, Coordinator=False)
return_url = reverse(
"users:return_authorization", kwargs={"pk": authorization.pk}
)
response = self.client.get(return_url, follow=True)
self.assertEqual(response.status_code, 403)
response = self.client.post(return_url, return_form.initial)
self.assertEqual(response.status_code, 403)
authorization.refresh_from_db()
self.assertEqual(authorization.date_expires, someday)
def test_latest_application(self):
# Create an editor with a session.
editor = EditorCraftRoom(self, Terms=True, Coordinator=False)
partner = PartnerFactory(authorization_method=Partner.PROXY)
app = ApplicationFactory(
status=Application.SENT,
editor=editor,
partner=partner,
sent_by=self.user_coordinator,
)
authorization = Authorization.objects.get(user=editor.user, partners=partner)
self.assertEqual(authorization.get_latest_app(), app)
# Simulate a valid user trying to return their access
return_url = reverse(
"users:return_authorization", kwargs={"pk": authorization.pk}
)
response = self.client.get(return_url, follow=True)
return_form = response.context["form"]
self.client.post(return_url, return_form.initial)
yesterday = datetime.now().date() - timedelta(days=1)
authorization.refresh_from_db()
self.assertEqual(authorization.date_expires, yesterday)
# Create a new application to the same partner (in reality this
# is most likely to be a renewal)
app_renewal = ApplicationFactory(
status=Application.SENT,
editor=editor,
partner=partner,
sent_by=self.user_coordinator,
)
app_renewal.save()
# return access
authorization.refresh_from_db()
return_url = reverse(
"users:return_authorization", kwargs={"pk": authorization.pk}
)
response = self.client.get(return_url, follow=True)
return_form = response.context["form"]
self.client.post(return_url, return_form.initial)
yesterday = datetime.now().date() - timedelta(days=1)
authorization.refresh_from_db()
self.assertEqual(authorization.date_expires, yesterday)
# Renew again, but deny this time.
app_renewal2 = ApplicationFactory(editor=editor, partner=partner)
app_renewal2.status = Application.NOT_APPROVED
app_renewal2.save()
authorization.refresh_from_db()
self.assertEqual(authorization.get_latest_app(), app_renewal)
self.assertEqual(authorization.get_latest_sent_app(), app_renewal)
def test_user_home_view_anon(self):
"""
If an AnonymousUser hits UserHomeView, they are redirected to login.
"""
factory = RequestFactory()
request = factory.get(reverse("users:home"))
request.user = AnonymousUser()
response = views.UserHomeView.as_view()(request)
self.assertEqual(response.status_code, 302)
self.assertEqual(urlparse(response.url).path, settings.LOGIN_URL)
def test_user_home_view_is_editor(self):
"""
If a User who is an editor hits UserHomeView, they see EditorDetailView.
TODO: Change this test's assertions (they might break when the csrf
token is rendered differently)
"""
user = UserFactory()
editor = EditorFactory(user=user)
factory = RequestFactory()
home_request = factory.get(reverse("users:home"))
home_request.user = user
home_response = views.UserHomeView.as_view()(home_request)
detail_request = factory.get(
reverse("users:editor_detail", kwargs={"pk": editor.pk})
)
detail_request.user = user
detail_response = views.EditorDetailView.as_view()(detail_request, pk=editor.pk)
# We can't actually check that EditorDetailView was used by UserHomeView
# directly, because its as_view function has already been processed
# and all we have access to is a return value. So let's check that the
# output of the two pages is the same - the user would have seen the
# same thing on either page.
self.assertEqual(home_response.status_code, 200)
expected_detail_view = remove_csrfmiddlewaretoken(
detail_response.rendered_content
)
home_view = remove_csrfmiddlewaretoken(home_response.rendered_content)
self.assertEqual(expected_detail_view, home_view)
@patch("TWLight.users.views.UserDetailView.as_view")
def test_user_home_view_non_editor(self, mock_view):
"""
A User who isn't an editor hitting UserHomeView sees UserDetailView.
"""
user = UserFactory(username="not_an_editor")
self.assertFalse(hasattr(user, "editor"))
factory = RequestFactory()
request = factory.get(reverse("users:home"))
request.user = user
_ = views.UserHomeView.as_view()(request)
# For this we can't even check that the rendered content is the same,
# because we don't have a URL allowing us to render UserDetailView
# correctly; we'll mock out its as_view function and make sure it got
# called.
mock_view.assert_called_once_with()
def test_coordinator_restricted(self):
# If a coordinator restricts their data processing
# they should stop being a coordinator.
restrict_url = reverse("users:restrict_data")
coordinators = get_coordinators()
restricted = get_restricted()
# Double check that the coordinator still has the relevant group
assert self.user_coordinator in coordinators.user_set.all()
# Need a password so we can login
self.user_coordinator.set_password("editor")
self.user_coordinator.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username4, password="editor")
restrict = self.client.get(restrict_url, follow=True)
restrict_form = restrict.context["form"]
data = restrict_form.initial
data["restricted"] = True
data["submit"] = True
agree = self.client.post(restrict_url, data)
assert self.user_coordinator not in coordinators.user_set.all()
assert self.user_coordinator in restricted.user_set.all()
def test_user_delete(self):
"""
Verify that deleted users have no user object.
"""
delete_url = reverse("users:delete_data", kwargs={"pk": self.user_editor.pk})
# Need a password so we can login
self.user_editor.set_password("editor")
self.user_editor.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username1, password="editor")
submit = self.client.post(delete_url)
assert not User.objects.filter(username=self.username1).exists()
# Check that the associated Editor also got deleted.
assert not Editor.objects.filter(user=self.user_editor).exists()
def test_user_delete_authorizations(self):
"""
Verify that deleted user authorizations are expired and contain no user links
"""
delete_url = reverse("users:delete_data", kwargs={"pk": self.user_editor.pk})
# Need a password so we can login
self.user_editor.set_password("editor")
self.user_editor.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username1, password="editor")
partner = PartnerFactory()
user_auth = Authorization(
user=self.user_editor,
authorizer=self.user_coordinator,
date_authorized=date.today(),
date_expires=date.today() + timedelta(days=30),
)
user_auth.save()
user_auth.partners.add(partner)
submit = self.client.post(delete_url)
user_auth.refresh_from_db()
self.assertEqual(user_auth.date_expires, date.today() - timedelta(days=1))
def test_user_delete_bundle_authorizations(self):
"""
Verify that deleted user authorizations are expired and contain no user links
"""
delete_url = reverse("users:delete_data", kwargs={"pk": self.user_editor.pk})
# Need a password so we can login
self.editor1.user.set_password("editor")
self.editor1.user.save()
bundle_partner_1 = PartnerFactory(authorization_method=Partner.BUNDLE)
bundle_partner_2 = PartnerFactory(authorization_method=Partner.BUNDLE)
self.client = Client()
session = self.client.session
self.client.login(username=self.username1, password="editor")
# Bundle authorization should be created
self.editor1.update_bundle_authorization()
self.editor1.refresh_from_db()
bundle_auth = self.editor1.get_bundle_authorization
self.assertTrue(bundle_auth.is_bundle)
# Saving the bundle authorization id so we can query it after to make
# sure it's been deleted
bundle_auth_id = bundle_auth.pk
submit = self.client.post(delete_url)
editor_count = Editor.objects.filter(pk=self.editor1.pk).count()
self.assertEqual(editor_count, 0)
bundle_auth_count = Authorization.objects.filter(pk=bundle_auth_id).count()
self.assertEqual(bundle_auth_count, 0)
def test_user_data_download(self):
"""
Verify that if users try to download their personal data they
are actually sent a file.
"""
# Need a password so we can login
self.user_editor2.set_password("editor")
self.user_editor2.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username2, password="editor")
response = self.client.post(self.url2, {"download": "Download"})
self.assertEqual(
response.get("Content-Disposition"), "attachment; filename=user_data.json"
)
def test_terms_of_use_on_editor_detail_page_show(self):
"""Editor who agreed term of use, can see checkbox to disagree"""
user_agreed_TOU = UserFactory()
user_agreed_TOU.userprofile.terms_of_use = True
editor_agreed_TOU = EditorFactory(user=user_agreed_TOU)
factory = RequestFactory()
detail_request = factory.get(
reverse("users:editor_detail", kwargs={"pk": editor_agreed_TOU.pk})
)
detail_request.user = user_agreed_TOU
response = views.EditorDetailView.as_view()(
detail_request, pk=editor_agreed_TOU.pk
)
content = response.render().content.decode("utf-8")
self.assertIn("By unchecking this box and clicking “Update", content)
def test_terms_of_use_on_editor_detail_page_not_show(self):
"""Editor who hasn't agreed term of use, won't see checkbox to disagree"""
user_not_agreed_TOU = UserFactory()
user_not_agreed_TOU.userprofile.terms_of_use = False
editor_not_agreed_TOU = EditorFactory(user=user_not_agreed_TOU)
factory = RequestFactory()
detail_request = factory.get(
reverse("users:editor_detail", kwargs={"pk": editor_not_agreed_TOU.pk})
)
detail_request.user = user_not_agreed_TOU
response = views.EditorDetailView.as_view()(
detail_request, pk=editor_not_agreed_TOU.pk
)
content = response.render().content.decode("utf-8")
self.assertNotIn("By unchecking this box and clicking “Update", content)
def test_user_email_form(self):
"""
Users have a form available on their user pages which enables them to
control which emails they receive. Verify that they can post this form
without error.
"""
# Need a password so we can login
self.user_editor2.set_password("editor")
self.user_editor2.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username2, password="editor")
response = self.client.post(self.url2, {"update_email_settings": ["Update"]})
# Should be successfully redirected back to the user page.
self.assertEqual(response.status_code, 302)
def test_user_email_preferences_disable_update(self):
"""
Verify that users can disable renewal notices and coordinator reminder
emails in the email form.
"""
# Need a password so we can login
self.user_editor2.set_password("editor")
self.user_editor2.save()
# Only coordinators get to change their reminder preferences
get_coordinators().user_set.add(self.user_editor2)
self.client = Client()
session = self.client.session
self.client.login(username=self.username2, password="editor")
response = self.client.post(self.url2, {"update_email_settings": ["Update"]})
# Should be successfully redirected back to the user page.
self.assertEqual(response.status_code, 302)
self.user_editor2.userprofile.refresh_from_db()
# We didn't send send_renewal_notices or send_pending_application_reminders
# or send_discussion_application_reminders or send_approved_application_reminders
# in POST to simulate an unchecked box.
self.assertEqual(self.user_editor2.userprofile.send_renewal_notices, False)
self.assertEqual(self.user_editor2.userprofile.pending_app_reminders, False)
self.assertEqual(self.user_editor2.userprofile.discussion_app_reminders, False)
self.assertEqual(self.user_editor2.userprofile.approved_app_reminders, False)
def test_user_email_preferences_enable_update(self):
"""
Verify that users can email renewal notices and coordinator reminder
emails in the email form.
"""
# Need a password so we can login
self.user_editor2.set_password("editor")
self.user_editor2.userprofile.send_renewal_notices = False
self.user_editor2.userprofile.pending_app_reminders = False
self.user_editor2.userprofile.discussion_app_reminders = False
self.user_editor2.userprofile.approved_app_reminders = False
self.user_editor2.save()
# Only coordinators get to change their reminder preferences
get_coordinators().user_set.add(self.user_editor2)
self.client = Client()
session = self.client.session
self.client.login(username=self.username2, password="editor")
response = self.client.post(
self.url2,
{
"update_email_settings": ["Update"],
"send_renewal_notices": ["on"],
"send_pending_application_reminders": ["on"],
"send_discussion_application_reminders": ["on"],
"send_approved_application_reminders": ["on"],
},
)
# Should be successfully redirected back to the user page.
self.assertEqual(response.status_code, 302)
self.user_editor2.userprofile.refresh_from_db()
self.assertEqual(self.user_editor2.userprofile.send_renewal_notices, True)
self.assertEqual(self.user_editor2.userprofile.pending_app_reminders, True)
self.assertEqual(self.user_editor2.userprofile.discussion_app_reminders, True)
self.assertEqual(self.user_editor2.userprofile.approved_app_reminders, True)
def test_user_email_preferences_update_non_coordinator(self):
# Need a password so we can login
self.user_editor2.set_password("editor")
self.user_editor2.userprofile.send_renewal_notices = False
self.user_editor2.save()
self.client = Client()
session = self.client.session
self.client.login(username=self.username2, password="editor")
response = self.client.post(
self.url2,
{"update_email_settings": ["Update"], "send_renewal_notices": ["on"]},
)
# Should be successfully redirected back to the user page.
self.assertEqual(response.status_code, 302)
self.user_editor2.userprofile.refresh_from_db()
self.assertEqual(self.user_editor2.userprofile.send_renewal_notices, True)
# Only coordinators get to change their reminder preferences
self.assertEqual(self.user_editor2.userprofile.pending_app_reminders, True)
self.assertEqual(self.user_editor2.userprofile.discussion_app_reminders, True)
self.assertEqual(self.user_editor2.userprofile.approved_app_reminders, True)
class UserProfileModelTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.bundle_partner_1 = PartnerFactory(authorization_method=Partner.BUNDLE)
cls.bundle_partner_2 = PartnerFactory(authorization_method=Partner.BUNDLE)
cls.proxy_partner_1 = PartnerFactory(authorization_method=Partner.PROXY)
cls.user_coordinator = UserFactory(username="Jon Snow")
cls.editor = EditorFactory()
cls.editor.wp_bundle_eligible = True
cls.editor.save()
get_coordinators().user_set.add(cls.user_coordinator)
def test_user_profile_created(self):
"""
UserProfile should be created on user creation.
"""
user = UserFactory()
# If the signal has not created a UserProfile, this line will throw
# a DoesNotExist and the test will fail, which is what we want.
UserProfile.objects.get(user=user)
user.delete()
def test_user_profile_sets_tou_to_false(self):
# Don't use UserFactory, since it forces the related profile to have
# agreed to the terms for simplicity in most tests! Use the user
# creation function that we actually use in production.
user = User.objects.create_user(
username="profiler", email="profiler@example.com"
)
profile = UserProfile.objects.get(user=user)
self.assertEqual(profile.terms_of_use, False)
user.delete()
def test_user_profile_sets_use_wp_email_to_true(self):
"""
Verify that UserProfile.use_wp_email defaults to True.
(Editor.update_from_wikipedia assumes this to be the case.)
"""
user = User.objects.create_user(
username="profiler", email="profiler@example.com"
)
profile = UserProfile.objects.get(user=user)
self.assertEqual(profile.use_wp_email, True)
user.delete()
def test_add_favorite_collection_valid(self):
"""
Tests that a valid collection (one a user has access to) is successfully
added to the favorites
"""
profile = UserProfile.objects.get(user=self.editor.user)
# Create an authorization object so that the partner can be added to a
# user's favorites collection
app_bundle_partner_1 = ApplicationFactory(
status=Application.SENT,
editor=self.editor,
partner=self.bundle_partner_1,
sent_by=self.user_coordinator,
)
app_bundle_partner_2 = ApplicationFactory(
status=Application.SENT,
editor=self.editor,
partner=self.bundle_partner_2,
sent_by=self.user_coordinator,
)
app_proxy_partner_1 = ApplicationFactory(
status=Application.SENT,
editor=self.editor,
partner=self.proxy_partner_1,
sent_by=self.user_coordinator,
)
profile.favorites.add(self.bundle_partner_1)
profile.favorites.add(self.bundle_partner_2)
profile.favorites.add(self.proxy_partner_1)
self.assertIn(self.proxy_partner_1, profile.favorites.all())
self.assertIn(self.bundle_partner_1, profile.favorites.all())
self.assertIn(self.bundle_partner_2, profile.favorites.all())
def test_add_favorite_expired_collection_valid(self):
"""
Tests that a valid collection (one a user has access to, even if it has
expired) is successfully added to the favorites
"""
profile = UserProfile.objects.get(user=self.editor.user)
app_proxy_partner_1 = ApplicationFactory(
status=Application.SENT,
editor=self.editor,
partner=self.proxy_partner_1,
sent_by=self.user_coordinator,
)
someday = date.today() - timedelta(days=60)
authorization = Authorization.objects.get(
user=self.editor.user, partners=self.proxy_partner_1
)
authorization.date_expires = someday
authorization.save()
profile.favorites.add(self.proxy_partner_1)
self.assertIn(self.proxy_partner_1, profile.favorites.all())
def test_add_favorite_collection_invalid(self):
"""
Tests that an invalid collection (one a user does not has access to) is not
added to the favorites and that a ValidationError is raised
"""
profile = UserProfile.objects.get(user=self.editor.user)
with self.assertRaises(ValidationError):
profile.favorites.add(self.proxy_partner_1)
class EditorModelTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
for editor in Editor.objects.all():
# The test case succeeds when runs alone but fails when run
# as part of the whole suite, because it grabs the wrong editor
# object from the db. Kill them all with fire.
# (Why does it do this? Because our queries look for editors by
# username or wikipedia sub, not by foreign key - we have to use the
# information that we have from the wikipedia API, which knows
# nothing about our database. But the test runner doesn't actually
# *delete* database objects between runs, for performance reasons;
# it simply truncates them by nulling out their foreign keys.
# This means that if you are searching for db objects by properties
# other than foreign key, you *still find them*.)
editor.delete()
# Wiki 'zh-classical' is 'zh-classical.wikipedia.org'. It's also the
# longest wiki name in wiki_list.
cls.editor = EditorFactory(
wp_username="editor_model_test",
wp_rights=json.dumps(["cat floofing", "the big red button"]),
wp_groups=json.dumps(["sysops", "bureaucrats"]),
wp_registered=None,
)
cls.editor.user.userprofile.terms_of_use = True
cls.editor.user.userprofile.save()
cls.editor.user.save()
cls.editor.save()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
cls.editor.delete()
def test_encoder_works_with_special_character_username(self):
test = Editor().encode_wp_username("editor model&test")
self.assertEqual(test, "editor%20model%26test")
def test_wp_user_page_url(self):
expected_url = settings.TWLIGHT_OAUTH_PROVIDER_URL + "/User:editor_model_test"
self.assertEqual(expected_url, self.editor.wp_user_page_url)
def test_wp_link_central_auth(self):
expected_url = "https://meta.wikimedia.org/w/index.php?title=Special%3ACentralAuth&target=editor_model_test"
self.assertEqual(expected_url, self.editor.wp_link_central_auth)
def test_get_wp_rights_display(self):
expected_text = ["cat floofing", "the big red button"]
self.assertEqual(expected_text, self.editor.get_wp_rights_display)
def test_get_wp_groups_display(self):
expected_text = ["sysops", "bureaucrats"]
self.assertEqual(expected_text, self.editor.get_wp_groups_display)
def test_is_user_valid(self):
"""
Users must:
* Have >= 500 edits
* Be active for >= 6 months
* Have Special:Email User enabled
* Not be blocked on any projects
"""
identity = copy.copy(FAKE_IDENTITY)