test_classes: Rename and refactor 'tornado_redirected_to_list'.

This commit renames the 'tornado_redirected_to_list' context
manager to 'capture_send_event_calls' to improve readability.

It also refactors the function to yield a list of events
instead of passing in a list data structure as a parameter
and appending events to it.
This commit is contained in:
Prakhar Pratyush 2023-04-05 17:06:01 +05:30 committed by Tim Abbott
parent a62fcb1fd9
commit d96048b0af
16 changed files with 121 additions and 207 deletions

View File

@ -1692,10 +1692,10 @@ Output:
)
@contextmanager
def tornado_redirected_to_list(
self, lst: List[Mapping[str, Any]], expected_num_events: int
) -> Iterator[None]:
lst.clear()
def capture_send_event_calls(
self, expected_num_events: int
) -> Iterator[List[Mapping[str, Any]]]:
lst: List[Mapping[str, Any]] = []
# process_notification takes a single parameter called 'notice'.
# lst.append takes a single argument called 'object'.
@ -1711,7 +1711,7 @@ Output:
# never be sent in tests, and we would be unable to verify them. Hence, we use
# this helper to make sure the `send_event` calls actually run.
with self.captureOnCommitCallbacks(execute=True):
yield
yield lst
self.assert_length(lst, expected_num_events)

View File

@ -1,6 +1,6 @@
import filecmp
import os
from typing import Any, Dict, List, Mapping, Optional
from typing import Any, Dict, Optional
from unittest.mock import MagicMock, patch
import orjson
@ -163,8 +163,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
hamlet = self.example_user("hamlet")
self.login("hamlet")
self.assert_num_bots_equal(0)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.create_bot()
self.assert_num_bots_equal(1)
@ -330,8 +329,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
self.login_user(user)
self.assert_num_bots_equal(0)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.create_bot()
self.assert_num_bots_equal(1)
@ -384,8 +382,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
request_data = {
"principals": '["' + iago.email + '"]',
}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
result = self.common_subscribe_to_streams(hamlet, ["Rome"], request_data)
self.assert_json_success(result)
@ -401,8 +398,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
bot_request_data = {
"principals": '["hambot-bot@zulip.testserver"]',
}
events_bot: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events_bot, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events_bot:
result = self.common_subscribe_to_streams(hamlet, ["Rome"], bot_request_data)
self.assert_json_success(result)
@ -428,8 +424,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
)
self.assert_num_bots_equal(0)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.create_bot(default_sending_stream="Denmark")
self.assert_num_bots_equal(1)
self.assertEqual(result["default_sending_stream"], "Denmark")
@ -512,8 +507,7 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
)
self.assert_num_bots_equal(0)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.create_bot(default_events_register_stream="Denmark")
self.assert_num_bots_equal(1)
self.assertEqual(result["default_events_register_stream"], "Denmark")

View File

@ -1,5 +1,5 @@
import time
from typing import Any, Callable, Dict, List, Mapping, Optional
from typing import Any, Callable, Dict, List, Optional
from unittest import mock
from urllib.parse import urlsplit
@ -1367,8 +1367,7 @@ class TestUserPresenceUpdatesDisabled(ZulipTestCase):
# force_send_update is passed.
@override_settings(USER_LIMIT_FOR_SENDING_PRESENCE_UPDATE_EVENTS=3)
def test_presence_events_disabled_on_larger_realm(self) -> None:
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1):
do_update_user_presence(
self.example_user("cordelia"),
get_client("website"),
@ -1377,7 +1376,7 @@ class TestUserPresenceUpdatesDisabled(ZulipTestCase):
force_send_update=True,
)
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
do_update_user_presence(
self.example_user("hamlet"),
get_client("website"),

View File

@ -309,7 +309,7 @@ class BaseAction(ZulipTestCase):
# We want even those `send_event` calls which have been hooked to
# `transaction.on_commit` to execute in tests.
# See the comment in `ZulipTestCase.tornado_redirected_to_list`.
# See the comment in `ZulipTestCase.capture_send_event_calls`.
with self.captureOnCommitCallbacks(execute=True):
action()

View File

@ -1,5 +1,4 @@
import datetime
from typing import Any, List, Mapping
from unittest import mock
import orjson
@ -230,11 +229,8 @@ class TestFullStack(ZulipTestCase):
params = dict(status_text="on vacation")
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(cordelia, "/api/v1/users/me/status", params)
self.assert_json_success(result)

View File

@ -3900,7 +3900,7 @@ class DeleteMessageTest(ZulipTestCase):
self.send_stream_message(hamlet, "Denmark")
message = self.get_last_message()
with self.tornado_redirected_to_list([], expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1):
with mock.patch("zerver.actions.message_edit.send_event") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits."

View File

@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, Any, List, Mapping, Set
from typing import TYPE_CHECKING, Any, List, Set
from unittest import mock
import orjson
@ -322,8 +322,7 @@ class UnreadCountTests(ZulipTestCase):
self.example_user("hamlet"), "Denmark", "hello"
)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_post(
"/json/mark_stream_as_read",
{
@ -392,8 +391,7 @@ class UnreadCountTests(ZulipTestCase):
unrelated_message_id = self.send_stream_message(
self.example_user("hamlet"), "Denmark", "hello", "Denmark2"
)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_post(
"/json/mark_topic_as_read",
{
@ -1683,11 +1681,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -1756,11 +1751,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -1829,11 +1821,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -1958,8 +1947,7 @@ class MarkUnreadTest(ZulipTestCase):
# ones that already have UserMessage rows are already unread,
# and the others don't have UserMessage rows and cannot be
# marked as unread without first subscribing.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0) as events:
result = self.client_post(
"/json/messages/flags",
{"messages": orjson.dumps(message_ids).decode(), "op": "remove", "flag": "read"},
@ -1984,7 +1972,7 @@ class MarkUnreadTest(ZulipTestCase):
# have UserMessage rows will be ignored.
message_ids = before_subscribe_stream_message_ids + message_ids
self.login("hamlet")
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_post(
"/json/messages/flags",
{"messages": orjson.dumps(message_ids).decode(), "op": "add", "flag": "read"},
@ -2018,7 +2006,7 @@ class MarkUnreadTest(ZulipTestCase):
# This also create new 'historical' UserMessage rows for the
# messages in subscribed streams that didn't have them
# previously.
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_post(
"/json/messages/flags",
{"messages": orjson.dumps(message_ids).decode(), "op": "remove", "flag": "read"},
@ -2090,11 +2078,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -2160,11 +2145,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -2231,11 +2213,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)
@ -2297,11 +2276,8 @@ class MarkUnreadTest(ZulipTestCase):
"flag": "read",
}
events: List[Mapping[str, Any]] = []
# Use the tornado_redirected_to_list context manager to capture
# events.
with self.tornado_redirected_to_list(events, expected_num_events=1):
# Use the capture_send_event_calls context manager to capture events.
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(receiver, "/api/v1/messages/flags", params)
self.assert_json_success(result)

View File

@ -1,7 +1,7 @@
import datetime
import sys
from email.headerregistry import Address
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Set, Union
from typing import TYPE_CHECKING, Any, List, Optional, Set, Union
from unittest import mock
import orjson
@ -1682,8 +1682,7 @@ class StreamMessagesTest(ZulipTestCase):
)
def _send_stream_message(self, user: UserProfile, stream_name: str, content: str) -> Set[int]:
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
self.send_stream_message(
user,
stream_name,

View File

@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, Any, Dict, List, Mapping
from typing import TYPE_CHECKING, Any, Dict, List
from unittest import mock
import orjson
@ -443,8 +443,7 @@ class ReactionEventTest(ZulipTestCase):
"emoji_name": "smile",
}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info
)
@ -490,8 +489,7 @@ class ReactionEventTest(ZulipTestCase):
add = self.api_post(reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info)
self.assert_json_success(add)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_delete(
reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info
)
@ -528,8 +526,7 @@ class ReactionEventTest(ZulipTestCase):
# Hamlet and Polonius joined after the message was sent, and
# so only Iago should receive the event.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
iago, f"/api/v1/messages/{message_before_id}/reactions", reaction_info
)
@ -548,7 +545,7 @@ class ReactionEventTest(ZulipTestCase):
message_after_id = self.send_stream_message(
iago, "test_reactions_stream", "after subscription history private"
)
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
iago, f"/api/v1/messages/{message_after_id}/reactions", reaction_info
)
@ -573,7 +570,7 @@ class ReactionEventTest(ZulipTestCase):
# Since stream history is public to subscribers, reacting to
# message_before_id should notify all subscribers:
# Iago and Hamlet.
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
iago, f"/api/v1/messages/{message_before_id}/reactions", reaction_info
)
@ -597,7 +594,7 @@ class ReactionEventTest(ZulipTestCase):
)
# For is_web_public streams, events even on old messages
# should go to all subscribers, including guests like polonius.
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
iago, f"/api/v1/messages/{message_before_id}/reactions", reaction_info
)
@ -617,7 +614,7 @@ class ReactionEventTest(ZulipTestCase):
hamlet,
"hello to single receiver",
)
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
hamlet, f"/api/v1/messages/{private_message_id}/reactions", reaction_info
)
@ -633,7 +630,7 @@ class ReactionEventTest(ZulipTestCase):
[polonius, iago],
"hello message to multiple receiver",
)
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
polonius, f"/api/v1/messages/{huddle_message_id}/reactions", reaction_info
)
@ -1062,8 +1059,7 @@ class ReactionAPIEventTest(EmojiReactionBase):
"emoji_code": "1f354",
"reaction_type": "unicode_emoji",
}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
with mock.patch("zerver.actions.reactions.send_event") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits!"
@ -1106,8 +1102,7 @@ class ReactionAPIEventTest(EmojiReactionBase):
)
self.assert_json_success(add)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_delete(
reaction_sender,
f"/api/v1/messages/{pm_id}/reactions",
@ -1147,7 +1142,7 @@ class ReactionAPIEventTest(EmojiReactionBase):
reaction_type="whatever",
)
with self.tornado_redirected_to_list([], expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1):
with mock.patch("zerver.actions.reactions.send_event") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits."

View File

@ -2,7 +2,7 @@ import datetime
import os
import re
from datetime import timedelta
from typing import Any, Dict, List, Mapping, Union
from typing import Any, Dict, List, Union
from unittest import mock
import orjson
@ -136,8 +136,7 @@ class RealmTest(ZulipTestCase):
def test_update_realm_name_events(self) -> None:
realm = get_realm("zulip")
new_name = "Puliz"
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
do_set_realm_property(realm, "name", new_name, acting_user=None)
event = events[0]["event"]
self.assertEqual(
@ -153,8 +152,7 @@ class RealmTest(ZulipTestCase):
def test_update_realm_description_events(self) -> None:
realm = get_realm("zulip")
new_description = "zulip dev group"
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
do_set_realm_property(realm, "description", new_description, acting_user=None)
event = events[0]["event"]
self.assertEqual(
@ -171,8 +169,7 @@ class RealmTest(ZulipTestCase):
self.login("iago")
new_description = "zulip dev group"
data = dict(description=new_description)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_patch("/json/realm", data)
self.assert_json_success(result)
realm = get_realm("zulip")

View File

@ -1,4 +1,4 @@
from typing import Any, Dict, List, Mapping
from typing import Any, Dict, List
from unittest import mock
from zerver.actions.submessage import do_add_submessage
@ -151,8 +151,7 @@ class TestBasics(ZulipTestCase):
msg_type="whatever",
content='{"name": "alice", "salary": 20}',
)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_post("/json/submessage", payload)
self.assert_json_success(result)
@ -195,7 +194,7 @@ class TestBasics(ZulipTestCase):
hamlet = self.example_user("hamlet")
message_id = self.send_stream_message(hamlet, "Denmark")
with self.tornado_redirected_to_list([], expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1):
with mock.patch("zerver.actions.submessage.send_event") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits."

View File

@ -2,7 +2,7 @@ import hashlib
import random
from datetime import timedelta
from io import StringIO
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Set, Union
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Set, Union
from unittest import mock
import orjson
@ -247,8 +247,7 @@ class TestCreateStreams(ZulipTestCase):
realm = get_realm("zulip")
# Test stream creation events.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
ensure_stream(realm, "Public stream", invite_only=False, acting_user=None)
self.assertEqual(events[0]["event"]["type"], "stream")
@ -257,7 +256,7 @@ class TestCreateStreams(ZulipTestCase):
self.assertEqual(events[0]["users"], active_non_guest_user_ids(realm.id))
self.assertEqual(events[0]["event"]["streams"][0]["name"], "Public stream")
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
ensure_stream(realm, "Private stream", invite_only=True, acting_user=None)
self.assertEqual(events[0]["event"]["type"], "stream")
@ -1356,8 +1355,7 @@ class StreamAdminTest(ZulipTestCase):
self.subscribe(user_profile, "private_stream")
self.subscribe(self.example_user("cordelia"), "private_stream")
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
stream_id = get_stream("private_stream", user_profile.realm).id
result = self.client_patch(
f"/json/streams/{stream_id}",
@ -1374,7 +1372,7 @@ class StreamAdminTest(ZulipTestCase):
self.assertNotIn(prospero.id, notified_user_ids)
# Three events should be sent: a name event, an email address event and a notification event
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = get_stream("private_stream", user_profile.realm).id
result = self.client_patch(f"/json/streams/{stream_id}", {"new_name": "whatever"})
self.assert_json_success(result)
@ -1411,8 +1409,7 @@ class StreamAdminTest(ZulipTestCase):
self.assert_json_success(result)
# Three events should be sent: stream_email update, stream_name update and notification message.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = get_stream("stream_name1", user_profile.realm).id
result = self.client_patch(f"/json/streams/{stream_id}", {"new_name": "stream_name2"})
self.assert_json_success(result)
@ -1442,7 +1439,7 @@ class StreamAdminTest(ZulipTestCase):
# Test case to handle Unicode stream name change
# *NOTE: Here encoding is needed when Unicode string is passed as an argument*
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = stream_name2_exists.id
result = self.client_patch(f"/json/streams/{stream_id}", {"new_name": "नया नाम"})
self.assert_json_success(result)
@ -1453,7 +1450,7 @@ class StreamAdminTest(ZulipTestCase):
# Test case to handle changing of Unicode stream name to newer name
# NOTE: Unicode string being part of URL is handled cleanly
# by client_patch call, encoding of URL is not needed.
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = stream_name_uni_exists.id
result = self.client_patch(
f"/json/streams/{stream_id}",
@ -1467,7 +1464,7 @@ class StreamAdminTest(ZulipTestCase):
self.assertTrue(stream_name_new_uni_exists)
# Test case to change name from one language to other.
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = stream_name_new_uni_exists.id
result = self.client_patch(f"/json/streams/{stream_id}", {"new_name": "français"})
self.assert_json_success(result)
@ -1475,7 +1472,7 @@ class StreamAdminTest(ZulipTestCase):
self.assertTrue(stream_name_fr_exists)
# Test case to change name to mixed language name.
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = stream_name_fr_exists.id
result = self.client_patch(f"/json/streams/{stream_id}", {"new_name": "français name"})
self.assert_json_success(result)
@ -1487,7 +1484,7 @@ class StreamAdminTest(ZulipTestCase):
"stream_private_name1", realm=user_profile.realm, invite_only=True
)
self.subscribe(self.example_user("cordelia"), "stream_private_name1")
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
stream_id = get_stream("stream_private_name1", realm).id
result = self.client_patch(
f"/json/streams/{stream_id}",
@ -1607,8 +1604,7 @@ class StreamAdminTest(ZulipTestCase):
realm = user_profile.realm
self.subscribe(user_profile, "stream_name1")
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
stream_id = get_stream("stream_name1", realm).id
result = self.client_patch(
f"/json/streams/{stream_id}",
@ -1947,8 +1943,7 @@ class StreamAdminTest(ZulipTestCase):
self.assert_json_error(result, "Available on Zulip Cloud Standard. Upgrade to access.")
do_change_realm_plan_type(realm, Realm.PLAN_TYPE_SELF_HOSTED, acting_user=None)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.client_patch(
f"/json/streams/{stream.id}", {"message_retention_days": orjson.dumps(2).decode()}
)
@ -1975,7 +1970,7 @@ class StreamAdminTest(ZulipTestCase):
self.assertNotIn(self.example_user("polonius").id, notified_user_ids)
self.assertEqual(stream.message_retention_days, 2)
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.client_patch(
f"/json/streams/{stream.id}",
{"message_retention_days": orjson.dumps("unlimited").decode()},
@ -1997,7 +1992,7 @@ class StreamAdminTest(ZulipTestCase):
stream = get_stream("stream_name1", realm)
self.assertEqual(stream.message_retention_days, -1)
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.client_patch(
f"/json/streams/{stream.id}",
{"message_retention_days": orjson.dumps("realm_default").decode()},
@ -2234,8 +2229,7 @@ class StreamAdminTest(ZulipTestCase):
# Since we do not know the id of these simulated stream we prepend the name with a random hashed_stream_id
ensure_stream(realm, "DB32B77!DEACTIVATED:" + active_name, acting_user=None)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.client_delete("/json/streams/" + str(stream_id))
self.assert_json_success(result)
@ -3255,9 +3249,8 @@ class SubscriptionPropertiesTest(ZulipTestCase):
)
self.assertEqual(sub.is_muted, False)
events: List[Mapping[str, Any]] = []
property_name = "is_muted"
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.api_post(
test_user,
"/api/v1/users/me/subscriptions/properties",
@ -3286,7 +3279,7 @@ class SubscriptionPropertiesTest(ZulipTestCase):
self.assertEqual(sub.is_muted, True)
legacy_property_name = "in_home_view"
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.api_post(
test_user,
"/api/v1/users/me/subscriptions/properties",
@ -3315,7 +3308,7 @@ class SubscriptionPropertiesTest(ZulipTestCase):
)
self.assertEqual(sub.is_muted, False)
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
result = self.api_post(
test_user,
"/api/v1/users/me/subscriptions/properties",
@ -3878,8 +3871,7 @@ class SubscriptionAPITest(ZulipTestCase):
add_streams = ["Verona2", "Denmark5"]
self.assertNotEqual(len(add_streams), 0) # necessary for full test coverage
# Three events should be sent for each stream for stream creation, subscription add and message notifications.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=6):
with self.capture_send_event_calls(expected_num_events=6):
self.helper_check_subs_before_and_after_add(
self.streams + add_streams,
{},
@ -3901,7 +3893,6 @@ class SubscriptionAPITest(ZulipTestCase):
self.assertNotEqual(len(self.streams), 0)
add_streams = ["Verona2", "Denmark5"]
self.assertNotEqual(len(add_streams), 0)
events: List[Mapping[str, Any]] = []
other_params = {
"announce": "true",
}
@ -3909,7 +3900,7 @@ class SubscriptionAPITest(ZulipTestCase):
self.test_realm.notifications_stream_id = notifications_stream.id
self.test_realm.save()
with self.tornado_redirected_to_list(events, expected_num_events=7):
with self.capture_send_event_calls(expected_num_events=7) as events:
self.helper_check_subs_before_and_after_add(
self.streams + add_streams,
other_params,
@ -4374,9 +4365,8 @@ class SubscriptionAPITest(ZulipTestCase):
user2 = self.example_user("iago")
realm = get_realm("zulip")
streams_to_sub = ["multi_user_stream"]
events: List[Mapping[str, Any]] = []
flush_per_request_caches()
with self.tornado_redirected_to_list(events, expected_num_events=5):
with self.capture_send_event_calls(expected_num_events=5) as events:
with self.assert_database_query_count(36):
self.common_subscribe_to_streams(
self.test_user,
@ -4400,7 +4390,7 @@ class SubscriptionAPITest(ZulipTestCase):
self.assertEqual(num_subscribers_for_stream_id(stream.id), 2)
# Now add ourselves
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
with self.assert_database_query_count(13):
self.common_subscribe_to_streams(
self.test_user,
@ -4433,7 +4423,7 @@ class SubscriptionAPITest(ZulipTestCase):
user3 = user_profile
realm3 = user_profile.realm
stream = get_stream("multi_user_stream", realm)
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
bulk_add_subscriptions(realm, [stream], [user_profile], acting_user=None)
add_event, add_peer_event = events
@ -4467,8 +4457,7 @@ class SubscriptionAPITest(ZulipTestCase):
# Now subscribe Cordelia to the stream, capturing events
user_profile = self.example_user("cordelia")
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=3):
with self.capture_send_event_calls(expected_num_events=3) as events:
bulk_add_subscriptions(realm, [stream], [user_profile], acting_user=None)
create_event, add_event, add_peer_event = events
@ -4498,7 +4487,7 @@ class SubscriptionAPITest(ZulipTestCase):
# even if realm admin is subscribed to stream cause realm admin already get
# private stream creation event on stream creation.
new_stream = ensure_stream(realm, "private stream", invite_only=True, acting_user=None)
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
bulk_add_subscriptions(
realm, [new_stream], [self.example_user("iago")], acting_user=None
)
@ -4614,8 +4603,7 @@ class SubscriptionAPITest(ZulipTestCase):
)
new_user_ids_to_subscribe = [iago.id, cordelia.id]
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=5):
with self.capture_send_event_calls(expected_num_events=5) as events:
self.common_subscribe_to_streams(
self.test_user,
streams_to_sub,
@ -4666,8 +4654,7 @@ class SubscriptionAPITest(ZulipTestCase):
self.subscribe(user3, "private_stream")
# Sends 3 peer-remove events and 2 unsubscribe events.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=5):
with self.capture_send_event_calls(expected_num_events=5) as events:
with self.assert_database_query_count(16):
with cache_tries_captured() as cache_count:
bulk_remove_subscriptions(
@ -4724,8 +4711,7 @@ class SubscriptionAPITest(ZulipTestCase):
# Make sure Zephyr mirroring realms such as MIT do not get
# any tornado subscription events
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
with self.assert_database_query_count(5):
self.common_subscribe_to_streams(
mit_user,
@ -4735,7 +4721,7 @@ class SubscriptionAPITest(ZulipTestCase):
allow_fail=True,
)
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
bulk_remove_subscriptions(
realm,
users=[mit_user],

View File

@ -1,5 +1,3 @@
from typing import Any, List, Mapping
import orjson
from zerver.lib.test_classes import ZulipTestCase
@ -146,9 +144,8 @@ class TypingHappyPathTestPMs(ZulipTestCase):
op="start",
)
events: List[Mapping[str, Any]] = []
with self.assert_database_query_count(4):
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
@ -176,15 +173,13 @@ class TypingHappyPathTestPMs(ZulipTestCase):
huddle_hash = get_huddle_hash(list(expected_recipient_ids))
self.assertFalse(Huddle.objects.filter(huddle_hash=huddle_hash).exists())
events: List[Mapping[str, Any]] = []
params = dict(
to=orjson.dumps([user.id for user in recipient_users]).decode(),
op="start",
)
with self.assert_database_query_count(5):
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
self.assert_length(events, 1)
@ -215,8 +210,7 @@ class TypingHappyPathTestPMs(ZulipTestCase):
email = user.email
expected_recipient_emails = {email}
expected_recipient_ids = {user.id}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(
user,
"/api/v1/typing",
@ -256,8 +250,7 @@ class TypingHappyPathTestPMs(ZulipTestCase):
op="start",
)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
@ -285,8 +278,7 @@ class TypingHappyPathTestPMs(ZulipTestCase):
expected_recipient_emails = {email}
expected_recipient_ids = {user.id}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
params = dict(
to=orjson.dumps([user.id]).decode(),
op="stop",
@ -319,8 +311,7 @@ class TypingHappyPathTestPMs(ZulipTestCase):
expected_recipient_emails = {user.email for user in expected_recipients}
expected_recipient_ids = {user.id for user in expected_recipients}
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
params = dict(
to=orjson.dumps([recipient.id]).decode(),
op="stop",
@ -362,9 +353,8 @@ class TypingHappyPathTestStreams(ZulipTestCase):
topic=topic,
)
events: List[Mapping[str, Any]] = []
with self.assert_database_query_count(5):
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
self.assert_length(events, 1)
@ -397,9 +387,8 @@ class TypingHappyPathTestStreams(ZulipTestCase):
topic=topic,
)
events: List[Mapping[str, Any]] = []
with self.assert_database_query_count(5):
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
self.assert_length(events, 1)
@ -430,8 +419,7 @@ class TestSendTypingNotificationsSettings(ZulipTestCase):
# Test typing events sent when `send_private_typing_notifications` set to `True`.
self.assertTrue(sender.send_private_typing_notifications)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
@ -444,8 +432,7 @@ class TestSendTypingNotificationsSettings(ZulipTestCase):
sender.save()
# No events should be sent now
events = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_error(result, "User has disabled typing notifications for direct messages")
@ -472,8 +459,7 @@ class TestSendTypingNotificationsSettings(ZulipTestCase):
# Test typing events sent when `send_stream_typing_notifications` set to `True`.
self.assertTrue(sender.send_stream_typing_notifications)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=1):
with self.capture_send_event_calls(expected_num_events=1) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_success(result)
self.assert_length(events, 1)
@ -485,8 +471,7 @@ class TestSendTypingNotificationsSettings(ZulipTestCase):
sender.save()
# No events should be sent now
events = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0) as events:
result = self.api_post(sender, "/api/v1/typing", params)
self.assert_json_error(result, "User has disabled typing notifications for stream messages")
self.assertEqual(events, [])

View File

@ -1,4 +1,4 @@
from typing import Any, Dict, List, Mapping
from typing import Any, Dict
import orjson
@ -118,8 +118,7 @@ class UserStatusTest(ZulipTestCase):
def update_status_and_assert_event(
self, payload: Dict[str, Any], expected_event: Dict[str, Any], num_events: int = 1
) -> None:
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=num_events):
with self.capture_send_event_calls(expected_num_events=num_events) as events:
result = self.client_post("/json/users/me/status", payload)
self.assert_json_success(result)
self.assertEqual(events[0]["event"], expected_event)

View File

@ -1,5 +1,5 @@
from datetime import datetime, timezone
from typing import Any, Dict, List, Mapping
from typing import Any, Dict, List
import time_machine
from django.utils.timezone import now as timezone_now
@ -323,8 +323,7 @@ class MutedTopicsTests(ZulipTestCase):
mock_date_muted = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc), tick=False):
result = self.api_post(user, url, data)
self.assert_json_success(result)
@ -390,8 +389,7 @@ class MutedTopicsTests(ZulipTestCase):
mock_date_mute_removed = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc), tick=False):
result = self.api_post(user, url, data)
self.assert_json_success(result)
@ -518,8 +516,7 @@ class UnmutedTopicsTests(ZulipTestCase):
mock_date_unmuted = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc), tick=False):
result = self.api_post(user, url, data)
self.assert_json_success(result)
@ -585,8 +582,7 @@ class UnmutedTopicsTests(ZulipTestCase):
mock_date_unmute_removed = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=2):
with self.capture_send_event_calls(expected_num_events=2) as events:
with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc), tick=False):
result = self.api_post(user, url, data)
self.assert_json_success(result)

View File

@ -1,6 +1,6 @@
import datetime
from email.headerregistry import Address
from typing import Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union
from typing import Any, Dict, Iterable, List, Optional, TypeVar, Union
from unittest import mock
import orjson
@ -213,8 +213,7 @@ class PermissionTest(ZulipTestCase):
self.assertFalse(othello_dict["is_owner"])
req = dict(role=UserProfile.ROLE_REALM_OWNER)
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.client_patch(f"/json/users/{othello.id}", req)
self.assert_json_success(result)
owner_users = realm.get_human_owner_users()
@ -224,7 +223,7 @@ class PermissionTest(ZulipTestCase):
self.assertEqual(person["role"], UserProfile.ROLE_REALM_OWNER)
req = dict(role=UserProfile.ROLE_MEMBER)
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.client_patch(f"/json/users/{othello.id}", req)
self.assert_json_success(result)
owner_users = realm.get_human_owner_users()
@ -236,7 +235,7 @@ class PermissionTest(ZulipTestCase):
# Cannot take away from last owner
self.login("desdemona")
req = dict(role=UserProfile.ROLE_MEMBER)
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.client_patch(f"/json/users/{iago.id}", req)
self.assert_json_success(result)
owner_users = realm.get_human_owner_users()
@ -244,7 +243,7 @@ class PermissionTest(ZulipTestCase):
person = events[0]["event"]["person"]
self.assertEqual(person["user_id"], iago.id)
self.assertEqual(person["role"], UserProfile.ROLE_MEMBER)
with self.tornado_redirected_to_list([], expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
result = self.client_patch(f"/json/users/{desdemona.id}", req)
self.assert_json_error(
result, "The owner permission cannot be removed from the only organization owner."
@ -252,7 +251,7 @@ class PermissionTest(ZulipTestCase):
do_change_user_role(iago, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)
self.login("iago")
with self.tornado_redirected_to_list([], expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
result = self.client_patch(f"/json/users/{desdemona.id}", req)
self.assert_json_error(result, "Must be an organization owner")
@ -275,8 +274,7 @@ class PermissionTest(ZulipTestCase):
# Giveth
req = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode())
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.client_patch(f"/json/users/{othello.id}", req)
self.assert_json_success(result)
admin_users = realm.get_human_admin_users()
@ -287,7 +285,7 @@ class PermissionTest(ZulipTestCase):
# Taketh away
req = dict(role=orjson.dumps(UserProfile.ROLE_MEMBER).decode())
with self.tornado_redirected_to_list(events, expected_num_events=4):
with self.capture_send_event_calls(expected_num_events=4) as events:
result = self.client_patch(f"/json/users/{othello.id}", req)
self.assert_json_success(result)
admin_users = realm.get_human_admin_users()
@ -513,11 +511,10 @@ class PermissionTest(ZulipTestCase):
)
req = dict(role=orjson.dumps(new_role).decode())
events: List[Mapping[str, Any]] = []
num_events = 3
if UserProfile.ROLE_MEMBER in [old_role, new_role]:
num_events = 4
with self.tornado_redirected_to_list(events, expected_num_events=num_events):
with self.capture_send_event_calls(expected_num_events=num_events) as events:
result = self.client_patch(f"/json/users/{user_profile.id}", req)
self.assert_json_success(result)
@ -789,11 +786,9 @@ class QueryCountTest(ZulipTestCase):
prereg_user = PreregistrationUser.objects.get(email="fred@zulip.com")
events: List[Mapping[str, Any]] = []
with self.assert_database_query_count(88):
with cache_tries_captured() as cache_tries:
with self.tornado_redirected_to_list(events, expected_num_events=11):
with self.capture_send_event_calls(expected_num_events=11) as events:
fred = do_create_user(
email="fred@zulip.com",
password="password",
@ -1192,8 +1187,7 @@ class UserProfileTest(ZulipTestCase):
# users; this work is happening before the user account is
# created, so any changes will be reflected in the "add" event
# introducing the user to clients.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
copy_default_settings(cordelia, iago)
# We verify that cordelia and iago match, but hamlet has the defaults.
@ -1249,8 +1243,7 @@ class UserProfileTest(ZulipTestCase):
# users; this work is happening before the user account is
# created, so any changes will be reflected in the "add" event
# introducing the user to clients.
events: List[Mapping[str, Any]] = []
with self.tornado_redirected_to_list(events, expected_num_events=0):
with self.capture_send_event_calls(expected_num_events=0):
copy_default_settings(realm_user_default, cordelia)
self.assertEqual(cordelia.default_view, "recent_topics")