Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
test_tornado: Remove async_to_sync_decorator.
Anders Kaseorg722c1e89991b
diff --git a/zerver/tests/test_tornado.py b/zerver/tests/test_tornado.pyindex 50283b1d687..e2132170387 100644--- a/zerver/tests/test_tornado.py+++ b/zerver/tests/test_tornado.py@@ -1,14 +1,13 @@import asyncioimport socket-from collections.abc import Awaitable, Callable, Iterator-from contextlib import contextmanager-from functools import wraps+from collections.abc import AsyncIterator, Callable, Iterator+from contextlib import asynccontextmanager, contextmanagerfrom typing import Any, TypeVar-from unittest import TestResult, mock+from unittest import mockfrom urllib.parse import urlencodeimport orjson-from asgiref.sync import async_to_sync, sync_to_async+from asgiref.sync import sync_to_asyncfrom django.conf import settingsfrom django.core import signalsfrom django.db import close_old_connections@@ -16,7 +15,7 @@ from django.test import override_settingsfrom tornado import netutilfrom tornado.httpclient import AsyncHTTPClient, HTTPResponsefrom tornado.httpserver import HTTPServer-from typing_extensions import ParamSpec, override+from typing_extensions import overridefrom zerver.lib.cache import user_profile_narrow_by_id_cache_keyfrom zerver.lib.test_classes import ZulipTestCase@@ -26,26 +25,16 @@ from zerver.tornado import event_queuefrom zerver.tornado.application import create_tornado_applicationfrom zerver.tornado.event_queue import process_event-P = ParamSpec("P")T = TypeVar("T")-def async_to_sync_decorator(f: Callable[P, Awaitable[T]]) -> Callable[P, T]:- @wraps(f)- def wrapped(*args: P.args, **kwargs: P.kwargs) -> T:- return async_to_sync(f)(*args, **kwargs)-- return wrapped--async def in_django_thread(f: Callable[[], T]) -> T:return await asyncio.create_task(sync_to_async(f)())class TornadoWebTestCase(ZulipTestCase):- @async_to_sync_decorator- @override- async def setUp(self) -> None:+ @asynccontextmanager+ async def with_tornado(self) -> AsyncIterator[None]:super().setUp()with override_settings(DEBUG=False):@@ -57,19 +46,15 @@ class TornadoWebTestCase(ZulipTestCase):signals.request_started.disconnect(close_old_connections)signals.request_finished.disconnect(close_old_connections)self.session_cookie: dict[str, str] | None = None-- @async_to_sync_decorator- @override- async def tearDown(self) -> None:- self.http_client.close()- self.http_server.stop()- super().tearDown()-- @override- def run(self, result: TestResult | None = None) -> TestResult | None:- return async_to_sync(- sync_to_async(super().run, thread_sensitive=False), force_new_loop=True- )(result)+ try:+ yield+ finally:+ self.http_client.close()+ self.http_server.stop()+ await self.http_server.close_all_connections()+ tasks = set(asyncio.all_tasks()) - {asyncio.current_task()}+ if tasks:+ await asyncio.wait(tasks)async def fetch_async(self, method: str, path: str, **kwargs: Any) -> HTTPResponse:self.add_session_cookie(kwargs)@@ -109,11 +94,11 @@ class TornadoWebTestCase(ZulipTestCase):class EventsTestCase(TornadoWebTestCase):- @async_to_sync_decoratorasync def test_create_queue(self) -> None:- await in_django_thread(lambda: self.login_user(self.example_user("hamlet")))- queue_id = await self.create_queue()- self.assertIn(queue_id, event_queue.clients)+ async with self.with_tornado():+ await in_django_thread(lambda: self.login_user(self.example_user("hamlet")))+ queue_id = await self.create_queue()+ self.assertIn(queue_id, event_queue.clients)@contextmanagerdef mocked_events(self, user_profile: UserProfile, event: dict[str, object]) -> Iterator[None]:@@ -129,85 +114,87 @@ class EventsTestCase(TornadoWebTestCase):with mock.patch("zerver.tornado.views.fetch_events", side_effect=wrapped_fetch_events):yield- @async_to_sync_decoratorasync def test_events_async(self) -> None:- user_profile = await in_django_thread(lambda: self.example_user("hamlet"))- await in_django_thread(lambda: self.login_user(user_profile))- event_queue_id = await self.create_queue()- data = {- "queue_id": event_queue_id,- "last_event_id": -1,- }-- path = f"/json/events?{urlencode(data)}"-- with self.mocked_events(user_profile, {"type": "test", "data": "test data"}):- response = await self.fetch_async("GET", path)-- self.assertEqual(response.headers["Vary"], "Accept-Language, Cookie")- data = orjson.loads(response.body)- self.assertEqual(- data["events"],- [- {"type": "test", "data": "test data", "id": 0},- ],- )- self.assertEqual(data["result"], "success")-- @async_to_sync_decorator- async def test_events_caching(self) -> None:- user_profile = await in_django_thread(lambda: self.example_user("hamlet"))- await in_django_thread(lambda: self.login_user(user_profile))- event_queue_id = await self.create_queue()- data = {- "queue_id": event_queue_id,- "last_event_id": -1,- }-- path = f"/json/events?{urlencode(data)}"-- with (- self.mocked_events(user_profile, {"type": "test", "data": "test data"}),- cache_tries_captured() as cache_gets,- queries_captured() as queries,- ):- await self.fetch_async("GET", path)-- # Two cache fetches -- for the user and the client. In- # production, the session would also be a cache access,- # but tests don't use cached sessions.- self.assert_length(cache_gets, 2)+ async with self.with_tornado():+ user_profile = await in_django_thread(lambda: self.example_user("hamlet"))+ await in_django_thread(lambda: self.login_user(user_profile))+ event_queue_id = await self.create_queue()+ data = {+ "queue_id": event_queue_id,+ "last_event_id": -1,+ }++ path = f"/json/events?{urlencode(data)}"++ with self.mocked_events(user_profile, {"type": "test", "data": "test data"}):+ response = await self.fetch_async("GET", path)++ self.assertEqual(response.headers["Vary"], "Accept-Language, Cookie")+ data = orjson.loads(response.body)self.assertEqual(- cache_gets[0], ("get", user_profile_narrow_by_id_cache_key(user_profile.id), None)+ data["events"],+ [+ {"type": "test", "data": "test data", "id": 0},+ ],)- self.assertEqual(cache_gets[1][0], "get")- assert isinstance(cache_gets[1][1], str)- self.assertTrue(cache_gets[1][1].startswith("get_client:"))-- # Three database queries -- session, user, and client.- # The user query should remain small; it is currently 470- # bytes, but anything under 1k should be Fine.- self.assert_length(queries, 3)- self.assertIn("django_session", queries[0].sql)- self.assertIn("zerver_userprofile", queries[1].sql)- self.assertLessEqual(len(queries[1].sql), 1024)- self.assertIn("zerver_client", queries[2].sql)-- # Perform the same request again, preserving the caches. We- # should only see one database query -- the session. As noted- # above, in production even that would be cached.- with (- self.mocked_events(user_profile, {"type": "test", "data": "test data"}),- cache_tries_captured() as cache_gets,- queries_captured(keep_cache_warm=True) as queries,- ):- await self.fetch_async("GET", path)- self.assert_length(cache_gets, 1)- self.assertEqual(- cache_gets[0], ("get", user_profile_narrow_by_id_cache_key(user_profile.id), None)- )- # Client is cached in-process-memory, so doesn't even see- # a memcached hit+ self.assertEqual(data["result"], "success")- self.assert_length(queries, 1)- self.assertIn("django_session", queries[0].sql)+ async def test_events_caching(self) -> None:+ async with self.with_tornado():+ user_profile = await in_django_thread(lambda: self.example_user("hamlet"))+ await in_django_thread(lambda: self.login_user(user_profile))+ event_queue_id = await self.create_queue()+ data = {+ "queue_id": event_queue_id,+ "last_event_id": -1,+ }++ path = f"/json/events?{urlencode(data)}"++ with (+ self.mocked_events(user_profile, {"type": "test", "data": "test data"}),+ cache_tries_captured() as cache_gets,+ queries_captured() as queries,+ ):+ await self.fetch_async("GET", path)++ # Two cache fetches -- for the user and the client. In+ # production, the session would also be a cache access,+ # but tests don't use cached sessions.+ self.assert_length(cache_gets, 2)+ self.assertEqual(+ cache_gets[0],+ ("get", user_profile_narrow_by_id_cache_key(user_profile.id), None),+ )+ self.assertEqual(cache_gets[1][0], "get")+ assert isinstance(cache_gets[1][1], str)+ self.assertTrue(cache_gets[1][1].startswith("get_client:"))++ # Three database queries -- session, user, and client.+ # The user query should remain small; it is currently 470+ # bytes, but anything under 1k should be Fine.+ self.assert_length(queries, 3)+ self.assertIn("django_session", queries[0].sql)+ self.assertIn("zerver_userprofile", queries[1].sql)+ self.assertLessEqual(len(queries[1].sql), 1024)+ self.assertIn("zerver_client", queries[2].sql)++ # Perform the same request again, preserving the caches. We+ # should only see one database query -- the session. As noted+ # above, in production even that would be cached.+ with (+ self.mocked_events(user_profile, {"type": "test", "data": "test data"}),+ cache_tries_captured() as cache_gets,+ queries_captured(keep_cache_warm=True) as queries,+ ):+ await self.fetch_async("GET", path)+ self.assert_length(cache_gets, 1)+ self.assertEqual(+ cache_gets[0],+ ("get", user_profile_narrow_by_id_cache_key(user_profile.id), None),+ )+ # Client is cached in-process-memory, so doesn't even see+ # a memcached hit++ self.assert_length(queries, 1)+ self.assertIn("django_session", queries[0].sql)