Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

subscriptions: Improve types for subscription info.

Steve Howellf9ddd8012215
diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py
index a0c74ab7b2c..784c0577dcb 100644
--- a/zerver/lib/actions.py
+++ b/zerver/lib/actions.py
@@ -77,7 +77,7 @@ from zerver.lib.cache import (
user_profile_delivery_email_cache_key,
)
from zerver.lib.create_user import create_user, get_display_email_address
-from zerver.lib.email_mirror_helpers import encode_email_address, encode_email_address_helper
+from zerver.lib.email_mirror_helpers import encode_email_address
from zerver.lib.email_notifications import enqueue_welcome_emails
from zerver.lib.email_validation import (
email_reserved_for_system_bots_error,
@@ -129,7 +129,7 @@ from zerver.lib.send_email import (
from zerver.lib.server_initialization import create_internal_realm, server_initialized
from zerver.lib.sessions import delete_user_sessions
from zerver.lib.storage import static_path
-from zerver.lib.stream_color import STREAM_ASSIGNMENT_COLORS, pick_colors
+from zerver.lib.stream_color import pick_colors
from zerver.lib.stream_subscription import (
SubInfo,
bulk_get_private_peers,
@@ -160,6 +160,7 @@ from zerver.lib.streams import (
subscribed_to_stream,
)
from zerver.lib.string_validation import check_stream_name, check_stream_topic
+from zerver.lib.subscription_info import build_stream_dict_for_never_sub, build_stream_dict_for_sub
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
from zerver.lib.timezone import canonicalize_timezone
from zerver.lib.topic import (
@@ -176,8 +177,13 @@ from zerver.lib.topic import (
)
from zerver.lib.types import (
EditHistoryEvent,
+ NeverSubscribedStreamDict,
ProfileDataElementValue,
ProfileFieldData,
+ RawStreamDict,
+ RawSubscriptionDict,
+ SubscriptionInfo,
+ SubscriptionStreamDict,
UnspecifiedValue,
)
from zerver.lib.upload import (
@@ -277,17 +283,6 @@ if settings.BILLING_ENABLED:
)
-@dataclass
-class SubscriptionInfo:
- subscriptions: List[Dict[str, Any]]
- unsubscribed: List[Dict[str, Any]]
- never_subscribed: List[Dict[str, Any]]
-
-
-# These are hard to type-check because of the API_FIELDS loops.
-RawStreamDict = Dict[str, Any]
-RawSubscriptionDict = Dict[str, Any]
-
ONBOARDING_TOTAL_MESSAGES = 1000
ONBOARDING_UNREAD_MESSAGES = 20
ONBOARDING_RECENT_TIMEDELTA = datetime.timedelta(weeks=1)
@@ -7108,115 +7103,6 @@ def do_delete_messages_by_sender(user: UserProfile) -> None:
move_messages_to_archive(message_ids, chunk_size=retention.STREAM_MESSAGE_BATCH_SIZE)
-def get_web_public_subs(realm: Realm) -> SubscriptionInfo:
- color_idx = 0
-
- def get_next_color() -> str:
- nonlocal color_idx
- color = STREAM_ASSIGNMENT_COLORS[color_idx]
- color_idx = (color_idx + 1) % len(STREAM_ASSIGNMENT_COLORS)
- return color
-
- subscribed = []
- for stream in get_web_public_streams_queryset(realm):
- stream_dict = stream.to_dict()
-
- # Add versions of the Subscription fields based on a simulated
- # new user subscription set.
- stream_dict["is_muted"] = False
- stream_dict["color"] = get_next_color()
- stream_dict["desktop_notifications"] = True
- stream_dict["audible_notifications"] = True
- stream_dict["push_notifications"] = True
- stream_dict["email_notifications"] = True
- stream_dict["pin_to_top"] = False
- stream_weekly_traffic = get_average_weekly_stream_traffic(
- stream.id, stream.date_created, {}
- )
- stream_dict["stream_weekly_traffic"] = stream_weekly_traffic
- stream_dict["email_address"] = ""
- subscribed.append(stream_dict)
-
- return SubscriptionInfo(
- subscriptions=subscribed,
- unsubscribed=[],
- never_subscribed=[],
- )
-
-
-def build_stream_dict_for_sub(
- user: UserProfile,
- sub_dict: RawSubscriptionDict,
- raw_stream_dict: RawStreamDict,
- recent_traffic: Dict[int, int],
-) -> Dict[str, object]:
- # We first construct a dictionary based on the standard Stream
- # and Subscription models' API_FIELDS.
- result = {}
- for field_name in Stream.API_FIELDS:
- if field_name == "id":
- result["stream_id"] = raw_stream_dict["id"]
- continue
- elif field_name == "date_created":
- result["date_created"] = datetime_to_timestamp(raw_stream_dict[field_name])
- continue
- result[field_name] = raw_stream_dict[field_name]
-
- # Copy Subscription.API_FIELDS.
- for field_name in Subscription.API_FIELDS:
- result[field_name] = sub_dict[field_name]
-
- # Backwards-compatibility for clients that haven't been
- # updated for the in_home_view => is_muted API migration.
- result["in_home_view"] = not result["is_muted"]
-
- # Backwards-compatibility for clients that haven't been
- # updated for the is_announcement_only -> stream_post_policy
- # migration.
- result["is_announcement_only"] = (
- raw_stream_dict["stream_post_policy"] == Stream.STREAM_POST_POLICY_ADMINS
- )
-
- # Add a few computed fields not directly from the data models.
- result["stream_weekly_traffic"] = get_average_weekly_stream_traffic(
- raw_stream_dict["id"], raw_stream_dict["date_created"], recent_traffic
- )
-
- result["email_address"] = encode_email_address_helper(
- raw_stream_dict["name"], raw_stream_dict["email_token"], show_sender=True
- )
-
- # Our caller may add a subscribers field.
- return result
-
-
-def build_stream_dict_for_never_sub(
- raw_stream_dict: RawStreamDict,
- recent_traffic: Dict[int, int],
-) -> Dict[str, object]:
- result = {}
- for field_name in Stream.API_FIELDS:
- if field_name == "id":
- result["stream_id"] = raw_stream_dict["id"]
- continue
- elif field_name == "date_created":
- result["date_created"] = datetime_to_timestamp(raw_stream_dict[field_name])
- continue
- result[field_name] = raw_stream_dict[field_name]
-
- result["stream_weekly_traffic"] = get_average_weekly_stream_traffic(
- raw_stream_dict["id"], raw_stream_dict["date_created"], recent_traffic
- )
-
- # Backwards-compatibility addition of removed field.
- result["is_announcement_only"] = (
- raw_stream_dict["stream_post_policy"] == Stream.STREAM_POST_POLICY_ADMINS
- )
-
- # Our caller may add a subscribers field.
- return result
-
-
# In general, it's better to avoid using .values() because it makes
# the code pretty ugly, but in this case, it has significant
# performance impact for loading / for users with large numbers of
@@ -7265,9 +7151,9 @@ def gather_subscriptions_helper(
# Okay, now we finally get to populating our main results, which
# will be these three lists.
- subscribed = []
- unsubscribed = []
- never_subscribed = []
+ subscribed: List[SubscriptionStreamDict] = []
+ unsubscribed: List[SubscriptionStreamDict] = []
+ never_subscribed: List[NeverSubscribedStreamDict] = []
sub_unsub_stream_ids = set()
for sub_dict in sub_dicts:
@@ -7302,11 +7188,11 @@ def gather_subscriptions_helper(
for raw_stream_dict in never_subscribed_streams:
is_public = not raw_stream_dict["invite_only"]
if is_public or user_profile.is_realm_admin:
- stream_dict = build_stream_dict_for_never_sub(
+ slim_stream_dict = build_stream_dict_for_never_sub(
raw_stream_dict=raw_stream_dict, recent_traffic=recent_traffic
)
- never_subscribed.append(stream_dict)
+ never_subscribed.append(slim_stream_dict)
if include_subscribers:
# The highly optimized bulk_get_subscriber_user_ids wants to know which
@@ -7322,23 +7208,32 @@ def gather_subscriptions_helper(
subscribed_stream_ids,
)
- for lst in [subscribed, unsubscribed, never_subscribed]:
+ for lst in [subscribed, unsubscribed]:
for stream_dict in lst:
assert isinstance(stream_dict["stream_id"], int)
stream_id = stream_dict["stream_id"]
stream_dict["subscribers"] = subscriber_map[stream_id]
+ for slim_stream_dict in never_subscribed:
+ assert isinstance(slim_stream_dict["stream_id"], int)
+ stream_id = slim_stream_dict["stream_id"]
+ slim_stream_dict["subscribers"] = subscriber_map[stream_id]
+
+ subscribed.sort(key=lambda x: x["name"])
+ unsubscribed.sort(key=lambda x: x["name"])
+ never_subscribed.sort(key=lambda x: x["name"])
+
return SubscriptionInfo(
- subscriptions=sorted(subscribed, key=lambda x: x["name"]),
- unsubscribed=sorted(unsubscribed, key=lambda x: x["name"]),
- never_subscribed=sorted(never_subscribed, key=lambda x: x["name"]),
+ subscriptions=subscribed,
+ unsubscribed=unsubscribed,
+ never_subscribed=never_subscribed,
)
def gather_subscriptions(
user_profile: UserProfile,
include_subscribers: bool = False,
-) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
+) -> Tuple[List[SubscriptionStreamDict], List[SubscriptionStreamDict]]:
helper_result = gather_subscriptions_helper(
user_profile,
include_subscribers=include_subscribers,
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index b4a2a285a21..c5d50c9f2d5 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -16,7 +16,6 @@ from zerver.lib.actions import (
get_default_streams_for_realm,
get_owned_bot_dicts,
get_web_public_streams,
- get_web_public_subs,
streams_to_dicts_sorted,
)
from zerver.lib.alert_words import user_alert_words
@@ -44,6 +43,7 @@ from zerver.lib.realm_icon import realm_icon_url
from zerver.lib.realm_logo import get_realm_logo_source, get_realm_logo_url
from zerver.lib.soft_deactivation import reactivate_user_if_soft_deactivated
from zerver.lib.stream_subscription import handle_stream_notifications_compatibility
+from zerver.lib.subscription_info import get_web_public_subs
from zerver.lib.timestamp import datetime_to_timestamp
from zerver.lib.timezone import canonicalize_timezone
from zerver.lib.topic import TOPIC_NAME
diff --git a/zerver/lib/subscription_info.py b/zerver/lib/subscription_info.py
new file mode 100644
index 00000000000..bf15968ca40
--- /dev/null
+++ b/zerver/lib/subscription_info.py
@@ -0,0 +1,209 @@
+from typing import Dict
+
+from zerver.lib.email_mirror_helpers import encode_email_address_helper
+from zerver.lib.stream_color import STREAM_ASSIGNMENT_COLORS
+from zerver.lib.stream_traffic import get_average_weekly_stream_traffic
+from zerver.lib.streams import get_web_public_streams_queryset
+from zerver.lib.timestamp import datetime_to_timestamp
+from zerver.lib.types import (
+ NeverSubscribedStreamDict,
+ RawStreamDict,
+ RawSubscriptionDict,
+ SubscriptionInfo,
+ SubscriptionStreamDict,
+)
+from zerver.models import Realm, Stream, Subscription, UserProfile
+
+
+def get_web_public_subs(realm: Realm) -> SubscriptionInfo:
+ color_idx = 0
+
+ def get_next_color() -> str:
+ nonlocal color_idx
+ color = STREAM_ASSIGNMENT_COLORS[color_idx]
+ color_idx = (color_idx + 1) % len(STREAM_ASSIGNMENT_COLORS)
+ return color
+
+ subscribed = []
+ for stream in get_web_public_streams_queryset(realm):
+ # Add Stream fields.
+ date_created = datetime_to_timestamp(stream.date_created)
+ description = stream.description
+ first_message_id = stream.first_message_id
+ history_public_to_subscribers = stream.history_public_to_subscribers
+ invite_only = stream.invite_only
+ is_announcement_only = stream.stream_post_policy == Stream.STREAM_POST_POLICY_ADMINS
+ is_web_public = stream.is_web_public
+ message_retention_days = stream.message_retention_days
+ name = stream.name
+ rendered_description = stream.rendered_description
+ stream_id = stream.id
+ stream_post_policy = stream.stream_post_policy
+
+ # Add versions of the Subscription fields based on a simulated
+ # new user subscription set.
+ audible_notifications = True
+ color = get_next_color()
+ desktop_notifications = True
+ email_address = ""
+ email_notifications = True
+ in_home_view = True
+ is_muted = False
+ pin_to_top = False
+ push_notifications = True
+ role = Subscription.ROLE_MEMBER
+ stream_weekly_traffic = get_average_weekly_stream_traffic(
+ stream.id, stream.date_created, {}
+ )
+ wildcard_mentions_notify = True
+
+ sub = SubscriptionStreamDict(
+ audible_notifications=audible_notifications,
+ color=color,
+ date_created=date_created,
+ description=description,
+ desktop_notifications=desktop_notifications,
+ email_address=email_address,
+ email_notifications=email_notifications,
+ first_message_id=first_message_id,
+ history_public_to_subscribers=history_public_to_subscribers,
+ in_home_view=in_home_view,
+ invite_only=invite_only,
+ is_announcement_only=is_announcement_only,
+ is_muted=is_muted,
+ is_web_public=is_web_public,
+ message_retention_days=message_retention_days,
+ name=name,
+ pin_to_top=pin_to_top,
+ push_notifications=push_notifications,
+ rendered_description=rendered_description,
+ role=role,
+ stream_id=stream_id,
+ stream_post_policy=stream_post_policy,
+ stream_weekly_traffic=stream_weekly_traffic,
+ wildcard_mentions_notify=wildcard_mentions_notify,
+ )
+ subscribed.append(sub)
+
+ return SubscriptionInfo(
+ subscriptions=subscribed,
+ unsubscribed=[],
+ never_subscribed=[],
+ )
+
+
+def build_stream_dict_for_sub(
+ user: UserProfile,
+ sub_dict: RawSubscriptionDict,
+ raw_stream_dict: RawStreamDict,
+ recent_traffic: Dict[int, int],
+) -> SubscriptionStreamDict:
+ # Handle Stream.API_FIELDS
+ date_created = datetime_to_timestamp(raw_stream_dict["date_created"])
+ description = raw_stream_dict["description"]
+ first_message_id = raw_stream_dict["first_message_id"]
+ history_public_to_subscribers = raw_stream_dict["history_public_to_subscribers"]
+ invite_only = raw_stream_dict["invite_only"]
+ is_web_public = raw_stream_dict["is_web_public"]
+ message_retention_days = raw_stream_dict["message_retention_days"]
+ name = raw_stream_dict["name"]
+ rendered_description = raw_stream_dict["rendered_description"]
+ stream_id = raw_stream_dict["id"]
+ stream_post_policy = raw_stream_dict["stream_post_policy"]
+
+ # Handle Subscription.API_FIELDS.
+ color = sub_dict["color"]
+ is_muted = sub_dict["is_muted"]
+ pin_to_top = sub_dict["pin_to_top"]
+ audible_notifications = sub_dict["audible_notifications"]
+ desktop_notifications = sub_dict["desktop_notifications"]
+ email_notifications = sub_dict["email_notifications"]
+ push_notifications = sub_dict["push_notifications"]
+ wildcard_mentions_notify = sub_dict["wildcard_mentions_notify"]
+ role = sub_dict["role"]
+
+ # Backwards-compatibility for clients that haven't been
+ # updated for the in_home_view => is_muted API migration.
+ in_home_view = not is_muted
+
+ # Backwards-compatibility for clients that haven't been
+ # updated for the is_announcement_only -> stream_post_policy
+ # migration.
+ is_announcement_only = raw_stream_dict["stream_post_policy"] == Stream.STREAM_POST_POLICY_ADMINS
+
+ # Add a few computed fields not directly from the data models.
+ stream_weekly_traffic = get_average_weekly_stream_traffic(
+ raw_stream_dict["id"], raw_stream_dict["date_created"], recent_traffic
+ )
+
+ email_address = encode_email_address_helper(
+ raw_stream_dict["name"], raw_stream_dict["email_token"], show_sender=True
+ )
+
+ # Our caller may add a subscribers field.
+ return SubscriptionStreamDict(
+ audible_notifications=audible_notifications,
+ color=color,
+ date_created=date_created,
+ description=description,
+ desktop_notifications=desktop_notifications,
+ email_address=email_address,
+ email_notifications=email_notifications,
+ first_message_id=first_message_id,
+ history_public_to_subscribers=history_public_to_subscribers,
+ in_home_view=in_home_view,
+ invite_only=invite_only,
+ is_announcement_only=is_announcement_only,
+ is_muted=is_muted,
+ is_web_public=is_web_public,
+ message_retention_days=message_retention_days,
+ name=name,
+ pin_to_top=pin_to_top,
+ push_notifications=push_notifications,
+ rendered_description=rendered_description,
+ role=role,
+ stream_id=stream_id,
+ stream_post_policy=stream_post_policy,
+ stream_weekly_traffic=stream_weekly_traffic,
+ wildcard_mentions_notify=wildcard_mentions_notify,
+ )
+
+
+def build_stream_dict_for_never_sub(
+ raw_stream_dict: RawStreamDict,
+ recent_traffic: Dict[int, int],
+) -> NeverSubscribedStreamDict:
+ date_created = datetime_to_timestamp(raw_stream_dict["date_created"])
+ description = raw_stream_dict["description"]
+ first_message_id = raw_stream_dict["first_message_id"]
+ history_public_to_subscribers = raw_stream_dict["history_public_to_subscribers"]
+ invite_only = raw_stream_dict["invite_only"]
+ is_web_public = raw_stream_dict["is_web_public"]
+ message_retention_days = raw_stream_dict["message_retention_days"]
+ name = raw_stream_dict["name"]
+ rendered_description = raw_stream_dict["rendered_description"]
+ stream_id = raw_stream_dict["id"]
+ stream_post_policy = raw_stream_dict["stream_post_policy"]
+ stream_weekly_traffic = get_average_weekly_stream_traffic(
+ raw_stream_dict["id"], raw_stream_dict["date_created"], recent_traffic
+ )
+
+ # Backwards-compatibility addition of removed field.
+ is_announcement_only = raw_stream_dict["stream_post_policy"] == Stream.STREAM_POST_POLICY_ADMINS
+
+ # Our caller may add a subscribers field.
+ return NeverSubscribedStreamDict(
+ date_created=date_created,
+ description=description,
+ first_message_id=first_message_id,
+ history_public_to_subscribers=history_public_to_subscribers,
+ invite_only=invite_only,
+ is_announcement_only=is_announcement_only,
+ is_web_public=is_web_public,
+ message_retention_days=message_retention_days,
+ name=name,
+ rendered_description=rendered_description,
+ stream_id=stream_id,
+ stream_post_policy=stream_post_policy,
+ stream_weekly_traffic=stream_weekly_traffic,
+ )
diff --git a/zerver/lib/types.py b/zerver/lib/types.py
index f1ef411ba46..43db3cb4a64 100644
--- a/zerver/lib/types.py
+++ b/zerver/lib/types.py
@@ -1,8 +1,10 @@
+import datetime
+from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from django.http import HttpResponse
from django.utils.functional import Promise
-from typing_extensions import TypedDict
+from typing_extensions import NotRequired, TypedDict
ViewFuncT = TypeVar("ViewFuncT", bound=Callable[..., HttpResponse])
@@ -128,3 +130,100 @@ class FormattedEditHistoryEvent(TypedDict, total=False):
prev_rendered_content: Optional[str]
rendered_content: Optional[str]
content_html_diff: str
+
+
+# This next batch of types is for Stream/Subscription objects.
+class RawStreamDict(TypedDict):
+ """Dictionary containing fields fetched from the Stream model that
+ are needed to encode the stream for the API.
+ """
+
+ date_created: datetime.datetime
+ description: str
+ email_token: str
+ first_message_id: Optional[int]
+ history_public_to_subscribers: bool
+ id: int
+ invite_only: Optional[bool]
+ is_web_public: bool
+ message_retention_days: Optional[int]
+ name: str
+ rendered_description: str
+ stream_post_policy: int
+
+
+class RawSubscriptionDict(TypedDict):
+ """Dictionary containing fields fetched from the Subscription model
+ that are needed to encode the subscription for the API.
+ """
+
+ active: bool
+ audible_notifications: Optional[bool]
+ color: str
+ desktop_notifications: Optional[bool]
+ email_notifications: Optional[bool]
+ is_muted: Optional[bool]
+ pin_to_top: bool
+ push_notifications: Optional[bool]
+ recipient_id: int
+ role: int
+ wildcard_mentions_notify: Optional[bool]
+
+
+class SubscriptionStreamDict(TypedDict):
+ """Conceptually, the union of RawSubscriptionDict and RawStreamDict
+ (i.e. containing all the user's personal settings for the stream
+ as well as the stream's global settings), with a few additional
+ computed fields.
+ """
+
+ audible_notifications: Optional[bool]
+ color: str
+ date_created: int
+ description: str
+ desktop_notifications: Optional[bool]
+ email_address: str
+ email_notifications: Optional[bool]
+ first_message_id: Optional[int]
+ history_public_to_subscribers: bool
+ in_home_view: Optional[bool]
+ # Bug: invite_only should be bool.
+ invite_only: Optional[bool]
+ is_announcement_only: bool
+ is_muted: Optional[bool]
+ is_web_public: bool
+ message_retention_days: Optional[int]
+ name: str
+ pin_to_top: bool
+ push_notifications: Optional[bool]
+ rendered_description: str
+ role: int
+ stream_id: int
+ stream_post_policy: int
+ stream_weekly_traffic: Optional[int]
+ subscribers: NotRequired[List[int]]
+ wildcard_mentions_notify: Optional[bool]
+
+
+class NeverSubscribedStreamDict(TypedDict):
+ date_created: int
+ description: str
+ first_message_id: Optional[int]
+ history_public_to_subscribers: bool
+ invite_only: Optional[bool]
+ is_announcement_only: bool
+ is_web_public: bool
+ message_retention_days: Optional[int]
+ name: str
+ rendered_description: str
+ stream_id: int
+ stream_post_policy: int
+ stream_weekly_traffic: Optional[int]
+ subscribers: NotRequired[List[int]]
+
+
+@dataclass
+class SubscriptionInfo:
+ subscriptions: List[SubscriptionStreamDict]
+ unsubscribed: List[SubscriptionStreamDict]
+ never_subscribed: List[NeverSubscribedStreamDict]
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index a303f78a518..0b8861c1326 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -73,6 +73,7 @@ from zerver.lib.test_helpers import (
queries_captured,
reset_emails_in_zulip_realm,
)
+from zerver.lib.types import NeverSubscribedStreamDict, SubscriptionInfo
from zerver.models import (
DefaultStream,
DefaultStreamGroup,
@@ -2536,9 +2537,9 @@ class DefaultStreamTest(ZulipTestCase):
never_subscribed = sub_info.never_subscribed
self.assert_length(streams, len(subscribed) + len(unsubscribed) + len(never_subscribed))
- expected_streams = subscribed + unsubscribed + never_subscribed
stream_names = [stream["name"] for stream in streams]
- expected_stream_names = [stream["name"] for stream in expected_streams]
+ expected_stream_names = [stream["name"] for stream in subscribed + unsubscribed]
+ expected_stream_names += [stream["name"] for stream in never_subscribed]
self.assertEqual(set(stream_names), set(expected_stream_names))
@@ -5378,6 +5379,36 @@ class GetSubscribersTest(ZulipTestCase):
self.user_profile = self.example_user("hamlet")
self.login_user(self.user_profile)
+ def verify_sub_fields(self, sub_data: SubscriptionInfo) -> None:
+ other_fields = {
+ "email_address",
+ "is_announcement_only",
+ "in_home_view",
+ "stream_id",
+ "stream_weekly_traffic",
+ "subscribers",
+ }
+
+ expected_fields = set(Stream.API_FIELDS) | set(Subscription.API_FIELDS) | other_fields
+ expected_fields -= {"id"}
+
+ for lst in [sub_data.subscriptions, sub_data.unsubscribed]:
+ for sub in lst:
+ self.assertEqual(set(sub), expected_fields)
+
+ other_fields = {
+ "is_announcement_only",
+ "stream_id",
+ "stream_weekly_traffic",
+ "subscribers",
+ }
+
+ expected_fields = set(Stream.API_FIELDS) | other_fields
+ expected_fields -= {"id"}
+
+ for never_sub in sub_data.never_subscribed:
+ self.assertEqual(set(never_sub), expected_fields)
+
def assert_user_got_subscription_notification(
self, user: UserProfile, expected_msg: str
) -> None:
@@ -5577,9 +5608,10 @@ class GetSubscribersTest(ZulipTestCase):
create_private_streams()
- def get_never_subscribed() -> List[Dict[str, Any]]:
+ def get_never_subscribed() -> List[NeverSubscribedStreamDict]:
with queries_captured() as queries:
sub_data = gather_subscriptions_helper(self.user_profile)
+ self.verify_sub_fields(sub_data)
never_subscribed = sub_data.never_subscribed
self.assert_length(queries, 4)
@@ -5614,6 +5646,7 @@ class GetSubscribersTest(ZulipTestCase):
def test_guest_user_case() -> None:
self.user_profile.role = UserProfile.ROLE_GUEST
helper_result = gather_subscriptions_helper(self.user_profile)
+ self.verify_sub_fields(helper_result)
sub = helper_result.subscriptions
unsub = helper_result.unsubscribed
never_sub = helper_result.never_subscribed
@@ -5657,6 +5690,7 @@ class GetSubscribersTest(ZulipTestCase):
self.subscribe(normal_user, stream_name_unsub)
helper_result = gather_subscriptions_helper(guest_user)
+ self.verify_sub_fields(helper_result)
subs = helper_result.subscriptions
neversubs = helper_result.never_subscribed
@@ -5676,6 +5710,14 @@ class GetSubscribersTest(ZulipTestCase):
# Guest user only get data about never subscribed web-public streams
self.assert_length(neversubs, 1)
+ def test_api_fields_present(self) -> None:
+ user = self.example_user("cordelia")
+
+ sub_data = gather_subscriptions_helper(user)
+ subscribed = sub_data.subscriptions
+ self.assertGreaterEqual(len(subscribed), 1)
+ self.verify_sub_fields(sub_data)
+
def test_previously_subscribed_private_streams(self) -> None:
admin_user = self.example_user("iago")
non_admin_user = self.example_user("cordelia")
@@ -5694,17 +5736,20 @@ class GetSubscribersTest(ZulipTestCase):
# Test admin user gets previously subscribed private stream's subscribers.
sub_data = gather_subscriptions_helper(admin_user)
+ self.verify_sub_fields(sub_data)
unsubscribed_streams = sub_data.unsubscribed
self.assert_length(unsubscribed_streams, 1)
self.assert_length(unsubscribed_streams[0]["subscribers"], 1)
# Test non admin users cannot get previously subscribed private stream's subscribers.
sub_data = gather_subscriptions_helper(non_admin_user)
+ self.verify_sub_fields(sub_data)
unsubscribed_streams = sub_data.unsubscribed
self.assert_length(unsubscribed_streams, 1)
self.assertEqual(unsubscribed_streams[0]["subscribers"], [])
sub_data = gather_subscriptions_helper(guest_user)
+ self.verify_sub_fields(sub_data)
unsubscribed_streams = sub_data.unsubscribed
self.assert_length(unsubscribed_streams, 1)
self.assertEqual(unsubscribed_streams[0]["subscribers"], [])