Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
streams: Fix compose_views type safety.
Anders Kaseorgd0016767280c
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex abf555d8c7e..945846ed5cd 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -6,7 +6,7 @@ from unittest import mockimport orjsonfrom django.conf import settingsfrom django.core.exceptions import ValidationError-from django.http import HttpRequest, HttpResponse+from django.http import HttpResponsefrom django.utils.timezone import now as timezone_nowfrom zerver.decorator import JsonableError@@ -2873,16 +2873,16 @@ class SubscriptionRestApiTest(ZulipTestCase):user_profile.full_name = "Hamlet"user_profile.save()- def method1(req: HttpRequest, user_profile: UserProfile) -> HttpResponse:+ def thunk1() -> HttpResponse:user_profile.full_name = "Should not be committed"user_profile.save()return json_success()- def method2(req: HttpRequest, user_profile: UserProfile) -> HttpResponse:+ def thunk2() -> HttpResponse:return json_error("random failure")with self.assertRaises(JsonableError):- compose_views(None, user_profile, [(method1, {}), (method2, {})])+ compose_views([thunk1, thunk2])user_profile = self.example_user("hamlet")self.assertEqual(user_profile.full_name, "Hamlet")diff --git a/zerver/views/streams.py b/zerver/views/streams.pyindex 0e0afdab48d..d4e88ff9f48 100644--- a/zerver/views/streams.py+++ b/zerver/views/streams.py@@ -1,17 +1,5 @@from collections import defaultdict-from typing import (- Any,- Callable,- Dict,- Iterable,- List,- Mapping,- Optional,- Sequence,- Set,- Tuple,- Union,-)+from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Set, Unionimport orjsonfrom django.conf import settings@@ -331,8 +319,6 @@ def list_subscriptions_backend(return json_success({"subscriptions": subscribed})-FuncKwargPair = Tuple[Callable[..., HttpResponse], Dict[str, Union[int, Iterable[Any]]]]-add_subscriptions_schema = check_list(check_dict_only(required_keys=[("name", check_string)],@@ -351,37 +337,34 @@ def update_subscriptions_backend(request: HttpRequest,user_profile: UserProfile,delete: Iterable[str] = REQ(validator=remove_subscriptions_schema, default=[]),- add: Iterable[Mapping[str, Any]] = REQ(validator=add_subscriptions_schema, default=[]),+ add: Iterable[Mapping[str, str]] = REQ(validator=add_subscriptions_schema, default=[]),) -> HttpResponse:if not add and not delete:return json_error(_('Nothing to do. Specify at least one of "add" or "delete".'))- method_kwarg_pairs: List[FuncKwargPair] = [- (add_subscriptions_backend, dict(streams_raw=add)),- (remove_subscriptions_backend, dict(streams_raw=delete)),+ thunks = [+ lambda: add_subscriptions_backend(request, user_profile, streams_raw=add),+ lambda: remove_subscriptions_backend(request, user_profile, streams_raw=delete),]- return compose_views(request, user_profile, method_kwarg_pairs)+ return compose_views(thunks)-def compose_views(- request: HttpRequest,- user_profile: UserProfile,- method_kwarg_pairs: "List[FuncKwargPair]",-) -> HttpResponse:+def compose_views(thunks: List[Callable[[], HttpResponse]]) -> HttpResponse:"""- This takes a series of view methods from method_kwarg_pairs and calls- them in sequence, and it smushes all the json results into a single- response when everything goes right. (This helps clients avoid extra- latency hops.) It rolls back the transaction when things go wrong in- any one of the composed methods.+ This takes a series of thunks and calls them in sequence, and it+ smushes all the json results into a single response when+ everything goes right. (This helps clients avoid extra latency+ hops.) It rolls back the transaction when things go wrong in any+ one of the composed methods.TODO: Move this a utils-like module if we end up using it more widely.+"""json_dict: Dict[str, Any] = {}with transaction.atomic():- for method, kwargs in method_kwarg_pairs:- response = method(request, user_profile, **kwargs)+ for thunk in thunks:+ response = thunk()if response.status_code != 200:raise JsonableError(response.content)json_dict.update(orjson.loads(response.content))@@ -463,7 +446,7 @@ EMPTY_PRINCIPALS: Union[Sequence[str], Sequence[int]] = []def add_subscriptions_backend(request: HttpRequest,user_profile: UserProfile,- streams_raw: Iterable[Dict[str, str]] = REQ(+ streams_raw: Iterable[Mapping[str, str]] = REQ("subscriptions", validator=add_subscriptions_schema),invite_only: bool = REQ(validator=check_bool, default=False),diff --git a/zerver/views/user_groups.py b/zerver/views/user_groups.pyindex 9a2c569cbc4..dc4f34e6657 100644--- a/zerver/views/user_groups.py+++ b/zerver/views/user_groups.py@@ -1,4 +1,4 @@-from typing import List, Sequence+from typing import Sequencefrom django.http import HttpRequest, HttpResponsefrom django.utils.translation import ugettext as _@@ -24,7 +24,7 @@ from zerver.lib.user_groups import (from zerver.lib.users import user_ids_to_usersfrom zerver.lib.validator import check_int, check_listfrom zerver.models import UserProfile-from zerver.views.streams import FuncKwargPair, compose_views+from zerver.views.streams import compose_views@require_user_group_edit_permission@@ -95,15 +95,19 @@ def update_user_group_backend(if not add and not delete:return json_error(_('Nothing to do. Specify at least one of "add" or "delete".'))- method_kwarg_pairs: List[FuncKwargPair] = [- (add_members_to_group_backend, dict(user_group_id=user_group_id, members=add)),- (remove_members_from_group_backend, dict(user_group_id=user_group_id, members=delete)),+ thunks = [+ lambda: add_members_to_group_backend(+ request, user_profile, user_group_id=user_group_id, members=add+ ),+ lambda: remove_members_from_group_backend(+ request, user_profile, user_group_id=user_group_id, members=delete+ ),]- return compose_views(request, user_profile, method_kwarg_pairs)+ return compose_views(thunks)def add_members_to_group_backend(- request: HttpRequest, user_profile: UserProfile, user_group_id: int, members: List[int]+ request: HttpRequest, user_profile: UserProfile, user_group_id: int, members: Sequence[int]) -> HttpResponse:if not members:return json_success()@@ -125,7 +129,7 @@ def add_members_to_group_backend(def remove_members_from_group_backend(- request: HttpRequest, user_profile: UserProfile, user_group_id: int, members: List[int]+ request: HttpRequest, user_profile: UserProfile, user_group_id: int, members: Sequence[int]) -> HttpResponse:if not members:return json_success()