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.

mypy: Add StreamDict.

Steve Howellc199571112c6
diff --git a/zerver/lib/streams.py b/zerver/lib/streams.py
index 3c4ff107c46..d4678c98ab8 100644
--- a/zerver/lib/streams.py
+++ b/zerver/lib/streams.py
@@ -1,9 +1,10 @@
-from typing import Any, Iterable, List, Mapping, Optional, Set, Tuple, Union
+from typing import Iterable, List, Optional, Set, Tuple, Union
from django.conf import settings
from django.db.models.query import QuerySet
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext as _
+from typing_extensions import TypedDict
from zerver.lib.exceptions import StreamAdministratorRequired
from zerver.lib.markdown import markdown_convert
@@ -26,6 +27,28 @@ from zerver.models import (
from zerver.tornado.django_api import send_event
+class StreamDict(TypedDict, total=False):
+ """
+ This type ultimately gets used in two places:
+
+ - we use it to create a stream
+ - we use it to specify a stream
+
+ It's possible we want a smaller type to use
+ for removing streams, but it would complicate
+ how we write the types for list_to_stream.
+
+ Note that these fields are just a subset of
+ the fields in the Stream model.
+ """
+ name: str
+ description: str
+ invite_only: bool
+ is_web_public: bool
+ stream_post_policy: int
+ history_public_to_subscribers: Optional[bool]
+ message_retention_days: Optional[int]
+
def get_default_value_for_history_public_to_subscribers(
realm: Realm,
invite_only: bool,
@@ -103,9 +126,11 @@ def create_stream_if_needed(realm: Realm,
event_time=event_time)
return stream, created
-def create_streams_if_needed(realm: Realm,
- stream_dicts: List[Mapping[str, Any]],
- acting_user: Optional[UserProfile]=None) -> Tuple[List[Stream], List[Stream]]:
+def create_streams_if_needed(
+ realm: Realm,
+ stream_dicts: List[StreamDict],
+ acting_user: Optional[UserProfile]=None
+) -> Tuple[List[Stream], List[Stream]]:
"""Note that stream_dict["name"] is assumed to already be stripped of
whitespace"""
added_streams: List[Stream] = []
@@ -458,7 +483,7 @@ def filter_stream_authorization(user_profile: UserProfile,
stream.id not in {stream.id for stream in unauthorized_streams}]
return authorized_streams, unauthorized_streams
-def list_to_streams(streams_raw: Iterable[Mapping[str, Any]],
+def list_to_streams(streams_raw: Iterable[StreamDict],
user_profile: UserProfile,
autocreate: bool=False,
admin_access_required: bool=False) -> Tuple[List[Stream], List[Stream]]:
@@ -486,7 +511,7 @@ def list_to_streams(streams_raw: Iterable[Mapping[str, Any]],
check_stream_name(stream_name)
existing_streams: List[Stream] = []
- missing_stream_dicts: List[Mapping[str, Any]] = []
+ missing_stream_dicts: List[StreamDict] = []
existing_stream_map = bulk_get_streams(user_profile.realm, stream_set)
if admin_access_required:
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index a146f4f80b2..4183968469c 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -1,6 +1,6 @@
import datetime
import os
-from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from unittest import mock
import orjson
@@ -31,7 +31,7 @@ from zerver.lib.message import (
from zerver.lib.narrow import build_narrow_filter, is_web_public_compatible
from zerver.lib.request import JsonableError
from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection
-from zerver.lib.streams import create_streams_if_needed, get_public_streams_queryset
+from zerver.lib.streams import StreamDict, create_streams_if_needed, get_public_streams_queryset
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import POSTRequestMock, get_user_messages, queries_captured
from zerver.lib.topic import MATCH_TOPIC, TOPIC_NAME
@@ -131,7 +131,7 @@ class NarrowBuilderTest(ZulipTestCase):
self._do_add_term_test(term, 'WHERE recipient_id IN (%(recipient_id_1)s, %(recipient_id_2)s, %(recipient_id_3)s, %(recipient_id_4)s, %(recipient_id_5)s)')
# Add new streams
- stream_dicts: List[Mapping[str, Any]] = [
+ stream_dicts: List[StreamDict] = [
{
"name": "publicstream",
"description": "Public stream with public history",
@@ -161,7 +161,7 @@ class NarrowBuilderTest(ZulipTestCase):
self._do_add_term_test(term, 'WHERE recipient_id NOT IN (%(recipient_id_1)s, %(recipient_id_2)s, %(recipient_id_3)s, %(recipient_id_4)s, %(recipient_id_5)s)')
# Add new streams
- stream_dicts: List[Mapping[str, Any]] = [
+ stream_dicts: List[StreamDict] = [
{
"name": "publicstream",
"description": "Public stream with public history",
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index 0a1e63660f6..0718b2671f1 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -53,6 +53,7 @@ from zerver.lib.stream_subscription import (
num_subscribers_for_stream_id,
)
from zerver.lib.streams import (
+ StreamDict,
access_stream_by_id,
access_stream_by_name,
can_access_stream_history,
@@ -198,7 +199,7 @@ class TestCreateStreams(ZulipTestCase):
def test_history_public_to_subscribers_on_stream_creation(self) -> None:
realm = get_realm('zulip')
- stream_dicts: List[Mapping[str, Any]] = [
+ stream_dicts: List[StreamDict] = [
{
"name": "publicstream",
"description": "Public stream with public history",
@@ -1132,7 +1133,7 @@ class StreamAdminTest(ZulipTestCase):
"""
admin = self.example_user('iago')
- streams_raw = [{
+ streams_raw: List[StreamDict] = [{
'name': 'new_stream',
'message_retention_days': 10,
}]
@@ -3076,7 +3077,7 @@ class SubscriptionAPITest(ZulipTestCase):
([], [stream]))
# Test UserProfile.can_create_streams for guest users.
- streams_raw = [{
+ streams_raw: List[StreamDict] = [{
'invite_only': False,
'history_public_to_subscribers': None,
'name': 'new_stream',
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index 4271e33cd53..7022cf42fcf 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -60,6 +60,7 @@ from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.lib.retention import parse_message_retention_days
from zerver.lib.streams import (
+ StreamDict,
access_default_stream_group_by_id,
access_stream_by_id,
access_stream_by_name,
@@ -361,7 +362,7 @@ def remove_subscriptions_backend(
removing_someone_else = check_if_removing_someone_else(user_profile, principals)
- streams_as_dict = []
+ streams_as_dict: List[StreamDict] = []
for stream_name in streams_raw:
streams_as_dict.append({"name": stream_name.strip()})
@@ -433,20 +434,20 @@ def add_subscriptions_backend(
# check for its presence in the streams_raw first
if 'color' in stream_dict:
color_map[stream_dict['name']] = stream_dict['color']
- if 'description' in stream_dict:
- # We don't allow newline characters in stream descriptions.
- stream_dict['description'] = stream_dict['description'].replace("\n", " ")
- stream_dict_copy: Dict[str, Any] = {}
- for field in stream_dict:
- stream_dict_copy[field] = stream_dict[field]
- # Strip the stream name here.
- stream_dict_copy['name'] = stream_dict_copy['name'].strip()
+ stream_dict_copy: StreamDict = {}
+ stream_dict_copy["name"] = stream_dict["name"].strip()
+
+ # We don't allow newline characters in stream descriptions.
+ if "description" in stream_dict:
+ stream_dict_copy["description"] = stream_dict["description"].replace("\n", " ")
+
stream_dict_copy["invite_only"] = invite_only
stream_dict_copy["stream_post_policy"] = stream_post_policy
stream_dict_copy["history_public_to_subscribers"] = history_public_to_subscribers
stream_dict_copy["message_retention_days"] = parse_message_retention_days(
message_retention_days, Stream.MESSAGE_RETENTION_SPECIAL_VALUES_MAP)
+
stream_dicts.append(stream_dict_copy)
# Validation of the streams arguments, including enforcement of