-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
test_events.py
4364 lines (3846 loc) · 182 KB
/
test_events.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
# See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html for
# high-level documentation on how this system works.
#
# This module is closely integrated with zerver/lib/event_schema.py
# and zerver/lib/data_types.py systems for validating the schemas of
# events; it also uses the OpenAPI tools to validate our documentation.
import copy
import time
from contextlib import contextmanager
from datetime import timedelta
from io import StringIO
from typing import Any, Dict, Iterator, List, Optional, Set
from unittest import mock
import orjson
from dateutil.parser import parse as dateparser
from django.utils.timezone import now as timezone_now
from typing_extensions import override
from zerver.actions.alert_words import do_add_alert_words, do_remove_alert_words
from zerver.actions.bots import (
do_change_bot_owner,
do_change_default_all_public_streams,
do_change_default_events_register_stream,
do_change_default_sending_stream,
)
from zerver.actions.create_user import do_create_user, do_reactivate_user
from zerver.actions.custom_profile_fields import (
check_remove_custom_profile_field_value,
do_remove_realm_custom_profile_field,
do_update_user_custom_profile_data_if_changed,
try_add_realm_custom_profile_field,
try_update_realm_custom_profile_field,
)
from zerver.actions.default_streams import (
do_add_default_stream,
do_add_streams_to_default_stream_group,
do_change_default_stream_group_description,
do_change_default_stream_group_name,
do_create_default_stream_group,
do_remove_default_stream,
do_remove_default_stream_group,
do_remove_streams_from_default_stream_group,
lookup_default_stream_groups,
)
from zerver.actions.invites import (
do_create_multiuse_invite_link,
do_invite_users,
do_revoke_multi_use_invite,
do_revoke_user_invite,
)
from zerver.actions.message_delete import do_delete_messages
from zerver.actions.message_edit import do_update_embedded_data, do_update_message
from zerver.actions.message_flags import do_update_message_flags
from zerver.actions.muted_users import do_mute_user, do_unmute_user
from zerver.actions.onboarding_steps import do_mark_onboarding_step_as_read
from zerver.actions.presence import do_update_user_presence
from zerver.actions.reactions import do_add_reaction, do_remove_reaction
from zerver.actions.realm_domains import (
do_add_realm_domain,
do_change_realm_domain,
do_remove_realm_domain,
)
from zerver.actions.realm_emoji import check_add_realm_emoji, do_remove_realm_emoji
from zerver.actions.realm_icon import do_change_icon_source
from zerver.actions.realm_linkifiers import (
check_reorder_linkifiers,
do_add_linkifier,
do_remove_linkifier,
do_update_linkifier,
)
from zerver.actions.realm_logo import do_change_logo_source
from zerver.actions.realm_playgrounds import check_add_realm_playground, do_remove_realm_playground
from zerver.actions.realm_settings import (
do_change_realm_org_type,
do_change_realm_permission_group_setting,
do_change_realm_plan_type,
do_deactivate_realm,
do_set_push_notifications_enabled_end_timestamp,
do_set_realm_authentication_methods,
do_set_realm_new_stream_announcements_stream,
do_set_realm_property,
do_set_realm_signup_announcements_stream,
do_set_realm_user_default_setting,
do_set_realm_zulip_update_announcements_stream,
)
from zerver.actions.scheduled_messages import (
check_schedule_message,
delete_scheduled_message,
edit_scheduled_message,
)
from zerver.actions.streams import (
bulk_add_subscriptions,
bulk_remove_subscriptions,
do_change_stream_description,
do_change_stream_group_based_setting,
do_change_stream_message_retention_days,
do_change_stream_permission,
do_change_stream_post_policy,
do_change_subscription_property,
do_deactivate_stream,
do_rename_stream,
)
from zerver.actions.submessage import do_add_submessage
from zerver.actions.typing import check_send_typing_notification, do_send_stream_typing_notification
from zerver.actions.user_groups import (
add_subgroups_to_user_group,
bulk_add_members_to_user_groups,
bulk_remove_members_from_user_groups,
check_add_user_group,
check_delete_user_group,
do_change_user_group_permission_setting,
do_update_user_group_description,
do_update_user_group_name,
remove_subgroups_from_user_group,
)
from zerver.actions.user_settings import (
do_change_avatar_fields,
do_change_full_name,
do_change_user_delivery_email,
do_change_user_setting,
do_regenerate_api_key,
)
from zerver.actions.user_status import do_update_user_status
from zerver.actions.user_topics import do_set_user_topic_visibility_policy
from zerver.actions.users import (
do_change_is_billing_admin,
do_change_user_role,
do_deactivate_user,
do_update_outgoing_webhook_service,
)
from zerver.actions.video_calls import do_set_zoom_token
from zerver.lib.drafts import DraftData, do_create_drafts, do_delete_draft, do_edit_draft
from zerver.lib.event_schema import (
check_alert_words,
check_attachment_add,
check_attachment_remove,
check_attachment_update,
check_custom_profile_fields,
check_default_stream_groups,
check_default_streams,
check_delete_message,
check_direct_message,
check_draft_add,
check_draft_remove,
check_draft_update,
check_has_zoom_token,
check_heartbeat,
check_invites_changed,
check_message,
check_muted_topics,
check_muted_users,
check_onboarding_steps,
check_presence,
check_reaction_add,
check_reaction_remove,
check_realm_bot_add,
check_realm_bot_delete,
check_realm_bot_update,
check_realm_deactivated,
check_realm_default_update,
check_realm_domains_add,
check_realm_domains_change,
check_realm_domains_remove,
check_realm_emoji_update,
check_realm_export,
check_realm_linkifiers,
check_realm_playgrounds,
check_realm_update,
check_realm_update_dict,
check_realm_user_add,
check_realm_user_remove,
check_realm_user_update,
check_scheduled_message_add,
check_scheduled_message_remove,
check_scheduled_message_update,
check_stream_create,
check_stream_delete,
check_stream_update,
check_submessage,
check_subscription_add,
check_subscription_peer_add,
check_subscription_peer_remove,
check_subscription_remove,
check_subscription_update,
check_typing_start,
check_typing_stop,
check_update_display_settings,
check_update_global_notifications,
check_update_message,
check_update_message_flags_add,
check_update_message_flags_remove,
check_user_group_add,
check_user_group_add_members,
check_user_group_add_subgroups,
check_user_group_remove,
check_user_group_remove_members,
check_user_group_remove_subgroups,
check_user_group_update,
check_user_settings_update,
check_user_status,
check_user_topic,
)
from zerver.lib.events import apply_events, fetch_initial_state_data, post_process_state
from zerver.lib.markdown import render_message_markdown
from zerver.lib.mention import MentionBackend, MentionData
from zerver.lib.muted_users import get_mute_object
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import (
create_dummy_file,
get_subscription,
get_test_image_file,
reset_email_visibility_to_everyone_in_zulip_realm,
stdout_suppressed,
)
from zerver.lib.timestamp import convert_to_UTC, datetime_to_timestamp
from zerver.lib.topic import TOPIC_NAME
from zerver.lib.types import ProfileDataElementUpdateDict
from zerver.lib.user_groups import AnonymousSettingGroupDict
from zerver.models import (
Attachment,
CustomProfileField,
Message,
MultiuseInvite,
NamedUserGroup,
PreregistrationUser,
Realm,
RealmAuditLog,
RealmDomain,
RealmFilter,
RealmPlayground,
RealmUserDefault,
Service,
Stream,
UserMessage,
UserPresence,
UserProfile,
UserStatus,
UserTopic,
)
from zerver.models.clients import get_client
from zerver.models.groups import SystemGroups
from zerver.models.streams import get_stream
from zerver.models.users import get_user_by_delivery_email
from zerver.openapi.openapi import validate_against_openapi_schema
from zerver.tornado.django_api import send_event
from zerver.tornado.event_queue import (
allocate_client_descriptor,
clear_client_event_queues_for_testing,
create_heartbeat_event,
mark_clients_to_reload,
send_restart_events,
send_web_reload_client_events,
)
from zerver.views.realm_playgrounds import access_playground_by_id
class BaseAction(ZulipTestCase):
"""Core class for verifying the apply_event race handling logic as
well as the event formatting logic of any function using send_event.
See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html#testing
for extensive design details for this testing system.
"""
@override
def setUp(self) -> None:
super().setUp()
self.user_profile = self.example_user("hamlet")
@contextmanager
def verify_action(
self,
*,
event_types: Optional[List[str]] = None,
include_subscribers: bool = True,
state_change_expected: bool = True,
notification_settings_null: bool = False,
client_gravatar: bool = True,
user_avatar_url_field_optional: bool = False,
slim_presence: bool = False,
include_streams: bool = True,
num_events: int = 1,
bulk_message_deletion: bool = True,
stream_typing_notifications: bool = True,
user_settings_object: bool = False,
pronouns_field_type_supported: bool = True,
linkifier_url_template: bool = True,
user_list_incomplete: bool = False,
client_is_old: bool = False,
) -> Iterator[List[Dict[str, Any]]]:
"""
Make sure we have a clean slate of client descriptors for these tests.
If we don't do this, then certain failures will only manifest when you
run multiple tests within a single test function.
See also https://zulip.readthedocs.io/en/latest/subsystems/events-system.html#testing
for details on the design of this test system.
"""
clear_client_event_queues_for_testing()
client = allocate_client_descriptor(
dict(
user_profile_id=self.user_profile.id,
realm_id=self.user_profile.realm_id,
event_types=event_types,
client_type_name="website",
apply_markdown=True,
client_gravatar=client_gravatar,
slim_presence=slim_presence,
all_public_streams=False,
queue_timeout=600,
last_connection_time=time.time(),
narrow=[],
bulk_message_deletion=bulk_message_deletion,
stream_typing_notifications=stream_typing_notifications,
user_settings_object=user_settings_object,
pronouns_field_type_supported=pronouns_field_type_supported,
linkifier_url_template=linkifier_url_template,
user_list_incomplete=user_list_incomplete,
)
)
# hybrid_state = initial fetch state + re-applying events triggered by our action
# normal_state = do action then fetch at the end (the "normal" code path)
hybrid_state = fetch_initial_state_data(
self.user_profile,
event_types=event_types,
client_gravatar=client_gravatar,
user_avatar_url_field_optional=user_avatar_url_field_optional,
slim_presence=slim_presence,
include_subscribers=include_subscribers,
include_streams=include_streams,
pronouns_field_type_supported=pronouns_field_type_supported,
linkifier_url_template=linkifier_url_template,
user_list_incomplete=user_list_incomplete,
)
if client_is_old:
mark_clients_to_reload([client.event_queue.id])
events: List[Dict[str, Any]] = []
# We want even those `send_event` calls which have been hooked to
# `transaction.on_commit` to execute in tests.
# See the comment in `ZulipTestCase.capture_send_event_calls`.
with self.captureOnCommitCallbacks(execute=True):
yield events
# Append to an empty list so the result is accessible through the
# reference we just yielded.
events += client.event_queue.contents()
content = {
"queue_id": "123.12",
# The JSON wrapper helps in converting tuples to lists
# as tuples aren't valid JSON structure.
"events": orjson.loads(orjson.dumps(events)),
"msg": "",
"result": "success",
}
validate_against_openapi_schema(content, "/events", "get", "200")
self.assert_length(events, num_events)
initial_state = copy.deepcopy(hybrid_state)
post_process_state(self.user_profile, initial_state, notification_settings_null)
before = orjson.dumps(initial_state)
apply_events(
self.user_profile,
state=hybrid_state,
events=events,
fetch_event_types=None,
client_gravatar=client_gravatar,
slim_presence=slim_presence,
include_subscribers=include_subscribers,
linkifier_url_template=linkifier_url_template,
user_list_incomplete=user_list_incomplete,
)
post_process_state(self.user_profile, hybrid_state, notification_settings_null)
after = orjson.dumps(hybrid_state)
if state_change_expected:
if before == after: # nocoverage
print(orjson.dumps(initial_state, option=orjson.OPT_INDENT_2).decode())
print(events)
raise AssertionError(
"Test does not exercise enough code -- events do not change state."
)
else:
try:
self.match_states(initial_state, copy.deepcopy(hybrid_state), events)
except AssertionError: # nocoverage
raise AssertionError("Test is invalid--state actually does change here.")
normal_state = fetch_initial_state_data(
self.user_profile,
event_types=event_types,
client_gravatar=client_gravatar,
user_avatar_url_field_optional=user_avatar_url_field_optional,
slim_presence=slim_presence,
include_subscribers=include_subscribers,
include_streams=include_streams,
pronouns_field_type_supported=pronouns_field_type_supported,
linkifier_url_template=linkifier_url_template,
user_list_incomplete=user_list_incomplete,
)
post_process_state(self.user_profile, normal_state, notification_settings_null)
self.match_states(hybrid_state, normal_state, events)
def match_states(
self, state1: Dict[str, Any], state2: Dict[str, Any], events: List[Dict[str, Any]]
) -> None:
def normalize(state: Dict[str, Any]) -> None:
if "never_subscribed" in state:
for u in state["never_subscribed"]:
if "subscribers" in u:
u["subscribers"].sort()
if "subscriptions" in state:
for u in state["subscriptions"]:
if "subscribers" in u:
u["subscribers"].sort()
state["subscriptions"] = {u["name"]: u for u in state["subscriptions"]}
if "unsubscribed" in state:
state["unsubscribed"] = {u["name"]: u for u in state["unsubscribed"]}
if "realm_bots" in state:
state["realm_bots"] = {u["email"]: u for u in state["realm_bots"]}
# Since time is different for every call, just fix the value
state["server_timestamp"] = 0
normalize(state1)
normalize(state2)
# If this assertions fails, we have unusual problems.
self.assertEqual(state1.keys(), state2.keys())
# The far more likely scenario is that some section of
# our enormous payload does not get updated properly. We
# want the diff here to be developer-friendly, hence
# the somewhat tedious code to provide useful output.
if state1 != state2: # nocoverage
print("\n---States DO NOT MATCH---")
print("\nEVENTS:\n")
# Printing out the events is a big help to
# developers.
import json
for event in events:
print(json.dumps(event, indent=4))
print("\nMISMATCHES:\n")
for k in state1:
if state1[k] != state2[k]:
print("\nkey = " + k)
try:
self.assertEqual({k: state1[k]}, {k: state2[k]})
except AssertionError as e:
print(e)
print(
"""
NOTE:
This is an advanced test that verifies how
we apply events after fetching data. If you
do not know how to debug it, you can ask for
help on chat.
""",
flush=True,
)
raise AssertionError("Mismatching states")
class NormalActionsTest(BaseAction):
def create_bot(self, email: str, **extras: Any) -> UserProfile:
return self.create_test_bot(email, self.user_profile, **extras)
def test_mentioned_send_message_events(self) -> None:
user = self.example_user("hamlet")
for i in range(3):
content = "mentioning... @**" + user.full_name + "** hello " + str(i)
with self.verify_action():
self.send_stream_message(
self.example_user("cordelia"),
"Verona",
content,
skip_capture_on_commit_callbacks=True,
)
def test_automatically_follow_topic_where_mentioned(self) -> None:
user = self.example_user("hamlet")
do_change_user_setting(
user_profile=user,
setting_name="automatically_follow_topics_where_mentioned",
setting_value=True,
acting_user=None,
)
def get_num_events() -> int: # nocoverage
try:
user_topic = UserTopic.objects.get(
user_profile=user,
stream_id=get_stream("Verona", user.realm).id,
topic_name__iexact="test",
)
if user_topic.visibility_policy != UserTopic.VisibilityPolicy.FOLLOWED:
return 3
except UserTopic.DoesNotExist:
return 3
return 1
for i in range(3):
content = "mentioning... @**" + user.full_name + "** hello " + str(i)
with self.verify_action(num_events=get_num_events()):
self.send_stream_message(
self.example_user("cordelia"),
"Verona",
content,
skip_capture_on_commit_callbacks=True,
)
def test_topic_wildcard_mentioned_send_message_events(self) -> None:
for i in range(3):
content = "mentioning... @**topic** hello " + str(i)
with self.verify_action():
self.send_stream_message(
self.example_user("cordelia"),
"Verona",
content,
skip_capture_on_commit_callbacks=True,
)
def test_stream_wildcard_mentioned_send_message_events(self) -> None:
for i in range(3):
content = "mentioning... @**all** hello " + str(i)
with self.verify_action():
self.send_stream_message(
self.example_user("cordelia"),
"Verona",
content,
skip_capture_on_commit_callbacks=True,
)
def test_pm_send_message_events(self) -> None:
with self.verify_action():
self.send_personal_message(
self.example_user("cordelia"),
self.example_user("hamlet"),
"hola",
skip_capture_on_commit_callbacks=True,
)
# Verify direct message editing - content only edit
pm = Message.objects.order_by("-id")[0]
content = "new content"
rendering_result = render_message_markdown(pm, content)
prior_mention_user_ids: Set[int] = set()
mention_backend = MentionBackend(self.user_profile.realm_id)
mention_data = MentionData(
mention_backend=mention_backend,
content=content,
message_sender=self.example_user("cordelia"),
)
with self.verify_action(state_change_expected=False) as events:
do_update_message(
self.user_profile,
pm,
None,
None,
None,
False,
False,
content,
rendering_result,
prior_mention_user_ids,
mention_data,
)
check_update_message(
"events[0]",
events[0],
is_stream_message=False,
has_content=True,
has_topic=False,
has_new_stream_id=False,
is_embedded_update_only=False,
)
def test_huddle_send_message_events(self) -> None:
huddle = [
self.example_user("hamlet"),
self.example_user("othello"),
]
with self.verify_action():
self.send_huddle_message(
self.example_user("cordelia"), huddle, "hola", skip_capture_on_commit_callbacks=True
)
def test_user_creation_events_on_sending_messages(self) -> None:
self.set_up_db_for_testing_user_access()
polonius = self.example_user("polonius")
cordelia = self.example_user("cordelia")
self.user_profile = polonius
# Test that guest will not receive creation event
# for bots as they can access all the bots.
bot = self.create_test_bot("test2", cordelia, full_name="Test bot")
with self.verify_action(num_events=1) as events:
self.send_personal_message(bot, polonius, "hola", skip_capture_on_commit_callbacks=True)
check_direct_message("events[0]", events[0])
with self.verify_action(num_events=2) as events:
self.send_personal_message(
cordelia, polonius, "hola", skip_capture_on_commit_callbacks=True
)
check_realm_user_add("events[0]", events[0])
check_direct_message("events[1]", events[1])
self.assertEqual(events[0]["person"]["user_id"], cordelia.id)
othello = self.example_user("othello")
desdemona = self.example_user("desdemona")
with self.verify_action(num_events=3) as events:
self.send_huddle_message(
othello, [polonius, desdemona, bot], "hola", skip_capture_on_commit_callbacks=True
)
check_realm_user_add("events[0]", events[0])
check_realm_user_add("events[1]", events[1])
check_direct_message("events[2]", events[2])
user_creation_user_ids = {events[0]["person"]["user_id"], events[1]["person"]["user_id"]}
self.assertEqual(user_creation_user_ids, {othello.id, desdemona.id})
def test_stream_send_message_events(self) -> None:
hamlet = self.example_user("hamlet")
for stream_name in ["Verona", "Denmark", "core team"]:
stream = get_stream(stream_name, hamlet.realm)
sub = get_subscription(stream.name, hamlet)
do_change_subscription_property(hamlet, sub, stream, "is_muted", True, acting_user=None)
def verify_events_generated_and_reset_visibility_policy(
events: List[Dict[str, Any]], stream_name: str, topic_name: str
) -> None:
# event-type: muted_topics
check_muted_topics("events[0]", events[0])
# event-type: user_topic
check_user_topic("events[1]", events[1])
if events[2]["type"] == "message":
check_message("events[2]", events[2])
else:
# event-type: reaction
check_reaction_add("events[2]", events[2])
# Reset visibility policy
do_set_user_topic_visibility_policy(
hamlet,
get_stream(stream_name, hamlet.realm),
topic_name,
visibility_policy=UserTopic.VisibilityPolicy.INHERIT,
)
# Events generated during send message action depends on the 'automatically_follow_topics_policy'
# and 'automatically_unmute_topics_in_muted_streams_policy' settings. Here we test all the
# possible combinations.
# action: participation
# 'automatically_follow_topics_policy' | 'automatically_unmute_topics_in_muted_streams_policy' | visibility_policy
# ON_PARTICIPATION | ON_INITIATION | FOLLOWED
# ON_PARTICIPATION | ON_PARTICIPATION | FOLLOWED
# ON_PARTICIPATION | ON_SEND | FOLLOWED
# ON_PARTICIPATION | NEVER | FOLLOWED
message_id = self.send_stream_message(hamlet, "Verona", "hello", "topic")
message = Message.objects.get(id=message_id)
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_follow_topics_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_PARTICIPATION,
acting_user=None,
)
for setting_value in UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES:
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=setting_value,
acting_user=None,
)
# Three events are generated:
# 2 for following the topic and 1 for adding reaction.
with self.verify_action(client_gravatar=False, num_events=3) as events:
do_add_reaction(hamlet, message, "tada", "1f389", "unicode_emoji")
verify_events_generated_and_reset_visibility_policy(events, "Verona", "topic")
do_remove_reaction(hamlet, message, "1f389", "unicode_emoji")
# action: send
# 'automatically_follow_topics_policy' | 'automatically_unmute_topics_in_muted_streams_policy' | visibility_policy
# ON_SEND | ON_INITIATION | FOLLOWED
# ON_SEND | ON_PARTICIPATION | FOLLOWED
# ON_SEND | ON_SEND | FOLLOWED
# ON_SEND | NEVER | FOLLOWED
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_follow_topics_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_SEND,
acting_user=None,
)
for setting_value in UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES:
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=setting_value,
acting_user=None,
)
# Three events are generated:
# 2 for following the topic and 1 for the message sent.
with self.verify_action(client_gravatar=False, num_events=3) as events:
self.send_stream_message(
hamlet, "Verona", "hello", "topic", skip_capture_on_commit_callbacks=True
)
verify_events_generated_and_reset_visibility_policy(events, "Verona", "topic")
# action: initiation
# 'automatically_follow_topics_policy' | 'automatically_unmute_topics_in_muted_streams_policy' | visibility_policy
# ON_INITIATION | ON_INITIATION | FOLLOWED
# ON_INITIATION | ON_PARTICIPATION | FOLLOWED
# ON_INITIATION | ON_SEND | FOLLOWED
# ON_INITIATION | NEVER | FOLLOWED
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_follow_topics_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_INITIATION,
acting_user=None,
)
for index, setting_value in enumerate(
UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES
):
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=setting_value,
acting_user=None,
)
# Three events are generated:
# 2 for following the topic and 1 for the message sent.
with self.verify_action(client_gravatar=False, num_events=3) as events:
self.send_stream_message(
hamlet,
"Denmark",
"hello",
f"new topic {index}",
skip_capture_on_commit_callbacks=True,
)
verify_events_generated_and_reset_visibility_policy(
events, "Denmark", f"new topic {index}"
)
# 'automatically_follow_topics_policy' | 'automatically_unmute_topics_in_muted_streams_policy' | visibility_policy
# NEVER | ON_INITIATION | UNMUTED
# NEVER | ON_PARTICIPATION | UNMUTED
# NEVER | ON_SEND | UNMUTED
# NEVER | NEVER | NA
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_follow_topics_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_NEVER,
acting_user=None,
)
for setting_value in [
UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_INITIATION,
UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_PARTICIPATION,
UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_SEND,
]:
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=setting_value,
acting_user=None,
)
# Three events are generated:
# 2 for unmuting the topic and 1 for the message sent.
with self.verify_action(client_gravatar=False, num_events=3) as events:
self.send_stream_message(
hamlet, "core team", "hello", "topic", skip_capture_on_commit_callbacks=True
)
verify_events_generated_and_reset_visibility_policy(events, "core team", "topic")
# If current_visibility_policy is already set to the value the policies would set.
do_set_user_topic_visibility_policy(
hamlet,
get_stream("core team", hamlet.realm),
"new Topic",
visibility_policy=UserTopic.VisibilityPolicy.UNMUTED,
)
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_PARTICIPATION,
acting_user=None,
)
# 1 event for the message sent
with self.verify_action(client_gravatar=False, num_events=1) as events:
self.send_stream_message(
hamlet, "core team", "hello", "new Topic", skip_capture_on_commit_callbacks=True
)
do_change_user_setting(
user_profile=hamlet,
setting_name="automatically_unmute_topics_in_muted_streams_policy",
setting_value=UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_NEVER,
acting_user=None,
)
# Only one message event is generated
with self.verify_action(client_gravatar=True) as events:
self.send_stream_message(
hamlet, "core team", "hello", skip_capture_on_commit_callbacks=True
)
# event-type: message
check_message("events[0]", events[0])
assert isinstance(events[0]["message"]["avatar_url"], str)
do_change_user_setting(
self.example_user("hamlet"),
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
with self.verify_action(client_gravatar=True) as events:
self.send_stream_message(
hamlet, "core team", "hello", skip_capture_on_commit_callbacks=True
)
check_message("events[0]", events[0])
assert events[0]["message"]["avatar_url"] is None
# Here we add coverage for the case where 'apply_unread_message_event'
# should be called and unread messages in unmuted or followed topic in
# muted stream is treated as unmuted stream message, thus added to 'unmuted_stream_msgs'.
stream = get_stream("Verona", hamlet.realm)
do_set_user_topic_visibility_policy(
hamlet,
stream,
"test",
visibility_policy=UserTopic.VisibilityPolicy.UNMUTED,
)
with self.verify_action(state_change_expected=True):
self.send_stream_message(
self.example_user("aaron"), "Verona", "hello", skip_capture_on_commit_callbacks=True
)
def test_stream_update_message_events(self) -> None:
iago = self.example_user("iago")
self.send_stream_message(iago, "Verona", "hello")
# Verify stream message editing - content only
message = Message.objects.order_by("-id")[0]
content = "new content"
rendering_result = render_message_markdown(message, content)
prior_mention_user_ids: Set[int] = set()
mention_backend = MentionBackend(self.user_profile.realm_id)
mention_data = MentionData(
mention_backend=mention_backend,
content=content,
message_sender=iago,
)
with self.verify_action(state_change_expected=False) as events:
do_update_message(
self.user_profile,
message,
None,
None,
None,
False,
False,
content,
rendering_result,
prior_mention_user_ids,
mention_data,
)
check_update_message(
"events[0]",
events[0],
is_stream_message=True,
has_content=True,
has_topic=False,
has_new_stream_id=False,
is_embedded_update_only=False,
)
# Verify stream message editing - topic only
topic_name = "new_topic"
propagate_mode = "change_all"
with self.verify_action(state_change_expected=True) as events:
do_update_message(
self.user_profile,
message,
None,
topic_name,
propagate_mode,
False,
False,
None,
None,
prior_mention_user_ids,
mention_data,
)
check_update_message(
"events[0]",
events[0],
is_stream_message=True,
has_content=False,
has_topic=True,
has_new_stream_id=False,
is_embedded_update_only=False,
)
# Verify special case of embedded content update
content = "embed_content"
rendering_result = render_message_markdown(message, content)
with self.verify_action(state_change_expected=False) as events:
do_update_embedded_data(self.user_profile, message, content, rendering_result)
check_update_message(
"events[0]",
events[0],
is_stream_message=False,
has_content=False,
has_topic=False,
has_new_stream_id=False,
is_embedded_update_only=True,
)
# Verify move topic to different stream.
self.subscribe(self.user_profile, "Verona")
self.subscribe(self.user_profile, "Denmark")
self.send_stream_message(iago, "Verona")
message_id = self.send_stream_message(self.user_profile, "Verona")
message = Message.objects.get(id=message_id)
stream = get_stream("Denmark", self.user_profile.realm)
propagate_mode = "change_all"
prior_mention_user_ids = set()
with self.verify_action(
state_change_expected=True,
# There are 3 events generated for this action
# * update_message: For updating existing messages
# * 2 new message events: Breadcrumb messages in the new and old topics.
num_events=3,
) as events:
do_update_message(
self.user_profile,
message,
stream,
None,
propagate_mode,
True,
True,
None,
None,
set(),
None,
)
check_update_message(
"events[0]",
events[0],
is_stream_message=True,
has_content=False,
has_topic=False,
has_new_stream_id=True,
is_embedded_update_only=False,
)
# Move both stream and topic, with update_message_flags
# excluded from event types.
self.send_stream_message(self.user_profile, "Verona")
message_id = self.send_stream_message(self.user_profile, "Verona")
message = Message.objects.get(id=message_id)
stream = get_stream("Denmark", self.user_profile.realm)
propagate_mode = "change_all"
prior_mention_user_ids = set()
with self.verify_action(
state_change_expected=True,
# Skip "update_message_flags" to exercise the code path
# where raw_unread_msgs does not exist in the state.
event_types=["message", "update_message"],
# There are 3 events generated for this action
# * update_message: For updating existing messages
# * 2 new message events: Breadcrumb messages in the new and old topics.
num_events=3,
) as events:
do_update_message(
self.user_profile,
message,
stream,
"final_topic",
propagate_mode,
True,
True,