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.

user_groups: Move compose_views from the streams views.

Agnish Baurib82d7643836a
diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.py
index 35100ddfbd7..c16234286b2 100644
--- a/tools/linter_lib/custom_check.py
+++ b/tools/linter_lib/custom_check.py
@@ -490,7 +490,7 @@ python_rules = RuleList(
"with transaction.atomic(savepoint=True):",
),
(
- "zerver/tests/test_subs.py",
+ "zerver/tests/test_user_groups.py",
"with transaction.atomic(savepoint=True), self.assertRaises(JsonableError):",
),
(
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index e2727bafe21..ab509246bb5 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -9,8 +9,6 @@ from unittest import mock
import orjson
from django.conf import settings
from django.core.exceptions import ValidationError
-from django.db import transaction
-from django.http import HttpResponse
from django.utils.timezone import now as timezone_now
from typing_extensions import override
@@ -43,7 +41,6 @@ from zerver.lib.attachments import (
)
from zerver.lib.exceptions import JsonableError
from zerver.lib.message import UnreadStreamInfo, aggregate_unread_data, get_raw_unread_data
-from zerver.lib.response import json_success
from zerver.lib.stream_color import STREAM_ASSIGNMENT_COLORS, pick_colors
from zerver.lib.stream_subscription import (
get_active_subscriptions_for_stream_id,
@@ -70,7 +67,7 @@ from zerver.lib.subscription_info import (
validate_user_access_to_subscribers_helper,
)
from zerver.lib.test_classes import ZulipTestCase, get_topic_messages
-from zerver.lib.test_helpers import HostRequestMock, cache_tries_captured
+from zerver.lib.test_helpers import cache_tries_captured
from zerver.lib.types import UserGroupMembersData
from zerver.lib.user_groups import UserGroupMembershipDetails, get_group_setting_value_for_api
from zerver.models import (
@@ -97,7 +94,6 @@ from zerver.models.users import (
get_user,
get_user_profile_by_id_in_realm,
)
-from zerver.views.streams import compose_views
if TYPE_CHECKING:
from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse
@@ -3631,36 +3627,6 @@ class SubscriptionRestApiTest(ZulipTestCase):
result = self.api_delete(user, "/api/v1/users/me/subscriptions", request)
self.assert_json_error(result, "Invalid character in channel name, at position 4.")
- def test_compose_views_rollback(self) -> None:
- """
- The compose_views function() is used under the hood by
- zerver.views.user_groups. It's a pretty simple method in terms of
- control flow, but it uses a Django rollback, which may make it brittle
- code when we upgrade Django. We test the functions's rollback logic
- here with a simple scenario to avoid false positives related to
- subscription complications.
- """
- user_profile = self.example_user("hamlet")
- user_profile.full_name = "Hamlet"
- user_profile.save()
- request = HostRequestMock(user_profile=user_profile)
-
- def thunk1() -> HttpResponse:
- user_profile.full_name = "Should not be committed"
- user_profile.save()
- return json_success(request)
-
- def thunk2() -> HttpResponse:
- raise JsonableError("random failure")
-
- with transaction.atomic(savepoint=True), self.assertRaises(JsonableError):
- # The atomic() wrapper helps to avoid JsonableError breaking
- # the test's transaction.
- compose_views([thunk1, thunk2])
-
- user_profile = self.example_user("hamlet")
- self.assertEqual(user_profile.full_name, "Hamlet")
-
class SubscriptionAPITest(ZulipTestCase):
@override
diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py
index 989c9a90040..e89f5e69bc5 100644
--- a/zerver/tests/test_user_groups.py
+++ b/zerver/tests/test_user_groups.py
@@ -5,6 +5,8 @@ from unittest import mock
import orjson
import time_machine
+from django.db import transaction
+from django.http import HttpResponse
from django.utils.timezone import now as timezone_now
from zerver.actions.create_realm import do_create_realm
@@ -34,9 +36,10 @@ from zerver.actions.users import do_deactivate_user
from zerver.lib.create_user import create_user
from zerver.lib.exceptions import JsonableError
from zerver.lib.mention import silent_mention_syntax_for_user
+from zerver.lib.response import json_success
from zerver.lib.streams import ensure_stream
from zerver.lib.test_classes import ZulipTestCase
-from zerver.lib.test_helpers import most_recent_usermessage
+from zerver.lib.test_helpers import HostRequestMock, most_recent_usermessage
from zerver.lib.timestamp import datetime_to_timestamp
from zerver.lib.types import GroupPermissionSetting, UserGroupMembersData, UserGroupMembersDict
from zerver.lib.user_groups import (
@@ -72,6 +75,7 @@ from zerver.models import (
)
from zerver.models.groups import SystemGroups, get_realm_system_groups_name_dict
from zerver.models.realms import get_realm
+from zerver.views.user_groups import compose_views
class UserGroupTestCase(ZulipTestCase):
@@ -2278,6 +2282,36 @@ class UserGroupAPITestCase(UserGroupTestCase):
self.assert_length(all_user_ids, 102)
self.assert_user_membership(user_group, [hamlet, cordelia, *new_users, *original_users])
+ def test_compose_views_rollback(self) -> None:
+ """
+ The compose_views function() is used under the hood by
+ zerver.views.user_groups. It's a pretty simple method in terms of
+ control flow, but it uses a Django rollback, which may make it brittle
+ code when we upgrade Django. We test the functions's rollback logic
+ here with a simple scenario to avoid false positives related to
+ subscription complications.
+ """
+ user_profile = self.example_user("hamlet")
+ user_profile.full_name = "Hamlet"
+ user_profile.save()
+ request = HostRequestMock(user_profile=user_profile)
+
+ def thunk1() -> HttpResponse:
+ user_profile.full_name = "Should not be committed"
+ user_profile.save()
+ return json_success(request)
+
+ def thunk2() -> HttpResponse:
+ raise JsonableError("random failure")
+
+ with transaction.atomic(savepoint=True), self.assertRaises(JsonableError):
+ # The atomic() wrapper helps to avoid JsonableError breaking
+ # the test's transaction.
+ compose_views([thunk1, thunk2])
+
+ user_profile = self.example_user("hamlet")
+ self.assertEqual(user_profile.full_name, "Hamlet")
+
def test_update_members_of_user_group(self) -> None:
hamlet = self.example_user("hamlet")
self.login("hamlet")
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index a9bc126d90b..519bf46aa0e 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -1,9 +1,7 @@
import time
from collections import defaultdict
-from collections.abc import Callable
from typing import Annotated, Any, Literal
-import orjson
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.db import transaction
@@ -572,23 +570,6 @@ class AddSubscriptionData(BaseModel):
return self
-def compose_views(thunks: list[Callable[[], HttpResponse]]) -> dict[str, Any]:
- """
- 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.
- """
-
- json_dict: dict[str, Any] = {}
- with transaction.atomic(savepoint=False):
- for thunk in thunks:
- response = thunk()
- json_dict.update(orjson.loads(response.content))
- return json_dict
-
-
@typed_endpoint
def remove_subscriptions_backend(
request: HttpRequest,
diff --git a/zerver/views/user_groups.py b/zerver/views/user_groups.py
index 367c6dcfef1..5a4f8de285f 100644
--- a/zerver/views/user_groups.py
+++ b/zerver/views/user_groups.py
@@ -1,3 +1,7 @@
+from collections.abc import Callable
+from typing import Any
+
+import orjson
from django.conf import settings
from django.db import transaction
from django.http import HttpRequest, HttpResponse
@@ -50,7 +54,23 @@ from zerver.lib.users import access_user_by_id, user_ids_to_users
from zerver.models import NamedUserGroup, UserProfile
from zerver.models.groups import SystemGroups
from zerver.models.users import get_system_bot
-from zerver.views.streams import compose_views
+
+
+def compose_views(thunks: list[Callable[[], HttpResponse]]) -> dict[str, Any]:
+ """
+ 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.
+ """
+
+ json_dict: dict[str, Any] = {}
+ with transaction.atomic(savepoint=False):
+ for thunk in thunks:
+ response = thunk()
+ json_dict.update(orjson.loads(response.content))
+ return json_dict
@transaction.atomic(durable=True)