-
-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathtest_model.py
4566 lines (4225 loc) · 159 KB
/
test_model.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 copy
import json
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
import pytest
from pytest import param as case
from pytest_mock import MockerFixture
from zulip import Client, ZulipError
from zulipterminal.config.symbols import STREAM_TOPIC_SEPARATOR
from zulipterminal.helper import initial_index, powerset
from zulipterminal.model import (
MAX_MESSAGE_LENGTH,
MAX_STREAM_NAME_LENGTH,
MAX_TOPIC_NAME_LENGTH,
PRESENCE_OFFLINE_THRESHOLD_SECS,
PRESENCE_PING_INTERVAL_SECS,
TYPING_STARTED_EXPIRY_PERIOD,
TYPING_STARTED_WAIT_PERIOD,
TYPING_STOPPED_WAIT_PERIOD,
Model,
ServerConnectionFailure,
UserSettings,
)
MODULE = "zulipterminal.model"
MODEL = MODULE + ".Model"
CONTROLLER = "zulipterminal.core.Controller"
class TestModel:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker: Any) -> None:
self.urlparse = mocker.patch("urllib.parse.urlparse")
self.controller = mocker.patch(CONTROLLER, return_value=None)
self.client = mocker.patch(CONTROLLER + ".client", spec=Client)
self.client.base_url = "chat.zulip.zulip"
mocker.patch(MODEL + "._start_presence_updates")
self.display_error_if_present = mocker.patch(
MODULE + ".display_error_if_present"
)
self.notify_if_message_sent_outside_narrow = mocker.patch(
MODULE + ".notify_if_message_sent_outside_narrow"
)
@pytest.fixture
def model(self, mocker, initial_data, user_profile, unicode_emojis):
mocker.patch(MODEL + ".get_messages", return_value="")
self.client.register.return_value = initial_data
mocker.patch(MODEL + "._update_users_data_from_initial_data")
# NOTE: PATCH WHERE USED NOT WHERE DEFINED
self.classify_unread_counts = mocker.patch(
MODULE + ".classify_unread_counts", return_value=[]
)
self.client.get_profile.return_value = user_profile
mocker.patch(MODULE + ".unicode_emojis", EMOJI_DATA=unicode_emojis)
model = Model(self.controller)
return model
def test_init(
self,
model,
initial_data,
user_profile,
unicode_emojis,
realm_emojis_data,
zulip_emoji,
stream_dict,
):
assert hasattr(model, "controller")
assert hasattr(model, "client")
assert model.narrow == []
assert model._have_last_message == {}
assert model.stream_id is None
assert model.stream_dict == stream_dict
assert model.recipients == frozenset()
assert model.index == initial_index
assert model.last_unread_pm is None
model.get_messages.assert_called_once_with(
num_before=30, num_after=10, anchor=None
)
assert model.initial_data == initial_data
assert model.server_version == initial_data["zulip_version"]
assert model.server_feature_level == initial_data.get("zulip_feature_level", 0)
assert model.user_id == user_profile["user_id"]
assert model.user_full_name == user_profile["full_name"]
assert model.user_email == user_profile["email"]
assert model.server_name == initial_data["realm_name"]
# FIXME Add test here for model.server_url
model._update_users_data_from_initial_data.assert_called_once_with()
assert model.users == []
self.classify_unread_counts.assert_called_once_with(model)
assert model.unread_counts == []
assert model.active_emoji_data == OrderedDict(
sorted(
{**unicode_emojis, **realm_emojis_data, **zulip_emoji}.items(),
key=lambda e: e[0],
)
)
assert model.all_emoji_names == sorted(
[
name
for emoji in {
**unicode_emojis,
**realm_emojis_data,
**zulip_emoji,
}.items()
for name in [emoji[0], *emoji[1]["aliases"]]
]
)
# Deactivated emoji is removed from active emojis set
assert "green_tick" not in model.active_emoji_data
# Custom emoji replaces unicode emoji with same name.
assert model.active_emoji_data["joker"]["type"] == "realm_emoji"
# zulip_extra_emoji replaces all other emoji types for 'zulip' emoji.
assert model.active_emoji_data["zulip"]["type"] == "zulip_extra_emoji"
@pytest.mark.parametrize(
"sptn, expected_sptn_value",
[(None, True), (True, True), (False, False)],
)
def test_init_user_settings(self, mocker, initial_data, sptn, expected_sptn_value):
assert "user_settings" not in initial_data # we add it in tests
if sptn is not None:
initial_data["user_settings"] = {"send_private_typing_notifications": sptn}
mocker.patch(MODEL + ".get_messages", return_value="")
self.client.register = mocker.Mock(return_value=initial_data)
model = Model(self.controller)
assert model.user_settings() == UserSettings(
send_private_typing_notifications=expected_sptn_value,
twenty_four_hour_time=initial_data["twenty_four_hour_time"],
pm_content_in_desktop_notifications=initial_data[
"pm_content_in_desktop_notifications"
],
)
def test_user_settings_expected_contents(self, model):
expected_keys = {
"send_private_typing_notifications",
"twenty_four_hour_time",
"pm_content_in_desktop_notifications",
}
settings = model.user_settings()
assert set(settings) == expected_keys
# Ensure original settings are unchanged through accessor
settings["foo"] = "bar"
assert set(model._user_settings) == expected_keys
@pytest.mark.parametrize(
"server_response, locally_processed_data, zulip_feature_level",
[
(
[["Stream 1", "muted stream muted topic"]],
{("Stream 1", "muted stream muted topic"): None},
0,
),
(
[["Stream 2", "muted topic", 1530129122]],
{("Stream 2", "muted topic"): 1530129122},
1,
),
],
ids=[
"zulip_feature_level:0",
"zulip_feature_level:1",
],
)
def test_init_muted_topics(
self,
mocker,
initial_data,
server_response,
locally_processed_data,
zulip_feature_level,
):
mocker.patch(MODEL + ".get_messages", return_value="")
initial_data["zulip_feature_level"] = zulip_feature_level
initial_data["muted_topics"] = server_response
self.client.register = mocker.Mock(return_value=initial_data)
model = Model(self.controller)
assert model._muted_topics == locally_processed_data
def test_init_InvalidAPIKey_response(self, mocker, initial_data):
# Both network calls indicate the same response
mocker.patch(MODEL + ".get_messages", return_value="Invalid API key")
mocker.patch(
MODEL + "._register_desired_events", return_value="Invalid API key"
)
mocker.patch(MODEL + "._update_users_data_from_initial_data")
mocker.patch(MODEL + "._subscribe_to_streams")
self.classify_unread_counts = mocker.patch(
MODULE + ".classify_unread_counts", return_value=[]
)
with pytest.raises(ServerConnectionFailure) as e:
Model(self.controller)
assert str(e.value) == "Invalid API key (get_messages, register)"
def test_init_ZulipError_exception(self, mocker, initial_data, exception_text="X"):
# Both network calls fail, resulting in exceptions
mocker.patch(MODEL + ".get_messages", side_effect=ZulipError(exception_text))
mocker.patch(
MODEL + "._register_desired_events", side_effect=ZulipError(exception_text)
)
mocker.patch(MODEL + "._update_users_data_from_initial_data")
mocker.patch(MODEL + "._subscribe_to_streams")
self.classify_unread_counts = mocker.patch(
MODULE + ".classify_unread_counts", return_value=[]
)
with pytest.raises(ServerConnectionFailure) as e:
Model(self.controller)
assert str(e.value) == exception_text + " (get_messages, register)"
def test_register_initial_desired_events(self, mocker, initial_data):
mocker.patch(MODEL + ".get_messages", return_value="")
mocker.patch(MODEL + "._update_users_data_from_initial_data")
self.client.register.return_value = initial_data
model = Model(self.controller)
event_types = [
"message",
"update_message",
"reaction",
"subscription",
"typing",
"update_message_flags",
"update_global_notifications",
"update_display_settings",
"user_settings",
"realm_emoji",
"realm_user",
]
fetch_event_types = [
"realm",
"presence",
"subscription",
"message",
"starred_messages",
"update_message_flags",
"muted_topics",
"realm_user",
"realm_user_groups",
"update_global_notifications",
"update_display_settings",
"user_settings",
"realm_emoji",
"custom_profile_fields",
"zulip_version",
]
model.client.register.assert_called_once_with(
event_types=event_types,
fetch_event_types=fetch_event_types,
apply_markdown=True,
client_gravatar=True,
include_subscribers=True,
)
@pytest.mark.parametrize(
[
"to_vary_in_stream_dict",
"realm_msg_retention_days",
"feature_level",
"expect_msg_retention_text",
],
[
case(
{1: {}},
None,
0,
{1: "Indefinite [Organization default]"},
id="ZFL=0_no_stream_retention_realm_retention=None",
),
case(
{1: {}},
None,
10,
{1: "Indefinite [Organization default]"},
id="ZFL=10_no_stream_retention_realm_retention=None",
),
case(
{1: {}, 2: {}},
-1,
16,
{
1: "Indefinite [Organization default]",
2: "Indefinite [Organization default]",
},
id="ZFL=16_no_stream_retention_realm_retention=-1",
),
case(
{2: {"message_retention_days": 30}},
60,
17,
{2: "30"},
id="ZFL=17_stream_retention_days=30",
),
case(
{
1: {"message_retention_days": None},
2: {"message_retention_days": -1},
},
72,
18,
{1: "72 [Organization default]", 2: "Indefinite"},
id="ZFL=18_stream_retention_days=[None, -1]",
),
],
)
def test_normalize_and_cache_message_retention_text(
self,
model,
stream_dict,
to_vary_in_stream_dict,
realm_msg_retention_days,
feature_level,
expect_msg_retention_text,
):
model.stream_dict = stream_dict
model.server_feature_level = feature_level
model.initial_data["realm_message_retention_days"] = realm_msg_retention_days
for stream_id in to_vary_in_stream_dict:
model.stream_dict[stream_id].update(to_vary_in_stream_dict[stream_id])
model.normalize_and_cache_message_retention_text()
for stream_id in to_vary_in_stream_dict:
assert (
model.cached_retention_text[stream_id]
== expect_msg_retention_text[stream_id]
)
@pytest.mark.parametrize("msg_id", [1, 5, None])
@pytest.mark.parametrize(
"narrow",
[
[],
[["stream", "hello world"]],
[["stream", "hello world"], ["topic", "what's it all about?"]],
[["pm-with", "[email protected]"]],
[["pm-with", "[email protected], [email protected]"]],
[["is", "private"]],
[["is", "starred"]],
],
)
def test_get_focus_in_current_narrow_individually(self, model, msg_id, narrow):
model.index = {"pointer": {str(narrow): msg_id}}
model.narrow = narrow
assert model.get_focus_in_current_narrow() == msg_id
@pytest.mark.parametrize("msg_id", [1, 5])
@pytest.mark.parametrize(
"narrow",
[
[],
[["stream", "hello world"]],
[["stream", "hello world"], ["topic", "what's it all about?"]],
[["pm-with", "[email protected]"]],
[["pm-with", "[email protected], [email protected]"]],
[["is", "private"]],
[["is", "starred"]],
],
)
def test_set_focus_in_current_narrow(self, mocker, model, narrow, msg_id):
model.index = dict(pointer=dict())
model.narrow = narrow
model.set_focus_in_current_narrow(msg_id)
assert model.index["pointer"][str(narrow)] == msg_id
@pytest.mark.parametrize(
"narrow, is_search_narrow",
[
([], False),
([["search", "FOO"]], True),
([["is", "private"]], False),
([["is", "private"], ["search", "FOO"]], True),
([["search", "FOO"], ["is", "private"]], True),
([["stream", "PTEST"]], False),
([["stream", "PTEST"], ["search", "FOO"]], True),
([["stream", "7"], ["topic", "Test"]], False),
([["stream", "7"], ["topic", "Test"], ["search", "FOO"]], True),
([["stream", "7"], ["search", "FOO"], ["topic", "Test"]], True),
([["search", "FOO"], ["stream", "7"], ["topic", "Test"]], True),
],
)
def test_is_search_narrow(self, model, narrow, is_search_narrow):
model.narrow = narrow
assert model.is_search_narrow() == is_search_narrow
@pytest.mark.parametrize(
"bad_args",
[
dict(topic="some topic"),
dict(stream="foo", pm_with="someone"),
dict(topic="blah", pm_with="someone"),
dict(pm_with="someone", topic="foo"),
],
)
def test_set_narrow_bad_input(self, model, bad_args):
with pytest.raises(RuntimeError):
model.set_narrow(**bad_args)
@pytest.mark.parametrize(
"narrow, good_args",
[
([], dict()),
([["stream", "some stream"]], dict(stream="some stream")),
(
[["stream", "some stream"], ["topic", "some topic"]],
dict(stream="some stream", topic="some topic"),
),
([["is", "starred"]], dict(starred=True)),
([["is", "mentioned"]], dict(mentioned=True)),
([["is", "private"]], dict(pms=True)),
([["pm-with", "[email protected]"]], dict(pm_with="[email protected]")),
],
)
def test_set_narrow_already_set(self, model, narrow, good_args):
model.narrow = narrow
assert model.set_narrow(**good_args)
assert model.narrow == narrow
@pytest.mark.parametrize(
"initial_narrow, narrow, good_args",
[
([["stream", "foo"]], [], dict()),
([], [["stream", "Stream 1"]], dict(stream="Stream 1")),
(
[],
[["stream", "Stream 1"], ["topic", "some topic"]],
dict(stream="Stream 1", topic="some topic"),
),
([], [["is", "starred"]], dict(starred=True)),
([], [["is", "mentioned"]], dict(mentioned=True)),
([], [["is", "private"]], dict(pms=True)),
([], [["pm-with", "[email protected]"]], dict(pm_with="[email protected]")),
],
)
def test_set_narrow_not_already_set(
self, model, initial_narrow, narrow, good_args, user_dict, stream_dict
):
model.narrow = initial_narrow
model.user_dict = user_dict
model.stream_dict = stream_dict
assert not model.set_narrow(**good_args)
assert model.narrow != initial_narrow
assert model.narrow == narrow
# FIXME: Add assert for recipients being updated (other tests too?)
@pytest.mark.parametrize(
"narrow, index, current_ids",
[
([], {"all_msg_ids": {0, 1}}, {0, 1}),
([["stream", "FOO"]], {"stream_msg_ids_by_stream_id": {1: {0, 1}}}, {0, 1}),
(
[["stream", "FOO"], ["topic", "BOO"]],
{"topic_msg_ids": {1: {"BOO": {0, 1}}}},
{0, 1},
),
(
[["stream", "FOO"], ["topic", "BOOBOO"]], # Covers one empty-set case
{"topic_msg_ids": {1: {"BOO": {0, 1}}}},
set(),
),
([["is", "private"]], {"direct_msg_ids": {0, 1}}, {0, 1}),
(
[["pm-with", "[email protected]"]],
{"direct_msg_ids_by_user_ids": {frozenset({1, 2}): {0, 1}}},
{0, 1},
),
(
[["pm-with", "[email protected]"]],
{ # Covers recipient empty-set case
"direct_msg_ids_by_user_ids": {
frozenset({1, 3}): {0, 1} # NOTE {1,3} not {1,2}
}
},
set(),
),
([["search", "FOO"]], {"search": {0, 1}}, {0, 1}),
([["is", "starred"]], {"starred_msg_ids": {0, 1}}, {0, 1}),
(
[["stream", "FOO"], ["search", "FOO"]],
{
"stream_msg_ids_by_stream_id": {
1: {0, 1, 2} # NOTE Should not be returned
},
"search": {0, 1},
},
{0, 1},
),
([["is", "mentioned"]], {"mentioned_msg_ids": {0, 1}}, {0, 1}),
],
)
def test_get_message_ids_in_current_narrow(
self, mocker, model, narrow, index, current_ids
):
model.recipients = frozenset({1, 2})
model.stream_id = 1
model.narrow = narrow
model.index = index
assert current_ids == model.get_message_ids_in_current_narrow()
@pytest.mark.parametrize(
"response, expected_index, return_value",
[
(
{"result": "success", "topics": [{"name": "Foo"}, {"name": "Boo"}]},
{23: ["Foo", "Boo"]},
"",
),
({"result": "success", "topics": []}, {23: []}, ""),
(
{"result": "failure", "msg": "Some Error", "topics": []},
{23: []},
"Some Error",
),
],
)
def test__fetch_topics_in_streams(
self, mocker, response, model, return_value, expected_index
) -> None:
self.client.get_stream_topics = mocker.Mock(return_value=response)
result = model._fetch_topics_in_streams([23])
self.client.get_stream_topics.assert_called_once_with(23)
assert model.index["topics"] == expected_index
assert result == return_value
if response["result"] != "success":
self.display_error_if_present.assert_called_once_with(
response, self.controller
)
@pytest.mark.parametrize(
"topics_index, fetched",
[
(["test"], False),
([], True),
],
)
def test_topics_in_stream(self, mocker, model, topics_index, fetched, stream_id=1):
model.index["topics"][stream_id] = topics_index
model._fetch_topics_in_streams = mocker.Mock()
return_value = model.topics_in_stream(stream_id)
assert model._fetch_topics_in_streams.called == fetched
assert model.index["topics"][stream_id] == return_value
assert model.index["topics"][stream_id] is not return_value
@pytest.mark.parametrize(
"response, expected_return_value",
[
(
{"result": "success", "msg": "", "email": "[email protected]"},
),
(
{"result": "error", "msg": "Invalid stream ID", "code": "BAD_REQUEST"},
None,
),
],
ids=["valid_email_returned", "no_email_returned"],
)
def test__fetch_stream_email_from_endpoint(
self,
mocker: MockerFixture,
model: Any,
response: Dict[str, str],
expected_return_value: Optional[str],
stream_id: int = 1,
) -> None:
self.client.call_endpoint = mocker.Mock(return_value=response)
result = model._fetch_stream_email_from_endpoint(stream_id)
self.client.call_endpoint.assert_called_once_with(
f"/streams/{stream_id}/email_address", method="GET"
)
assert result == expected_return_value
@pytest.mark.parametrize(
"email_address_stream_dict, email_fetch_response, "
"expected_fetched, expected_return_value",
[
(
{"email_address": "[email protected]"},
None,
False,
),
({}, "[email protected]", True, "[email protected]"),
({}, None, True, None),
],
ids=[
"email_present_in_dict:ZFL<226",
"email_absent_from_dict_and_fetched_ok:ZFL>=226",
"email_absent_from_dict_and_fetch_failed:ZFL>=226",
],
)
def test_get_stream_email_address(
self,
mocker: MockerFixture,
model: Any,
email_address_stream_dict: Dict[str, str],
email_fetch_response: Optional[str],
expected_fetched: bool,
expected_return_value: Optional[str],
stream_id: int = 1,
) -> None:
model.stream_dict[stream_id] = email_address_stream_dict
model._fetch_stream_email_from_endpoint = mocker.Mock(
return_value=email_fetch_response
)
result = model.get_stream_email_address(stream_id)
assert model._fetch_stream_email_from_endpoint.called == expected_fetched
assert result == expected_return_value
# pre server v3 provide user_id or id as a property within user key
# post server v3 provide user_id as a property outside the user key
@pytest.mark.parametrize("user_key", ["user_id", "id", None])
@pytest.mark.parametrize(
"emoji_unit, existing_reactions, expected_method",
[
case(
("thumbs_up", "1f44d", "unicode_emoji"),
[],
"POST",
id="add_unicode_original_no_existing_emoji",
),
case(
("singing", "3", "realm_emoji"),
[],
"POST",
id="add_realm_original_no_existing_emoji",
),
case(
("joy_cat", "1f639", "unicode_emoji"),
[dict(user="me", emoji_code="1f44d")],
"POST",
id="add_unicode_original_mine_existing_different_emoji",
),
case(
("zulip", "zulip", "zulip_extra_emoji"),
[dict(user="me", emoji_code="1f639")],
"POST",
id="add_zulip_original_mine_existing_different_emoji",
),
case(
("rock_on", "1f918", "unicode_emoji"),
[dict(user="not me", emoji_code="1f918")],
"POST",
id="add_unicode_original_others_existing_same_emoji",
),
case(
("grinning", "1f600", "unicode_emoji"),
[dict(user="not me", emoji_code="1f600")],
"POST",
id="add_unicode_alias_others_existing_same_emoji",
),
case(
("smiley", "1f603", "unicode_emoji"),
[dict(user="me", emoji_code="1f603")],
"DELETE",
id="remove_unicode_original_mine_existing_same_emoji",
),
case(
("smug", "1f60f", "unicode_emoji"),
[dict(user="me", emoji_code="1f60f")],
"DELETE",
id="remove_unicode_alias_mine_existing_same_emoji",
),
case(
("zulip", "zulip", "zulip_extra_emoji"),
[dict(user="me", emoji_code="zulip")],
"DELETE",
id="remove_zulip_original_mine_existing_same_emoji",
),
],
)
def test_toggle_message_reaction_with_valid_emoji(
self,
mocker,
model,
user_key,
emoji_unit,
existing_reactions,
expected_method,
msg_id=5,
):
# Map 'id' to running user_id or an arbitrary other (+1)
id = (
model.user_id
if existing_reactions and existing_reactions[0]["user"] == "me"
else model.user_id + 1
)
full_existing_reactions = [
dict(er, user={user_key: id})
if user_key is not None
else dict(user_id=id, emoji_code=er["emoji_code"])
for er in existing_reactions
]
message = dict(id=msg_id, reactions=full_existing_reactions)
emoji_name, emoji_code, emoji_type = emoji_unit
reaction_spec = dict(
emoji_name=emoji_name,
reaction_type=emoji_type,
emoji_code=emoji_code,
message_id=str(msg_id),
)
response = mocker.Mock()
model.client.add_reaction.return_value = response
model.client.remove_reaction.return_value = response
model.toggle_message_reaction(message, emoji_name)
if expected_method == "POST":
model.client.add_reaction.assert_called_once_with(reaction_spec)
model.client.remove_reaction.assert_not_called()
elif expected_method == "DELETE":
model.client.remove_reaction.assert_called_once_with(reaction_spec)
model.client.add_reaction.assert_not_called()
self.display_error_if_present.assert_called_once_with(response, self.controller)
def test_toggle_message_reaction_with_invalid_emoji(self, model):
with pytest.raises(AssertionError):
model.toggle_message_reaction(dict(), "x")
@pytest.mark.parametrize(
"emoji_code, reactions, expected_has_user_reacted",
[
case(
"1f600",
[{"user": {"id": 2}, "emoji_code": "1f602"}],
False,
id="id_inside_user_field__user_not_reacted",
),
case(
"1f44d",
[{"user": {"user_id": 1}, "emoji_code": "1f44d"}],
True,
id="user_id_inside_user_field__user_has_reacted",
),
case(
"zulip",
[{"user_id": 1, "emoji_code": "zulip"}],
True,
id="no_user_field_with_user_id__user_has_reacted",
),
case(
"1f639",
[{"user_id": 2, "emoji_code": "1f44d"}],
False,
id="no_user_field_with_user_id__user_not_reacted",
),
],
)
def test_has_user_reacted_to_message(
self,
model,
emoji_code,
reactions,
expected_has_user_reacted,
user_id=1,
message_id=5,
):
model.user_id = user_id
message = dict(id=message_id, reactions=reactions)
has_reacted = model.has_user_reacted_to_message(message, emoji_code=emoji_code)
assert has_reacted == expected_has_user_reacted
@pytest.mark.parametrize("recipient_user_ids", [[5140], [5140, 5179]])
@pytest.mark.parametrize("status", ["start", "stop"])
def test_send_typing_status_by_user_ids(
self, mocker, model, status, recipient_user_ids
):
response = mocker.Mock()
mock_api_query = mocker.patch(
CONTROLLER + ".client.set_typing_status", return_value=response
)
model._user_settings["send_private_typing_notifications"] = True
model.send_typing_status_by_user_ids(recipient_user_ids, status=status)
mock_api_query.assert_called_once_with(
{"to": recipient_user_ids, "op": status},
)
self.display_error_if_present.assert_called_once_with(response, self.controller)
@pytest.mark.parametrize("status", ["start", "stop"])
def test_send_typing_status_with_no_recipients(
self, model, status, recipient_user_ids=[]
):
with pytest.raises(RuntimeError):
model.send_typing_status_by_user_ids(recipient_user_ids, status=status)
@pytest.mark.parametrize("recipient_user_ids", [[5140], [5140, 5179]])
@pytest.mark.parametrize("status", ["start", "stop"])
def test_send_typing_status_avoided_due_to_user_setting(
self, mocker, model, status, recipient_user_ids
):
model._user_settings["send_private_typing_notifications"] = False
mock_api_query = mocker.patch(CONTROLLER + ".client.set_typing_status")
model.send_typing_status_by_user_ids(recipient_user_ids, status=status)
assert not mock_api_query.called
assert not self.display_error_if_present.called
@pytest.mark.parametrize(
"response, return_value",
[
({"result": "success"}, True),
({"result": "some_failure"}, False),
],
)
@pytest.mark.parametrize("recipients", [[5179], [5179, 5180]])
def test_send_private_message(
self, mocker, model, recipients, response, return_value, content="hi!"
):
self.client.send_message = mocker.Mock(return_value=response)
result = model.send_private_message(recipients, content)
req = dict(type="private", to=recipients, content=content, read_by_sender=True)
self.client.send_message.assert_called_once_with(req)
assert result == return_value
self.display_error_if_present.assert_called_once_with(response, self.controller)
if result == "success":
self.notify_if_message_sent_outside_narrow.assert_called_once_with(
req, self.controller
)
def test_send_private_message_with_no_recipients(
self, model, content="hi!", recipients=[]
):
with pytest.raises(RuntimeError):
model.send_private_message(recipients, content)
@pytest.mark.parametrize(
"response, return_value",
[
({"result": "success"}, True),
({"result": "some_failure"}, False),
],
)
def test_send_stream_message(
self,
mocker,
model,
response,
return_value,
content="hi!",
stream="foo",
topic="bar",
):
self.client.send_message = mocker.Mock(return_value=response)
result = model.send_stream_message(stream, topic, content)
req = dict(
type="stream",
to=stream,
subject=topic,
content=content,
read_by_sender=True,
)
self.client.send_message.assert_called_once_with(req)
assert result == return_value
self.display_error_if_present.assert_called_once_with(response, self.controller)
if result == "success":
self.notify_if_message_sent_outside_narrow.assert_called_once_with(
req, self.controller
)
@pytest.mark.parametrize(
"response, return_value",
[
({"result": "success"}, True),
({"result": "some_failure"}, False),
],
)
def test_update_private_message(
self, mocker, model, response, return_value, content="hi!", msg_id=1
):
self.client.update_message = mocker.Mock(return_value=response)
result = model.update_private_message(msg_id, content)
req = dict(message_id=msg_id, content=content)
self.client.update_message.assert_called_once_with(req)
assert result == return_value
self.display_error_if_present.assert_called_once_with(response, self.controller)
@pytest.mark.parametrize(
"response, return_value",
[
case({"result": "success"}, True, id="API_success"),
case({"result": "some_failure"}, False, id="API_error"),
],
)
@pytest.mark.parametrize(
"kwargs, expected_report_success",
[
case(
{
"propagate_mode": "change_one",
"content": "hi!",
"topic": "old topic",
},
None, # None as footer is not updated.
id="topic_passed_but_same_so_not_changed:content_changed",
),
case(
{
"propagate_mode": "change_one",
"topic": "Topic change",
},
[
"You changed one message's topic from ",
("footer_contrast", f" stream {STREAM_TOPIC_SEPARATOR} "),
("footer_contrast", " old topic "),
" to ",
("footer_contrast", f" stream {STREAM_TOPIC_SEPARATOR} "),
("footer_contrast", " Topic change "),
" .",
],
id="topic_changed[one]",
),
case(
{
"propagate_mode": "change_all",
"topic": "old topic",
},
None, # None as footer is not updated.
id="topic_passed_but_same_so_not_changed[all]",
),
case(
{
"propagate_mode": "change_later",
"content": ":smile:",
"topic": "old topic",
},
None, # None as footer is not updated.
id="topic_passed_but_same_so_not_changed[later]:content_changed",
),
case(
{
"propagate_mode": "change_later",
"content": ":smile:",
"topic": "new_terminal",
},
[
"You changed some messages' topic from ",
("footer_contrast", f" stream {STREAM_TOPIC_SEPARATOR} "),
("footer_contrast", " old topic "),
" to ",
("footer_contrast", f" stream {STREAM_TOPIC_SEPARATOR} "),
("footer_contrast", " new_terminal "),
" .",
],
id="topic_changed[later]:content_changed",
),
case(
{
"propagate_mode": "change_one",
"content": "Hey!",
"topic": "grett",
},
[
"You changed one message's topic from ",
("footer_contrast", f" stream {STREAM_TOPIC_SEPARATOR} "),
("footer_contrast", " old topic "),
" to ",