-
-
Notifications
You must be signed in to change notification settings - Fork 7.9k
/
test_event_system.py
1421 lines (1231 loc) · 53.7 KB
/
test_event_system.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 time
from typing import Any, Callable, Dict, List, Optional
from unittest import mock
from urllib.parse import urlsplit
import orjson
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.test import override_settings
from django.utils.timezone import now as timezone_now
from typing_extensions import override
from version import API_FEATURE_LEVEL, ZULIP_MERGE_BASE, ZULIP_VERSION
from zerver.actions.custom_profile_fields import try_update_realm_custom_profile_field
from zerver.actions.message_send import check_send_message
from zerver.actions.presence import do_update_user_presence
from zerver.actions.user_settings import do_change_user_setting
from zerver.actions.users import do_change_user_role
from zerver.lib.event_schema import check_restart_event
from zerver.lib.events import fetch_initial_state_data
from zerver.lib.exceptions import AccessDeniedError
from zerver.lib.request import RequestVariableMissingError
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import (
HostRequestMock,
dummy_handler,
reset_email_visibility_to_everyone_in_zulip_realm,
stub_event_queue_user_events,
)
from zerver.lib.users import get_api_key, get_users_for_api
from zerver.models import CustomProfileField, UserMessage, UserPresence, UserProfile
from zerver.models.clients import get_client
from zerver.models.realms import get_realm
from zerver.models.streams import get_stream
from zerver.models.users import get_system_bot
from zerver.tornado.event_queue import (
allocate_client_descriptor,
clear_client_event_queues_for_testing,
get_client_info_for_message_event,
process_message_event,
send_restart_events,
)
from zerver.tornado.exceptions import BadEventQueueIdError
from zerver.tornado.views import get_events, get_events_backend
from zerver.views.events_register import (
_default_all_public_streams,
_default_narrow,
events_register_backend,
)
class EventsEndpointTest(ZulipTestCase):
def test_events_register_without_user_agent(self) -> None:
result = self.client_post("/json/register", skip_user_agent=True)
self.assert_json_success(result)
def test_narrows(self) -> None:
user = self.example_user("hamlet")
with mock.patch("zerver.lib.events.request_event_queue", return_value=None) as m:
munge = lambda obj: orjson.dumps(obj).decode()
narrow = [["stream", "devel"], ["is", "mentioned"]]
payload = dict(narrow=munge(narrow))
result = self.api_post(user, "/api/v1/register", payload)
# We want the test to abort before actually fetching data.
self.assert_json_error(result, "Could not allocate event queue")
self.assertEqual(m.call_args.kwargs["narrow"], [["stream", "devel"], ["is", "mentioned"]])
def test_events_register_endpoint(self) -> None:
# This test is intended to get minimal coverage on the
# events_register code paths
user = self.example_user("hamlet")
with mock.patch("zerver.views.events_register.do_events_register", return_value={}):
result = self.api_post(user, "/api/v1/register")
self.assert_json_success(result)
with mock.patch("zerver.lib.events.request_event_queue", return_value=None):
result = self.api_post(user, "/api/v1/register")
self.assert_json_error(result, "Could not allocate event queue")
return_event_queue = "15:11"
return_user_events: List[Dict[str, Any]] = []
# We choose realm_emoji somewhat randomly--we want
# a "boring" event type for the purpose of this test.
event_type = "realm_emoji"
empty_realm_emoji_dict: Dict[str, Any] = {}
test_event = dict(id=6, type=event_type, realm_emoji=empty_realm_emoji_dict)
# Test that call is made to deal with a returning soft deactivated user.
with mock.patch("zerver.lib.events.reactivate_user_if_soft_deactivated") as fa:
with stub_event_queue_user_events(return_event_queue, return_user_events):
result = self.api_post(
user, "/api/v1/register", dict(event_types=orjson.dumps([event_type]).decode())
)
self.assertEqual(fa.call_count, 1)
with stub_event_queue_user_events(return_event_queue, return_user_events):
result = self.api_post(
user, "/api/v1/register", dict(event_types=orjson.dumps([event_type]).decode())
)
result_dict = self.assert_json_success(result)
self.assertEqual(result_dict["last_event_id"], -1)
self.assertEqual(result_dict["queue_id"], "15:11")
# Now start simulating returning actual data
return_event_queue = "15:12"
return_user_events = [test_event]
with stub_event_queue_user_events(return_event_queue, return_user_events):
result = self.api_post(
user, "/api/v1/register", dict(event_types=orjson.dumps([event_type]).decode())
)
result_dict = self.assert_json_success(result)
self.assertEqual(result_dict["last_event_id"], 6)
self.assertEqual(result_dict["queue_id"], "15:12")
# sanity check the data relevant to our event
self.assertEqual(result_dict["realm_emoji"], {})
# Now test with `fetch_event_types` not matching the event
return_event_queue = "15:13"
with stub_event_queue_user_events(return_event_queue, return_user_events):
result = self.api_post(
user,
"/api/v1/register",
dict(
event_types=orjson.dumps([event_type]).decode(),
fetch_event_types=orjson.dumps(["message"]).decode(),
),
)
result_dict = self.assert_json_success(result)
self.assertEqual(result_dict["last_event_id"], 6)
# Check that the message event types data is in there
self.assertIn("max_message_id", result_dict)
# Check that our original event type is not there.
self.assertNotIn(event_type, result_dict)
self.assertEqual(result_dict["queue_id"], "15:13")
# Now test with `fetch_event_types` matching the event
with stub_event_queue_user_events(return_event_queue, return_user_events):
result = self.api_post(
user,
"/api/v1/register",
dict(
fetch_event_types=orjson.dumps([event_type]).decode(),
event_types=orjson.dumps(["message"]).decode(),
),
)
result_dict = self.assert_json_success(result)
self.assertEqual(result_dict["last_event_id"], 6)
# Check that we didn't fetch the messages data
self.assertNotIn("max_message_id", result_dict)
# Check that the realm_emoji data is in there.
self.assertIn("realm_emoji", result_dict)
self.assertEqual(result_dict["realm_emoji"], {})
self.assertEqual(result_dict["queue_id"], "15:13")
def test_events_register_spectators(self) -> None:
# Verify that POST /register works for spectators, but not for
# normal users.
with self.settings(WEB_PUBLIC_STREAMS_ENABLED=False):
result = self.client_post("/json/register")
self.assert_json_error(
result,
"Not logged in: API authentication or user session required",
status_code=401,
)
result = self.client_post("/json/register")
result_dict = self.assert_json_success(result)
self.assertEqual(result_dict["queue_id"], None)
self.assertEqual(result_dict["realm_uri"], "http://zulip.testserver")
result = self.client_post("/json/register")
self.assertEqual(result.status_code, 200)
result = self.client_post("/json/register", dict(client_gravatar="false"))
self.assertEqual(result.status_code, 200)
result = self.client_post("/json/register", dict(client_gravatar="true"))
self.assert_json_error(
result,
"Invalid 'client_gravatar' parameter for anonymous request",
status_code=400,
)
result = self.client_post("/json/register", dict(include_subscribers="true"))
self.assert_json_error(
result,
"Invalid 'include_subscribers' parameter for anonymous request",
status_code=400,
)
def test_events_register_endpoint_all_public_streams_access(self) -> None:
guest_user = self.example_user("polonius")
normal_user = self.example_user("hamlet")
self.assertEqual(guest_user.role, UserProfile.ROLE_GUEST)
self.assertEqual(normal_user.role, UserProfile.ROLE_MEMBER)
with mock.patch("zerver.views.events_register.do_events_register", return_value={}):
result = self.api_post(normal_user, "/api/v1/register", dict(all_public_streams="true"))
self.assert_json_success(result)
with mock.patch("zerver.views.events_register.do_events_register", return_value={}):
result = self.api_post(guest_user, "/api/v1/register", dict(all_public_streams="true"))
self.assert_json_error(result, "User not authorized for this query")
def test_events_get_events_endpoint_guest_cant_use_all_public_streams_param(self) -> None:
"""
This test is meant to execute the very beginning of the codepath
to ensure guest users are immediately disallowed to use the
all_public_streams param. Deeper testing is hard (and not necessary for this case)
due to the codepath expecting AsyncDjangoHandler to be attached to the request,
which doesn't happen in our test setup.
"""
guest_user = self.example_user("polonius")
self.assertEqual(guest_user.role, UserProfile.ROLE_GUEST)
result = self.api_get(guest_user, "/api/v1/events", dict(all_public_streams="true"))
self.assert_json_error(result, "User not authorized for this query")
def test_tornado_endpoint(self) -> None:
# This test is mostly intended to get minimal coverage on
# the /notify_tornado endpoint, so we can have 100% URL coverage,
# but it does exercise a little bit of the codepath.
post_data = dict(
data=orjson.dumps(
dict(
event=dict(
type="other",
),
users=[self.example_user("hamlet").id],
),
).decode(),
)
req = HostRequestMock(post_data)
req.META["REMOTE_ADDR"] = "127.0.0.1"
with self.assertRaises(RequestVariableMissingError) as context:
result = self.client_post_request("/notify_tornado", req)
self.assertEqual(str(context.exception), "Missing 'secret' argument")
self.assertEqual(context.exception.http_status_code, 400)
post_data["secret"] = "random"
req = HostRequestMock(post_data, user_profile=None)
req.META["REMOTE_ADDR"] = "127.0.0.1"
with self.assertRaises(AccessDeniedError) as access_denied_error:
result = self.client_post_request("/notify_tornado", req)
self.assertEqual(str(access_denied_error.exception), "Access denied")
self.assertEqual(access_denied_error.exception.http_status_code, 403)
post_data["secret"] = settings.SHARED_SECRET
req = HostRequestMock(post_data, tornado_handler=dummy_handler)
req.META["REMOTE_ADDR"] = "127.0.0.1"
result = self.client_post_request("/notify_tornado", req)
self.assert_json_success(result)
post_data = dict(secret=settings.SHARED_SECRET)
req = HostRequestMock(post_data, tornado_handler=dummy_handler)
req.META["REMOTE_ADDR"] = "127.0.0.1"
with self.assertRaises(RequestVariableMissingError) as context:
result = self.client_post_request("/notify_tornado", req)
self.assertEqual(str(context.exception), "Missing 'data' argument")
self.assertEqual(context.exception.http_status_code, 400)
class GetEventsTest(ZulipTestCase):
def tornado_call(
self,
view_func: Callable[[HttpRequest, UserProfile], HttpResponse],
user_profile: UserProfile,
post_data: Dict[str, Any],
) -> HttpResponse:
request = HostRequestMock(post_data, user_profile, tornado_handler=dummy_handler)
return view_func(request, user_profile)
def test_get_events(self) -> None:
user_profile = self.example_user("hamlet")
email = user_profile.email
recipient_user_profile = self.example_user("othello")
recipient_email = recipient_user_profile.email
self.login_user(user_profile)
result = self.tornado_call(
get_events,
user_profile,
{
"apply_markdown": orjson.dumps(True).decode(),
"client_gravatar": orjson.dumps(True).decode(),
"event_types": orjson.dumps(["message"]).decode(),
"user_client": "website",
"dont_block": orjson.dumps(True).decode(),
},
)
self.assert_json_success(result)
queue_id = orjson.loads(result.content)["queue_id"]
recipient_result = self.tornado_call(
get_events,
recipient_user_profile,
{
"apply_markdown": orjson.dumps(True).decode(),
"client_gravatar": orjson.dumps(True).decode(),
"event_types": orjson.dumps(["message"]).decode(),
"user_client": "website",
"dont_block": orjson.dumps(True).decode(),
},
)
self.assert_json_success(recipient_result)
recipient_queue_id = orjson.loads(recipient_result.content)["queue_id"]
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 0)
local_id = "10.01"
check_send_message(
sender=user_profile,
client=get_client("whatever"),
recipient_type_name="private",
message_to=[recipient_email],
topic_name=None,
message_content="hello",
local_id=local_id,
sender_queue_id=queue_id,
)
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 1)
self.assertEqual(events[0]["type"], "message")
self.assertEqual(events[0]["message"]["sender_email"], email)
self.assertEqual(events[0]["local_message_id"], local_id)
self.assertEqual(events[0]["message"]["display_recipient"][0]["is_mirror_dummy"], False)
self.assertEqual(events[0]["message"]["display_recipient"][1]["is_mirror_dummy"], False)
last_event_id = events[0]["id"]
local_id = "10.02"
check_send_message(
sender=user_profile,
client=get_client("whatever"),
recipient_type_name="private",
message_to=[recipient_email],
topic_name=None,
message_content="hello",
local_id=local_id,
sender_queue_id=queue_id,
)
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": last_event_id,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 1)
self.assertEqual(events[0]["type"], "message")
self.assertEqual(events[0]["message"]["sender_email"], email)
self.assertEqual(events[0]["local_message_id"], local_id)
# Test that the received message in the receiver's event queue
# exists and does not contain a local id
recipient_result = self.tornado_call(
get_events,
recipient_user_profile,
{
"queue_id": recipient_queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
recipient_events = orjson.loads(recipient_result.content)["events"]
self.assert_json_success(recipient_result)
self.assert_length(recipient_events, 2)
self.assertEqual(recipient_events[0]["type"], "message")
self.assertEqual(recipient_events[0]["message"]["sender_email"], email)
self.assertTrue("local_message_id" not in recipient_events[0])
self.assertEqual(recipient_events[1]["type"], "message")
self.assertEqual(recipient_events[1]["message"]["sender_email"], email)
self.assertTrue("local_message_id" not in recipient_events[1])
def test_get_events_narrow(self) -> None:
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
def get_message(apply_markdown: bool, client_gravatar: bool) -> Dict[str, Any]:
result = self.tornado_call(
get_events,
user_profile,
dict(
apply_markdown=orjson.dumps(apply_markdown).decode(),
client_gravatar=orjson.dumps(client_gravatar).decode(),
event_types=orjson.dumps(["message"]).decode(),
narrow=orjson.dumps([["stream", "denmark"]]).decode(),
user_client="website",
dont_block=orjson.dumps(True).decode(),
),
)
self.assert_json_success(result)
queue_id = orjson.loads(result.content)["queue_id"]
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 0)
self.send_personal_message(user_profile, self.example_user("othello"), "hello")
self.send_stream_message(user_profile, "Denmark", "**hello**")
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 1)
self.assertEqual(events[0]["type"], "message")
return events[0]["message"]
message = get_message(apply_markdown=False, client_gravatar=False)
self.assertEqual(message["display_recipient"], "Denmark")
self.assertEqual(message["content"], "**hello**")
self.assertEqual(urlsplit(message["avatar_url"]).hostname, "secure.gravatar.com")
message = get_message(apply_markdown=True, client_gravatar=False)
self.assertEqual(message["display_recipient"], "Denmark")
self.assertEqual(message["content"], "<p><strong>hello</strong></p>")
self.assertIn("gravatar.com", message["avatar_url"])
do_change_user_setting(
user_profile,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
message = get_message(apply_markdown=False, client_gravatar=True)
self.assertEqual(message["display_recipient"], "Denmark")
self.assertEqual(message["content"], "**hello**")
self.assertEqual(message["avatar_url"], None)
message = get_message(apply_markdown=True, client_gravatar=True)
self.assertEqual(message["display_recipient"], "Denmark")
self.assertEqual(message["content"], "<p><strong>hello</strong></p>")
self.assertEqual(message["avatar_url"], None)
def test_bogus_queue_id(self) -> None:
user = self.example_user("hamlet")
with self.assertRaises(BadEventQueueIdError):
self.tornado_call(
get_events,
user,
{
"queue_id": "hamster",
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
def test_wrong_user_queue_id(self) -> None:
user = self.example_user("hamlet")
wrong_user = self.example_user("othello")
result = self.tornado_call(
get_events,
user,
{
"apply_markdown": orjson.dumps(True).decode(),
"client_gravatar": orjson.dumps(True).decode(),
"event_types": orjson.dumps(["message"]).decode(),
"user_client": "website",
"dont_block": orjson.dumps(True).decode(),
},
)
self.assert_json_success(result)
queue_id = orjson.loads(result.content)["queue_id"]
with self.assertLogs(level="WARNING") as cm, self.assertRaises(BadEventQueueIdError):
self.tornado_call(
get_events,
wrong_user,
{
"queue_id": queue_id,
"user_client": "website",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
self.assertIn("not authorized for queue", cm.output[0])
def test_get_events_custom_profile_fields(self) -> None:
user_profile = self.example_user("iago")
self.login_user(user_profile)
profile_field = CustomProfileField.objects.get(realm=user_profile.realm, name="Pronouns")
def check_pronouns_type_field_supported(
pronouns_field_type_supported: bool, new_name: str
) -> None:
clear_client_event_queues_for_testing()
queue_data = dict(
apply_markdown=True,
all_public_streams=True,
client_type_name="ZulipMobile",
event_types=["custom_profile_fields"],
last_connection_time=time.time(),
queue_timeout=0,
realm_id=user_profile.realm.id,
user_profile_id=user_profile.id,
pronouns_field_type_supported=pronouns_field_type_supported,
)
client = allocate_client_descriptor(queue_data)
try_update_realm_custom_profile_field(
realm=user_profile.realm, field=profile_field, name=new_name
)
result = self.tornado_call(
get_events,
user_profile,
{
"queue_id": client.event_queue.id,
"user_client": "ZulipAndroid",
"last_event_id": -1,
"dont_block": orjson.dumps(True).decode(),
},
)
events = orjson.loads(result.content)["events"]
self.assert_json_success(result)
self.assert_length(events, 1)
[pronouns_field] = (
field for field in events[0]["fields"] if field["id"] == profile_field.id
)
if pronouns_field_type_supported:
expected_type = CustomProfileField.PRONOUNS
else:
expected_type = CustomProfileField.SHORT_TEXT
self.assertEqual(pronouns_field["type"], expected_type)
check_pronouns_type_field_supported(False, "Pronouns field")
check_pronouns_type_field_supported(True, "Pronouns")
class FetchInitialStateDataTest(ZulipTestCase):
# Non-admin users don't have access to all bots
def test_realm_bots_non_admin(self) -> None:
user_profile = self.example_user("cordelia")
self.assertFalse(user_profile.is_realm_admin)
result = fetch_initial_state_data(user_profile)
self.assert_length(result["realm_bots"], 0)
# additionally the API key for a random bot is not present in the data
api_key = get_api_key(self.notification_bot(user_profile.realm))
self.assertNotIn(api_key, str(result))
# Admin users have access to all bots in the realm_bots field
def test_realm_bots_admin(self) -> None:
user_profile = self.example_user("hamlet")
do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)
self.assertTrue(user_profile.is_realm_admin)
result = fetch_initial_state_data(user_profile)
self.assertGreater(len(result["realm_bots"]), 2)
def test_max_message_id_with_no_history(self) -> None:
user_profile = self.example_user("aaron")
# Delete all historical messages for this user
UserMessage.objects.filter(user_profile=user_profile).delete()
result = fetch_initial_state_data(user_profile)
self.assertEqual(result["max_message_id"], -1)
def test_delivery_email_presence_for_non_admins(self) -> None:
user_profile = self.example_user("aaron")
hamlet = self.example_user("hamlet")
self.assertFalse(user_profile.is_realm_admin)
hamlet = self.example_user("hamlet")
do_change_user_setting(
hamlet,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
result = fetch_initial_state_data(user_profile)
(hamlet_obj,) = (value for key, value in result["raw_users"].items() if key == hamlet.id)
self.assertEqual(hamlet_obj["delivery_email"], hamlet.delivery_email)
do_change_user_setting(
hamlet,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_ADMINS,
acting_user=None,
)
result = fetch_initial_state_data(user_profile)
(hamlet_obj,) = (value for key, value in result["raw_users"].items() if key == hamlet.id)
self.assertIsNone(hamlet_obj["delivery_email"])
def test_delivery_email_presence_for_admins(self) -> None:
user_profile = self.example_user("iago")
hamlet = self.example_user("hamlet")
self.assertTrue(user_profile.is_realm_admin)
hamlet = self.example_user("hamlet")
do_change_user_setting(
hamlet,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
result = fetch_initial_state_data(user_profile)
(hamlet_obj,) = (value for key, value in result["raw_users"].items() if key == hamlet.id)
self.assertEqual(hamlet_obj["delivery_email"], hamlet.delivery_email)
do_change_user_setting(
hamlet,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_ADMINS,
acting_user=None,
)
result = fetch_initial_state_data(user_profile)
(hamlet_obj,) = (value for key, value in result["raw_users"].items() if key == hamlet.id)
self.assertIn("delivery_email", hamlet_obj)
def test_user_avatar_url_field_optional(self) -> None:
hamlet = self.example_user("hamlet")
users = [
self.example_user("iago"),
self.example_user("cordelia"),
self.example_user("ZOE"),
self.example_user("othello"),
]
for user in users:
user.long_term_idle = True
user.save()
long_term_idle_users_ids = [user.id for user in users]
result = fetch_initial_state_data(
user_profile=hamlet,
user_avatar_url_field_optional=True,
)
raw_users = result["raw_users"]
for user_dict in raw_users.values():
if user_dict["user_id"] in long_term_idle_users_ids:
self.assertFalse("avatar_url" in user_dict)
else:
self.assertIsNotNone(user_dict["avatar_url"])
gravatar_users_id = [
user_dict["user_id"]
for user_dict in raw_users.values()
if "avatar_url" in user_dict
and urlsplit(user_dict["avatar_url"]).hostname == "secure.gravatar.com"
]
reset_email_visibility_to_everyone_in_zulip_realm()
# Test again with client_gravatar = True
result = fetch_initial_state_data(
user_profile=hamlet,
client_gravatar=True,
user_avatar_url_field_optional=True,
)
raw_users = result["raw_users"]
for user_dict in raw_users.values():
if user_dict["user_id"] in gravatar_users_id:
self.assertIsNone(user_dict["avatar_url"])
else:
self.assertFalse("avatar_url" in user_dict)
def test_user_settings_based_on_client_capabilities(self) -> None:
hamlet = self.example_user("hamlet")
result = fetch_initial_state_data(
user_profile=hamlet,
user_settings_object=True,
)
self.assertIn("user_settings", result)
for prop in UserProfile.property_types:
self.assertNotIn(prop, result)
self.assertIn(prop, result["user_settings"])
result = fetch_initial_state_data(
user_profile=hamlet,
user_settings_object=False,
)
self.assertIn("user_settings", result)
for prop in UserProfile.property_types:
if prop in {
**UserProfile.display_settings_legacy,
**UserProfile.notification_settings_legacy,
}:
# Only legacy settings are included in the top level.
self.assertIn(prop, result)
self.assertIn(prop, result["user_settings"])
def test_realm_linkifiers_based_on_client_capabilities(self) -> None:
user = self.example_user("iago")
self.login_user(user)
data = {
"pattern": "#(?P<id>[123])",
"url_template": "https://realm.com/my_realm_filter/{id}",
}
post_result = self.client_post("/json/realm/filters", info=data)
self.assert_json_success(post_result)
result = fetch_initial_state_data(
user_profile=user,
linkifier_url_template=True,
)
self.assertEqual(result["realm_filters"], [])
self.assertEqual(result["realm_linkifiers"][-1]["pattern"], "#(?P<id>[123])")
self.assertEqual(
result["realm_linkifiers"][-1]["url_template"],
"https://realm.com/my_realm_filter/{id}",
)
# The default behavior should be `linkifier_url_template=False`
result = fetch_initial_state_data(
user_profile=user,
)
self.assertEqual(result["realm_filters"], [])
self.assertEqual(result["realm_linkifiers"], [])
def test_pronouns_field_type_support(self) -> None:
hamlet = self.example_user("hamlet")
result = fetch_initial_state_data(
user_profile=hamlet,
pronouns_field_type_supported=False,
)
self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"]
[pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
self.assertEqual(pronouns_field["type"], CustomProfileField.SHORT_TEXT)
result = fetch_initial_state_data(
user_profile=hamlet,
pronouns_field_type_supported=True,
)
self.assertIn("custom_profile_fields", result)
custom_profile_fields = result["custom_profile_fields"]
[pronouns_field] = (field for field in custom_profile_fields if field["name"] == "Pronouns")
self.assertEqual(pronouns_field["type"], CustomProfileField.PRONOUNS)
class ClientDescriptorsTest(ZulipTestCase):
def test_get_client_info_for_all_public_streams(self) -> None:
hamlet = self.example_user("hamlet")
realm = hamlet.realm
queue_data = dict(
all_public_streams=True,
apply_markdown=True,
client_gravatar=True,
client_type_name="website",
event_types=["message"],
last_connection_time=time.time(),
queue_timeout=0,
realm_id=realm.id,
user_profile_id=hamlet.id,
)
client = allocate_client_descriptor(queue_data)
message_event = dict(
realm_id=realm.id,
stream_name="whatever",
)
client_info = get_client_info_for_message_event(
message_event,
users=[],
)
self.assert_length(client_info, 1)
dct = client_info[client.event_queue.id]
self.assertEqual(dct["client"].apply_markdown, True)
self.assertEqual(dct["client"].client_gravatar, True)
self.assertEqual(dct["client"].user_profile_id, hamlet.id)
self.assertEqual(dct["flags"], [])
self.assertEqual(dct["is_sender"], False)
message_event = dict(
realm_id=realm.id,
stream_name="whatever",
sender_queue_id=client.event_queue.id,
)
client_info = get_client_info_for_message_event(
message_event,
users=[],
)
dct = client_info[client.event_queue.id]
self.assertEqual(dct["is_sender"], True)
def test_get_client_info_for_normal_users(self) -> None:
hamlet = self.example_user("hamlet")
cordelia = self.example_user("cordelia")
realm = hamlet.realm
def test_get_info(apply_markdown: bool, client_gravatar: bool) -> None:
clear_client_event_queues_for_testing()
queue_data = dict(
all_public_streams=False,
apply_markdown=apply_markdown,
client_gravatar=client_gravatar,
client_type_name="website",
event_types=["message"],
last_connection_time=time.time(),
queue_timeout=0,
realm_id=realm.id,
user_profile_id=hamlet.id,
)
client = allocate_client_descriptor(queue_data)
message_event = dict(
realm_id=realm.id,
stream_name="whatever",
)
client_info = get_client_info_for_message_event(
message_event,
users=[
dict(id=cordelia.id),
],
)
self.assert_length(client_info, 0)
client_info = get_client_info_for_message_event(
message_event,
users=[
dict(id=cordelia.id),
dict(id=hamlet.id, flags=["mentioned"]),
],
)
self.assert_length(client_info, 1)
dct = client_info[client.event_queue.id]
self.assertEqual(dct["client"].apply_markdown, apply_markdown)
self.assertEqual(dct["client"].client_gravatar, client_gravatar)
self.assertEqual(dct["client"].user_profile_id, hamlet.id)
self.assertEqual(dct["flags"], ["mentioned"])
self.assertEqual(dct["is_sender"], False)
test_get_info(apply_markdown=False, client_gravatar=False)
test_get_info(apply_markdown=True, client_gravatar=False)
test_get_info(apply_markdown=False, client_gravatar=True)
test_get_info(apply_markdown=True, client_gravatar=True)
def test_process_message_event_with_mocked_client_info(self) -> None:
hamlet = self.example_user("hamlet")
class MockClient:
def __init__(
self, user_profile_id: int, apply_markdown: bool, client_gravatar: bool
) -> None:
self.user_profile_id = user_profile_id
self.apply_markdown = apply_markdown
self.client_gravatar = client_gravatar
self.client_type_name = "whatever"
self.events: List[Dict[str, Any]] = []
def accepts_messages(self) -> bool:
return True
def accepts_event(self, event: Dict[str, Any]) -> bool:
assert event["type"] == "message"
return True
def add_event(self, event: Dict[str, Any]) -> None:
self.events.append(event)
client1 = MockClient(
user_profile_id=hamlet.id,
apply_markdown=True,
client_gravatar=False,
)
client2 = MockClient(
user_profile_id=hamlet.id,
apply_markdown=False,
client_gravatar=False,
)
client3 = MockClient(
user_profile_id=hamlet.id,
apply_markdown=True,
client_gravatar=True,
)
client4 = MockClient(
user_profile_id=hamlet.id,
apply_markdown=False,
client_gravatar=True,
)
client_info = {
"client:1": dict(
client=client1,
flags=["starred"],
),
"client:2": dict(
client=client2,
flags=["has_alert_word"],
),
"client:3": dict(
client=client3,
flags=[],
),
"client:4": dict(
client=client4,
flags=[],
),
}
sender = hamlet
message_event = dict(
message_dict=dict(
id=999,
content="**hello**",
rendered_content="<b>hello</b>",
sender_id=sender.id,
type="stream",
client="website",
# NOTE: Some of these fields are clutter, but some
# will be useful when we let clients specify
# that they can compute their own gravatar URLs.
sender_email=sender.email,
sender_delivery_email=sender.delivery_email,
sender_realm_id=sender.realm_id,
sender_avatar_source=UserProfile.AVATAR_FROM_GRAVATAR,
sender_avatar_version=1,
sender_is_mirror_dummy=None,
sender_email_address_visibility=UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
recipient_type=None,