Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
tests: Replace `HttpResponse` with `TestHttpResponse.`
Zixuan James Li426f8ce385f6
diff --git a/analytics/tests/test_support_views.py b/analytics/tests/test_support_views.pyindex a2370961d13..874421f662f 100644--- a/analytics/tests/test_support_views.py+++ b/analytics/tests/test_support_views.py@@ -1,8 +1,8 @@from datetime import datetime, timedelta, timezone+from typing import TYPE_CHECKINGfrom unittest import mockimport orjson-from django.http import HttpResponsefrom django.utils.timezone import now as timezone_nowfrom corporate.lib.stripe import add_months, update_sponsorship_status@@ -21,13 +21,16 @@ from zerver.models import (get_realm,)+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class TestSupportEndpoint(ZulipTestCase):def test_search(self) -> None:reset_emails_in_zulip_realm()def assert_user_details_in_html_response(- html_response: HttpResponse, full_name: str, email: str, role: str+ html_response: "TestHttpResponse", full_name: str, email: str, role: str) -> None:self.assert_in_success_response([@@ -40,7 +43,7 @@ class TestSupportEndpoint(ZulipTestCase):html_response,)- def check_hamlet_user_query_result(result: HttpResponse) -> None:+ def check_hamlet_user_query_result(result: "TestHttpResponse") -> None:assert_user_details_in_html_response(result, "King Hamlet", self.example_email("hamlet"), "Member")@@ -56,17 +59,17 @@ class TestSupportEndpoint(ZulipTestCase):result,)- def check_othello_user_query_result(result: HttpResponse) -> None:+ def check_othello_user_query_result(result: "TestHttpResponse") -> None:assert_user_details_in_html_response(result, "Othello, the Moor of Venice", self.example_email("othello"), "Member")- def check_polonius_user_query_result(result: HttpResponse) -> None:+ def check_polonius_user_query_result(result: "TestHttpResponse") -> None:assert_user_details_in_html_response(result, "Polonius", self.example_email("polonius"), "Guest")- def check_zulip_realm_query_result(result: HttpResponse) -> None:+ def check_zulip_realm_query_result(result: "TestHttpResponse") -> None:zulip_realm = get_realm("zulip")first_human_user = zulip_realm.get_first_human_user()assert first_human_user is not None@@ -87,7 +90,7 @@ class TestSupportEndpoint(ZulipTestCase):result,)- def check_lear_realm_query_result(result: HttpResponse) -> None:+ def check_lear_realm_query_result(result: "TestHttpResponse") -> None:lear_realm = get_realm("lear")self.assert_in_success_response([@@ -113,7 +116,7 @@ class TestSupportEndpoint(ZulipTestCase):)def check_preregistration_user_query_result(- result: HttpResponse, email: str, invite: bool = False+ result: "TestHttpResponse", email: str, invite: bool = False) -> None:self.assert_in_success_response([@@ -142,7 +145,7 @@ class TestSupportEndpoint(ZulipTestCase):result,)- def check_realm_creation_query_result(result: HttpResponse, email: str) -> None:+ def check_realm_creation_query_result(result: "TestHttpResponse", email: str) -> None:self.assert_in_success_response(['<span class="label">preregistration user</span>\n',@@ -153,7 +156,7 @@ class TestSupportEndpoint(ZulipTestCase):result,)- def check_multiuse_invite_link_query_result(result: HttpResponse) -> None:+ def check_multiuse_invite_link_query_result(result: "TestHttpResponse") -> None:self.assert_in_success_response(['<span class="label">multiuse invite</span>\n',@@ -163,7 +166,7 @@ class TestSupportEndpoint(ZulipTestCase):result,)- def check_realm_reactivation_link_query_result(result: HttpResponse) -> None:+ def check_realm_reactivation_link_query_result(result: "TestHttpResponse") -> None:self.assert_in_success_response(['<span class="label">realm reactivation</span>\n',diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex b660eb98e76..4a009f0833f 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -9,7 +9,18 @@ from dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom decimal import Decimalfrom functools import wraps-from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ List,+ Mapping,+ Optional,+ Sequence,+ Tuple,+ TypeVar,+)from unittest.mock import Mock, patchimport orjson@@ -18,7 +29,6 @@ import stripeimport stripe.utilfrom django.conf import settingsfrom django.core import signing-from django.http import HttpResponsefrom django.urls.resolvers import get_resolverfrom django.utils.crypto import get_random_stringfrom django.utils.timezone import now as timezone_now@@ -103,6 +113,9 @@ from zerver.models import ()from zilencer.models import RemoteZulipServer, RemoteZulipServerAuditLog+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+CallableT = TypeVar("CallableT", bound=Callable[..., Any])ParamT = ParamSpec("ParamT")ReturnT = TypeVar("ReturnT")@@ -422,11 +435,11 @@ class StripeTestCase(ZulipTestCase):self.next_month = datetime(2012, 2, 2, 3, 4, 5, tzinfo=timezone.utc)self.next_year = datetime(2013, 1, 2, 3, 4, 5, tzinfo=timezone.utc)- def get_signed_seat_count_from_response(self, response: HttpResponse) -> Optional[str]:+ def get_signed_seat_count_from_response(self, response: "TestHttpResponse") -> Optional[str]:match = re.search(r"name=\"signed_seat_count\" value=\"(.+)\"", response.content.decode())return match.group(1) if match else None- def get_salt_from_response(self, response: HttpResponse) -> Optional[str]:+ def get_salt_from_response(self, response: "TestHttpResponse") -> Optional[str]:match = re.search(r"name=\"salt\" value=\"(\w+)\"", response.content.decode())return match.group(1) if match else None@@ -533,10 +546,10 @@ class StripeTestCase(ZulipTestCase):onboarding: bool = False,realm: Optional[Realm] = None,payment_method: Optional[stripe.PaymentMethod] = None,- upgrade_page_response: HttpResponse = None,+ upgrade_page_response: Optional["TestHttpResponse"] = None,del_args: Sequence[str] = [],**kwargs: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":host_args = {}if realm is not None: # nocoverage: TODOhost_args["HTTP_HOST"] = realm.hostdiff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 7a11d4387e3..6fb9a8423bc 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -8,6 +8,7 @@ import urllibfrom contextlib import contextmanagerfrom datetime import timedeltafrom typing import (+ TYPE_CHECKING,Any,Callable,Collection,@@ -108,6 +109,9 @@ from zerver.tornado.event_queue import clear_client_event_queues_for_testingif settings.ZILENCER_ENABLED:from zilencer.models import get_remote_server_by_uuid+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class EmptyResponseError(Exception):pass@@ -254,7 +258,7 @@ Output:self,url: str,method: str,- result: HttpResponse,+ result: "TestHttpResponse",data: Union[str, bytes, Dict[str, Any]],kwargs: Dict[str, ClientArg],intentionally_undocumented: bool = False,@@ -302,7 +306,7 @@ Output:info: Dict[str, Any] = {},intentionally_undocumented: bool = False,**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""We need to urlencode, since Django's function won't do it for us."""@@ -323,7 +327,7 @@ Output:@instrument_urldef client_patch_multipart(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""Use this for patch requests that have file uploads orthat need some sort of multi-part content. In the future@@ -341,20 +345,24 @@ Output:def json_patch(self, url: str, payload: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":data = orjson.dumps(payload)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)return django_client.patch(url, data=data, content_type="application/json", **kwargs)@instrument_url- def client_put(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg) -> HttpResponse:+ def client_put(+ self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg+ ) -> "TestHttpResponse":encoded = urllib.parse.urlencode(info)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)return django_client.put(url, encoded, **kwargs)- def json_put(self, url: str, payload: Dict[str, Any] = {}, **kwargs: ClientArg) -> HttpResponse:+ def json_put(+ self, url: str, payload: Dict[str, Any] = {}, **kwargs: ClientArg+ ) -> "TestHttpResponse":data = orjson.dumps(payload)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)@@ -363,7 +371,7 @@ Output:@instrument_urldef client_delete(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":encoded = urllib.parse.urlencode(info)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)@@ -374,14 +382,16 @@ Output:@instrument_urldef client_options(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":encoded = urllib.parse.urlencode(info)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)return django_client.options(url, encoded, **kwargs)@instrument_url- def client_head(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg) -> HttpResponse:+ def client_head(+ self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg+ ) -> "TestHttpResponse":encoded = urllib.parse.urlencode(info)django_client = self.client # see WRAPPER_COMMENTself.set_http_headers(kwargs)@@ -393,7 +403,7 @@ Output:url: str,info: Union[str, bytes, Dict[str, Any]] = {},**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":intentionally_undocumented = kwargs.pop("intentionally_undocumented", False)assert isinstance(intentionally_undocumented, bool)django_client = self.client # see WRAPPER_COMMENT@@ -405,7 +415,7 @@ Output:return result@instrument_url- def client_post_request(self, url: str, req: Any) -> HttpResponse:+ def client_post_request(self, url: str, req: Any) -> "TestHttpResponse":"""We simulate hitting an endpoint here, although weactually resolve the URL manually and hit the view@@ -419,7 +429,9 @@ Output:return match.func(req)@instrument_url- def client_get(self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg) -> HttpResponse:+ def client_get(+ self, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg+ ) -> "TestHttpResponse":intentionally_undocumented = kwargs.pop("intentionally_undocumented", False)assert isinstance(intentionally_undocumented, bool)django_client = self.client # see WRAPPER_COMMENT@@ -539,7 +551,7 @@ Output:result = self.client_post("/json/bots", bot_info)self.assert_json_error(result, assert_json_error_msg)- def _get_page_params(self, result: HttpResponse) -> Dict[str, Any]:+ def _get_page_params(self, result: "TestHttpResponse") -> Dict[str, Any]:"""Helper for parsing page_params after fetching the web app's home view."""doc = lxml.html.document_fromstring(result.content)div = cast(lxml.html.HtmlMixin, doc).get_element_by_id("page-params")@@ -549,7 +561,7 @@ Output:page_params = orjson.loads(page_params_json)return page_params- def check_rendered_logged_in_app(self, result: HttpResponse) -> None:+ def check_rendered_logged_in_app(self, result: "TestHttpResponse") -> None:"""Verifies that a visit of / was a 200 that rendered page_paramsand not for a (logged-out) spectator."""self.assertEqual(result.status_code, 200)@@ -561,7 +573,7 @@ Output:def login_with_return(self, email: str, password: Optional[str] = None, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":if password is None:password = initial_password(email)result = self.client_post(@@ -638,7 +650,7 @@ Output:def logout(self) -> None:self.client.logout()- def register(self, email: str, password: str, **kwargs: Any) -> HttpResponse:+ def register(self, email: str, password: str, **kwargs: Any) -> "TestHttpResponse":self.client_post("/accounts/home/", {"email": email}, **kwargs)return self.submit_reg_form_for_user(email, password, **kwargs)@@ -659,7 +671,7 @@ Output:enable_marketing_emails: Optional[bool] = None,is_demo_organization: bool = False,**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""Stage two of the two-step registration process.@@ -756,7 +768,7 @@ Output:def uuid_get(self, identifier: str, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)return self.client_get(url, info, **kwargs)@@ -766,13 +778,13 @@ Output:url: str,info: Union[str, bytes, Dict[str, Any]] = {},**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)return self.client_post(url, info, **kwargs)def api_get(self, user: UserProfile, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)return self.client_get(url, info, **kwargs)@@ -782,7 +794,7 @@ Output:url: str,info: Union[str, bytes, Dict[str, Any]] = {},**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)return self.client_post(url, info, **kwargs)@@ -793,7 +805,7 @@ Output:info: Dict[str, Any] = {},intentionally_undocumented: bool = False,**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)return self.client_patch(url, info, intentionally_undocumented=intentionally_undocumented, **kwargs@@ -801,7 +813,7 @@ Output:def api_delete(self, user: UserProfile, url: str, info: Dict[str, Any] = {}, **kwargs: ClientArg- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)return self.client_delete(url, info, **kwargs)@@ -927,12 +939,14 @@ Output:return [subscription.user_profile for subscription in subscriptions]- def assert_streaming_content(self, response: HttpResponse, result: bytes) -> None:+ def assert_streaming_content(self, response: "TestHttpResponse", result: bytes) -> None:assert isinstance(response, StreamingHttpResponse)data = b"".join(response.streaming_content)self.assertEqual(result, data)- def assert_json_success(self, result: HttpResponse) -> Dict[str, Any]:+ def assert_json_success(+ self, result: Union["TestHttpResponse", HttpResponse]+ ) -> Dict[str, Any]:"""Successful POSTs return a 200 and JSON of the form {"result": "success","msg": ""}.@@ -949,7 +963,7 @@ Output:self.assertNotEqual(json["msg"], "Error parsing JSON in response!")return json- def get_json_error(self, result: HttpResponse, status_code: int = 400) -> str:+ def get_json_error(self, result: "TestHttpResponse", status_code: int = 400) -> str:try:json = orjson.loads(result.content)except orjson.JSONDecodeError: # nocoverage@@ -958,7 +972,9 @@ Output:self.assertEqual(json.get("result"), "error")return json["msg"]- def assert_json_error(self, result: HttpResponse, msg: str, status_code: int = 400) -> None:+ def assert_json_error(+ self, result: "TestHttpResponse", msg: str, status_code: int = 400+ ) -> None:"""Invalid POSTs return an error status code and JSON of the form{"result": "error", "msg": "reason"}.@@ -975,20 +991,26 @@ Output:raise AssertionError(f"{str(type(items))} is of unexpected size!")def assert_json_error_contains(- self, result: HttpResponse, msg_substring: str, status_code: int = 400+ self, result: "TestHttpResponse", msg_substring: str, status_code: int = 400) -> None:self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))- def assert_in_response(self, substring: str, response: HttpResponse) -> None:+ def assert_in_response(+ self, substring: str, response: Union["TestHttpResponse", HttpResponse]+ ) -> None:self.assertIn(substring, response.content.decode())- def assert_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:+ def assert_in_success_response(+ self, substrings: List[str], response: "TestHttpResponse"+ ) -> None:self.assertEqual(response.status_code, 200)decoded = response.content.decode()for substring in substrings:self.assertIn(substring, decoded)- def assert_not_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:+ def assert_not_in_success_response(+ self, substrings: List[str], response: "TestHttpResponse"+ ) -> None:self.assertEqual(response.status_code, 200)decoded = response.content.decode()for substring in substrings:@@ -1093,7 +1115,7 @@ Output:is_web_public: bool = False,allow_fail: bool = False,**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":post_data = {"subscriptions": orjson.dumps([{"name": stream} for stream in streams]).decode(),"is_web_public": orjson.dumps(is_web_public).decode(),@@ -1637,7 +1659,7 @@ You can fix this by adding "{complete_event_type}" to ALL_EVENT_TYPES for this wcontent_type: Optional[str] = "application/json",expect_noop: bool = False,**kwargs: ClientArg,- ) -> HttpResponse:+ ) -> "TestHttpResponse":kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)return self.check_webhook(fixture_name, expected_topic, expected_message, content_type, expect_noop, **kwargsdiff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.pyindex 9d64f0e819c..61bf77d00a8 100644--- a/zerver/lib/test_helpers.py+++ b/zerver/lib/test_helpers.py@@ -33,6 +33,7 @@ from django.contrib.auth.models import AnonymousUserfrom django.db.migrations.state import StateAppsfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.http.request import QueryDict+from django.http.response import HttpResponseBasefrom django.test import override_settingsfrom django.urls import URLResolverfrom moto import mock_s3@@ -64,6 +65,8 @@ from zilencer.models import RemoteZulipServerfrom zproject.backends import ExternalAuthDataDict, ExternalAuthResultif TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+# Avoid an import cycle; we only need these for type annotations.from zerver.lib.test_classes import ClientArg, MigrationsTestCase, ZulipTestCase@@ -349,7 +352,7 @@ class HostRequestMock(HttpRequest):INSTRUMENTING = os.environ.get("TEST_INSTRUMENT_URL_COVERAGE", "") == "TRUE"INSTRUMENTED_CALLS: List[Dict[str, Any]] = []-UrlFuncT = TypeVar("UrlFuncT", bound=Callable[..., HttpResponse]) # TODO: make more specific+UrlFuncT = TypeVar("UrlFuncT", bound=Callable[..., HttpResponseBase]) # TODO: make more specificdef append_instrumentation_data(data: Dict[str, Any]) -> None:@@ -363,7 +366,7 @@ def instrument_url(f: UrlFuncT) -> UrlFuncT:def wrapper(self: "ZulipTestCase", url: str, info: object = {}, **kwargs: "ClientArg"- ) -> HttpResponse:+ ) -> HttpResponseBase:start = time.time()result = f(self, url, info, **kwargs)delay = time.time() - start@@ -532,7 +535,7 @@ def write_instrumentation_reports(full_suite: bool, include_webhooks: bool) -> Nsys.exit(1)-def load_subdomain_token(response: HttpResponse) -> ExternalAuthDataDict:+def load_subdomain_token(response: Union["TestHttpResponse", HttpResponse]) -> ExternalAuthDataDict:assert isinstance(response, HttpResponseRedirect)token = response.url.rsplit("/", 1)[1]data = ExternalAuthResult(login_token=token, delete_stored_data=False).data_dictdiff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 65b174a88e9..5781ea3d1c6 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -9,7 +9,19 @@ import timeimport urllibfrom abc import ABC, abstractmethodfrom contextlib import contextmanager-from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ Iterator,+ List,+ Mapping,+ Optional,+ Sequence,+ Tuple,+ Type,+)from unittest import mockfrom urllib.parse import urlencode@@ -24,7 +36,7 @@ from cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom django.conf import settingsfrom django.contrib.auth import authenticatefrom django.core import mail-from django.http import HttpRequest, HttpResponse+from django.http import HttpRequestfrom django.test import override_settingsfrom django.test.client import RequestFactoryfrom django.urls import reverse@@ -142,6 +154,9 @@ from zproject.backends import (sync_user_from_ldap,)+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class AuthBackendTest(ZulipTestCase):def get_username(self, email_to_username: Optional[Callable[[str], str]] = None) -> str:@@ -535,7 +550,7 @@ class AuthBackendTest(ZulipTestCase):}def patched_authenticate(- request: Optional[HttpResponse] = None,+ request: Optional["TestHttpResponse"] = None,**kwargs: Any,) -> Any:# This is how we pass the subdomain to the authentication@@ -796,12 +811,12 @@ class CheckPasswordStrengthTest(ZulipTestCase):class DesktopFlowTestingLib(ZulipTestCase):- def verify_desktop_flow_app_page(self, response: HttpResponse) -> None:+ def verify_desktop_flow_app_page(self, response: "TestHttpResponse") -> None:self.assertEqual(response.status_code, 200)self.assertIn(b"<h1>Finish desktop login</h1>", response.content)def verify_desktop_flow_end_page(- self, response: HttpResponse, email: str, desktop_flow_otp: str+ self, response: "TestHttpResponse", email: str, desktop_flow_otp: str) -> None:self.assertEqual(response.status_code, 200)@@ -930,12 +945,12 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):def social_auth_test_finish(self,- result: HttpResponse,+ result: "TestHttpResponse",account_data_dict: Dict[str, str],expect_choose_email_screen: bool,headers: Any,**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":parsed_url = urllib.parse.urlparse(result["Location"])csrf_state = urllib.parse.parse_qs(parsed_url.query)["state"]result = self.client_get(self.AUTH_FINISH_URL, dict(state=csrf_state), **headers)@@ -963,7 +978,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):alternative_start_url: Optional[str] = None,user_agent: Optional[str] = None,**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""Main entry point for all social authentication tests.* account_data_dict: Dictionary containing the name/email data@@ -1350,7 +1365,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):def stage_two_of_registration(self,- result: HttpResponse,+ result: "TestHttpResponse",realm: Realm,subdomain: str,email: str,@@ -1895,7 +1910,7 @@ class SAMLAuthBackendTest(SocialAuthBase):user_agent: Optional[str] = None,extra_attributes: Mapping[str, List[str]] = {},**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":url, headers = self.prepare_login_url_and_headers(subdomain,mobile_flow_otp,@@ -2011,7 +2026,7 @@ class SAMLAuthBackendTest(SocialAuthBase):def make_idp_initiated_logout_request(self, email: str, make_validity_checks_pass: bool = True- ) -> HttpResponse:+ ) -> "TestHttpResponse":samlrequest = self.generate_saml_logout_request_from_idp(email)parameters = {"SAMLRequest": samlrequest}@@ -2962,12 +2977,12 @@ class AppleIdAuthBackendTest(AppleAuthMixin, SocialAuthBase):def social_auth_test_finish(self,- result: HttpResponse,+ result: "TestHttpResponse",account_data_dict: Dict[str, str],expect_choose_email_screen: bool,headers: Any,**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":parsed_url = urllib.parse.urlparse(result["Location"])state = urllib.parse.parse_qs(parsed_url.query)["state"]user_param = json.dumps(account_data_dict)@@ -3140,7 +3155,7 @@ class AppleAuthBackendNativeFlowTest(AppleAuthMixin, SocialAuthBase):skip_id_token: bool = False,user_agent: Optional[str] = None,**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""In Apple's native authentication flow, the client app authenticateswith Apple and receives the JWT id_token, before contactingthe Zulip server. The app sends an appropriate request with@@ -3305,7 +3320,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):self,*args: Any,**kwargs: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":# Example payload of the discovery endpoint (with appropriate values filled# in to match our test setup).# All the attributes below are REQUIRED per OIDC specification:@@ -3344,7 +3359,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):return result- def social_auth_test_finish(self, *args: Any, **kwargs: Any) -> HttpResponse:+ def social_auth_test_finish(self, *args: Any, **kwargs: Any) -> "TestHttpResponse":# Trying to generate a (access_token, id_token) pair here in tests that would# successfully pass validation by validate_and_return_id_token is impractical# and unnecessary (see python-social-auth implementation of the method for@@ -3512,13 +3527,13 @@ class GitHubAuthBackendTest(SocialAuthBase):def social_auth_test_finish(self,- result: HttpResponse,+ result: "TestHttpResponse",account_data_dict: Dict[str, str],expect_choose_email_screen: bool,headers: Any,expect_noreply_email_allowed: bool = False,**extra_data: Any,- ) -> HttpResponse:+ ) -> "TestHttpResponse":parsed_url = urllib.parse.urlparse(result["Location"])csrf_state = urllib.parse.parse_qs(parsed_url.query)["state"]result = self.client_get(self.AUTH_FINISH_URL, dict(state=csrf_state), **headers)@@ -4151,7 +4166,7 @@ class GoogleAuthBackendTest(SocialAuthBase):*,subdomain: str = "zulip",force_token: Optional[str] = None,- ) -> HttpResponse:+ ) -> "TestHttpResponse":if force_token is None:token = ExternalAuthResult(data_dict=data).store_data()else:@@ -4160,7 +4175,7 @@ class GoogleAuthBackendTest(SocialAuthBase):return self.client_get(url_path, subdomain=subdomain)def test_redirect_to_next_url_for_log_into_subdomain(self) -> None:- def test_redirect_to_next_url(next: str = "") -> HttpResponse:+ def test_redirect_to_next_url(next: str = "") -> "TestHttpResponse":data: ExternalAuthDataDict = {"full_name": "Hamlet","email": self.example_email("hamlet"),@@ -4802,7 +4817,7 @@ class ExternalMethodDictsTests(ZulipTestCase):class FetchAuthBackends(ZulipTestCase):def test_get_server_settings(self) -> None:def check_result(- result: HttpResponse, extra_fields: Sequence[Tuple[str, Validator[object]]] = []+ result: "TestHttpResponse", extra_fields: Sequence[Tuple[str, Validator[object]]] = []) -> None:authentication_methods_list = [("password", check_bool),@@ -4991,7 +5006,7 @@ class TestDevAuthBackend(ZulipTestCase):self.assertIn("otp_device_id", list(self.client.session.keys()))def test_redirect_to_next_url(self) -> None:- def do_local_login(formaction: str) -> HttpResponse:+ def do_local_login(formaction: str) -> "TestHttpResponse":user_email = self.example_email("hamlet")data = {"direct_email": user_email}return self.client_post(formaction, data)@@ -5365,7 +5380,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):"""This test verifies the behavior of the redirect_to logic inlogin_or_register_remote_user."""- def test_with_redirect_to_param_set_as_next(next: str = "") -> HttpResponse:+ def test_with_redirect_to_param_set_as_next(next: str = "") -> "TestHttpResponse":user_profile = self.example_user("hamlet")email = user_profile.delivery_emailwith self.settings(@@ -6621,9 +6636,9 @@ class TestMaybeSendToRegistration(ZulipTestCase):self.assertIn("do_confirm/" + confirmation_key, result["Location"])self.assertEqual(PreregistrationUser.objects.all().count(), 1)- result = self.client_get(result["Location"])- self.assert_in_response('action="/accounts/register/"', result)- self.assert_in_response(f'value="{confirmation_key}" name="key"', result)+ response = self.client_get(result["Location"])+ self.assert_in_response('action="/accounts/register/"', response)+ self.assert_in_response(f'value="{confirmation_key}" name="key"', response)def test_sso_only_when_preregistration_user_exists(self) -> None:rf = RequestFactory(HTTP_HOST=Realm.host_for_subdomain("zulip"))diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.pyindex 39f96626499..d4d800f10f2 100644--- a/zerver/tests/test_decorators.py+++ b/zerver/tests/test_decorators.py@@ -4,7 +4,7 @@ import reimport uuidfrom collections import defaultdictfrom functools import lru_cache-from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuplefrom unittest import mock, skipUnlessimport orjson@@ -90,6 +90,9 @@ from zerver.models import Realm, UserProfile, get_realm, get_userif settings.ZILENCER_ENABLED:from zilencer.models import RemoteZulipServer+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class DecoratorTestCase(ZulipTestCase):def test_parse_client(self) -> None:@@ -1772,7 +1775,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):)do_reactivate_realm(user_profile.realm)- def _do_test(self, user: UserProfile) -> HttpResponse:+ def _do_test(self, user: UserProfile) -> "TestHttpResponse":stream_name = "stream name"self.common_subscribe_to_streams(user, [stream_name], allow_fail=True)data = {"password": initial_password(user.email), "stream": stream_name}@@ -1815,7 +1818,7 @@ class TestAuthenticatedJsonViewDecorator(ZulipTestCase):],)- def _do_test(self, user_email: str) -> HttpResponse:+ def _do_test(self, user_email: str) -> "TestHttpResponse":data = {"password": initial_password(user_email)}return self.client_post(r"/accounts/webathena_kerberos_login/", data)diff --git a/zerver/tests/test_docs.py b/zerver/tests/test_docs.pyindex c9416e1be4d..72571bf4fad 100644--- a/zerver/tests/test_docs.py+++ b/zerver/tests/test_docs.py@@ -1,12 +1,11 @@import osimport re-from typing import Any, Dict, Sequence+from typing import TYPE_CHECKING, Any, Dict, Sequencefrom unittest import mock, skipUnlessfrom urllib.parse import urlsplitimport orjsonfrom django.conf import settings-from django.http import HttpResponsefrom django.test import override_settingsfrom django.utils.timezone import now as timezone_now@@ -18,14 +17,17 @@ from zerver.lib.test_helpers import HostRequestMockfrom zerver.models import Realm, get_realmfrom zerver.views.documentation import add_api_uri_context+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class DocPageTest(ZulipTestCase):- def get_doc(self, url: str, subdomain: str) -> HttpResponse:+ def get_doc(self, url: str, subdomain: str) -> "TestHttpResponse":if url[0:23] == "/integrations/doc-html/":return self.client_get(url, subdomain=subdomain, HTTP_X_REQUESTED_WITH="XMLHttpRequest")return self.client_get(url, subdomain=subdomain)- def print_msg_if_error(self, url: str, response: HttpResponse) -> None: # nocoverage+ def print_msg_if_error(self, url: str, response: "TestHttpResponse") -> None: # nocoverageif response.status_code == 200:returnprint("Error processing URL:", url)diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex c61e8560caa..eca373b1bcc 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -4,12 +4,11 @@ import osimport subprocessfrom email import message_from_stringfrom email.message import EmailMessage, MIMEPart-from typing import Any, Callable, Dict, Mapping, Optional+from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optionalfrom unittest import mockimport orjsonfrom django.conf import settings-from django.http import HttpResponsefrom zerver.actions.realm_settings import do_deactivate_realmfrom zerver.actions.streams import do_change_stream_post_policy@@ -50,6 +49,9 @@ from zerver.models import ()from zerver.worker.queue_processors import MirrorWorker+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+logger_name = "zerver.lib.email_mirror"@@ -1357,7 +1359,7 @@ class TestEmailMirrorTornadoView(ZulipTestCase):user_message = most_recent_usermessage(user_profile)return create_missed_message_address(user_profile, user_message.message)- def send_offline_message(self, to_address: str, sender: UserProfile) -> HttpResponse:+ def send_offline_message(self, to_address: str, sender: UserProfile) -> "TestHttpResponse":mail_template = self.fixture_data("simple.txt", type="email")mail = mail_template.format(stream_to_address=to_address, sender=sender.delivery_email)msg_base64 = base64.b64encode(mail.encode()).decode()diff --git a/zerver/tests/test_external.py b/zerver/tests/test_external.pyindex 6a911f14f67..243a6b828fb 100644--- a/zerver/tests/test_external.py+++ b/zerver/tests/test_external.py@@ -1,7 +1,7 @@import timeimport uuidfrom contextlib import contextmanager-from typing import IO, Any, Callable, Iterator, Optional, Sequence+from typing import IO, TYPE_CHECKING, Any, Callable, Iterator, Optional, Sequencefrom unittest import mock, skipUnlessimport DNS@@ -9,7 +9,6 @@ import orjsonfrom circuitbreaker import CircuitBreakerMonitorfrom django.conf import settingsfrom django.core.exceptions import ValidationError-from django.http import HttpResponsefrom django.test import override_settingsfrom django.utils.timezone import now as timezone_now@@ -30,6 +29,9 @@ from zerver.models import PushDeviceToken, UserProfileif settings.ZILENCER_ENABLED:from zilencer.models import RateLimitedRemoteZulipServer, RemoteZulipServer+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class MITNameTest(ZulipTestCase):def test_valid_hesiod(self) -> None:@@ -109,7 +111,7 @@ class RateLimitTests(ZulipTestCase):super().tearDown()- def send_api_message(self, user: UserProfile, content: str) -> HttpResponse:+ def send_api_message(self, user: UserProfile, content: str) -> "TestHttpResponse":return self.api_post(user,"/api/v1/messages",@@ -121,7 +123,7 @@ class RateLimitTests(ZulipTestCase):},)- def send_unauthed_api_request(self, **kwargs: Any) -> HttpResponse:+ def send_unauthed_api_request(self, **kwargs: Any) -> "TestHttpResponse":result = self.client_get("/json/messages", **kwargs)# We're not making a correct request here, but rate-limiting is supposed# to happen before the request fails due to not being correctly made. Thus@@ -136,9 +138,9 @@ class RateLimitTests(ZulipTestCase):RateLimitedUser(user).clear_history()result = self.send_api_message(user, "some stuff")- self.assertTrue("X-RateLimit-Remaining" in result)- self.assertTrue("X-RateLimit-Limit" in result)- self.assertTrue("X-RateLimit-Reset" in result)+ self.assertTrue("X-RateLimit-Remaining" in result.headers)+ self.assertTrue("X-RateLimit-Limit" in result.headers)+ self.assertTrue("X-RateLimit-Reset" in result.headers)def test_ratelimit_decrease(self) -> None:user = self.example_user("hamlet")@@ -152,20 +154,20 @@ class RateLimitTests(ZulipTestCase):def do_test_hit_ratelimits(self,- request_func: Callable[[], HttpResponse],+ request_func: Callable[[], "TestHttpResponse"],is_json: bool = True,- ) -> HttpResponse:- def api_assert_func(result: HttpResponse) -> None:+ ) -> None:+ def api_assert_func(result: "TestHttpResponse") -> None:self.assertEqual(result.status_code, 429)self.assertEqual(result.headers["Content-Type"], "application/json")json = result.json()self.assertEqual(json.get("result"), "error")self.assertIn("API usage exceeded rate limit", json.get("msg"))self.assertEqual(json.get("retry-after"), 0.5)- self.assertTrue("Retry-After" in result)+ self.assertTrue("Retry-After" in result.headers)self.assertEqual(result["Retry-After"], "0.5")- def user_facing_assert_func(result: HttpResponse) -> None:+ def user_facing_assert_func(result: "TestHttpResponse") -> None:self.assertEqual(result.status_code, 429)self.assertNotEqual(result.headers["Content-Type"], "application/json")self.assert_in_response("Rate limit exceeded.", result)@@ -282,7 +284,7 @@ class RateLimitTests(ZulipTestCase):# Alternate requests to /new/ and /accounts/find/request_count = 0- def alternate_requests() -> HttpResponse:+ def alternate_requests() -> "TestHttpResponse":nonlocal request_countrequest_count += 1if request_count % 2 == 1:@@ -333,7 +335,7 @@ class RateLimitTests(ZulipTestCase):for ip in ["1.2.3.4", "5.6.7.8", "tor-exit-node"]:RateLimitedIPAddr(ip, domain="api_by_ip").clear_history()- def alternate_requests() -> HttpResponse:+ def alternate_requests() -> "TestHttpResponse":nonlocal request_countrequest_count += 1if request_count % 2 == 1:diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 2b9f730d4be..e706a7a9115 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -2,13 +2,12 @@ import calendarimport datetimeimport urllibfrom datetime import timedelta-from typing import Any+from typing import TYPE_CHECKING, Anyfrom unittest.mock import patchimport orjsonimport pytzfrom django.conf import settings-from django.http import HttpResponsefrom django.test import override_settingsfrom django.utils.timezone import now as timezone_now@@ -39,6 +38,9 @@ from zerver.models import ()from zerver.worker.queue_processors import UserActivityWorker+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+logger_string = "zulip.soft_deactivation"@@ -430,14 +432,14 @@ class HomeTest(ZulipTestCase):html = result.content.decode()self.assertIn("test_stream_7", html)- def _get_home_page(self, **kwargs: Any) -> HttpResponse:+ def _get_home_page(self, **kwargs: Any) -> "TestHttpResponse":with patch("zerver.lib.events.request_event_queue", return_value=42), patch("zerver.lib.events.get_user_events", return_value=[]):result = self.client_get("/", dict(**kwargs))return result- def _sanity_check(self, result: HttpResponse) -> None:+ def _sanity_check(self, result: "TestHttpResponse") -> None:"""Use this for tests that are geared toward specific edge cases, butwhich still want the home page to load properly.diff --git a/zerver/tests/test_i18n.py b/zerver/tests/test_i18n.pyindex 373bcda46f8..1a7a819462f 100644--- a/zerver/tests/test_i18n.py+++ b/zerver/tests/test_i18n.py@@ -1,11 +1,10 @@from http.cookies import SimpleCookie-from typing import Any+from typing import TYPE_CHECKING, Anyfrom unittest import mockimport orjsonfrom django.conf import settingsfrom django.core import mail-from django.http import HttpResponsefrom django.utils import translationfrom zerver.lib.email_notifications import enqueue_welcome_emails@@ -15,6 +14,9 @@ from zerver.lib.test_helpers import HostRequestMockfrom zerver.management.commands import makemessagesfrom zerver.models import get_realm_stream+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class EmailTranslationTestCase(ZulipTestCase):def test_email_translation(self) -> None:@@ -81,7 +83,9 @@ class TranslationTestCase(ZulipTestCase):super().tearDown()# e.g. self.client_post(url) if method is "post"- def fetch(self, method: str, url: str, expected_status: int, **kwargs: Any) -> HttpResponse:+ def fetch(+ self, method: str, url: str, expected_status: int, **kwargs: Any+ ) -> "TestHttpResponse":response = getattr(self.client, method)(url, **kwargs)self.assertEqual(response.status_code,diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.pyindex 8ec6a49d449..50bb956cc01 100644--- a/zerver/tests/test_message_edit.py+++ b/zerver/tests/test_message_edit.py@@ -1,11 +1,10 @@import datetimefrom operator import itemgetter-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Unionfrom unittest import mockimport orjsonfrom django.db import IntegrityError-from django.http import HttpResponsefrom django.utils.timezone import now as timezone_nowfrom zerver.actions.message_edit import (@@ -31,6 +30,9 @@ from zerver.lib.user_topics import (from zerver.lib.utils import assert_is_not_nonefrom zerver.models import Message, Realm, Stream, UserMessage, UserProfile, get_realm, get_stream+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class EditMessageTestCase(ZulipTestCase):def check_topic(self, msg_id: int, topic_name: str) -> None:@@ -2730,17 +2732,17 @@ class DeleteMessageTest(ZulipTestCase):)self.assert_json_success(result)- def test_delete_message_by_admin(msg_id: int) -> HttpResponse:+ def test_delete_message_by_admin(msg_id: int) -> "TestHttpResponse":self.login("iago")result = self.client_delete(f"/json/messages/{msg_id}")return result- def test_delete_message_by_owner(msg_id: int) -> HttpResponse:+ def test_delete_message_by_owner(msg_id: int) -> "TestHttpResponse":self.login("hamlet")result = self.client_delete(f"/json/messages/{msg_id}")return result- def test_delete_message_by_other_user(msg_id: int) -> HttpResponse:+ def test_delete_message_by_other_user(msg_id: int) -> "TestHttpResponse":self.login("cordelia")result = self.client_delete(f"/json/messages/{msg_id}")return resultdiff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 2e8e604c931..37343028655 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -1,11 +1,10 @@import datetimeimport os-from typing import Any, Dict, List, Optional, Sequence, Tuple, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Unionfrom unittest import mockimport orjsonfrom django.db import connection-from django.http import HttpResponsefrom django.test import override_settingsfrom django.utils.timezone import now as timezone_nowfrom sqlalchemy.sql import ClauseElement, Select, and_, column, select, table@@ -59,6 +58,9 @@ from zerver.views.message_fetch import (post_process_limited_query,)+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+def get_sqlalchemy_sql(query: ClauseElement) -> str:with get_sqlalchemy_connection() as conn:@@ -1610,7 +1612,7 @@ class GetOldMessagesTest(ZulipTestCase):self.logout()def verify_web_public_query_result_success(- self, result: HttpResponse, expected_num_messages: int+ self, result: "TestHttpResponse", expected_num_messages: int) -> None:self.assert_json_success(result)messages = orjson.loads(result.content)["messages"]diff --git a/zerver/tests/test_message_flags.py b/zerver/tests/test_message_flags.pyindex 578e4cd33be..c46a336dee5 100644--- a/zerver/tests/test_message_flags.py+++ b/zerver/tests/test_message_flags.py@@ -1,9 +1,8 @@-from typing import Any, List, Mapping, Set+from typing import TYPE_CHECKING, Any, List, Mapping, Setfrom unittest import mockimport orjsonfrom django.db import connection-from django.http import HttpResponsefrom zerver.actions.message_flags import do_update_message_flagsfrom zerver.actions.streams import do_change_stream_permission@@ -35,6 +34,9 @@ from zerver.models import (get_stream,)+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+def check_flags(flags: List[str], expected: Set[str]) -> None:"""@@ -1019,7 +1021,9 @@ class MessageAccessTests(ZulipTestCase):)self.assert_json_error(result, "Invalid message flag operation: 'bogus'")- def change_star(self, messages: List[int], add: bool = True, **kwargs: Any) -> HttpResponse:+ def change_star(+ self, messages: List[int], add: bool = True, **kwargs: Any+ ) -> "TestHttpResponse":return self.client_post("/json/messages/flags",{diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex 2f718cf0de6..54222821fb2 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -1,12 +1,11 @@import datetime-from typing import Any, List, Mapping, Optional, Set+from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Setfrom unittest import mockimport orjsonimport pytzfrom django.conf import settingsfrom django.db.models import Q-from django.http import HttpResponsefrom django.test import override_settingsfrom django.utils.timezone import now as timezone_now@@ -66,6 +65,9 @@ from zerver.models import ()from zerver.views.message_send import InvalidMirrorInput+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class MessagePOSTTest(ZulipTestCase):def _send_and_verify_message(@@ -1350,7 +1352,7 @@ class ScheduledMessageTest(ZulipTestCase):tz_guess: str = "",delivery_type: str = "send_later",realm_str: str = "zulip",- ) -> HttpResponse:+ ) -> "TestHttpResponse":self.login("hamlet")topic_name = ""diff --git a/zerver/tests/test_reactions.py b/zerver/tests/test_reactions.pyindex 1d2e75405f6..32ecfa2f19f 100644--- a/zerver/tests/test_reactions.py+++ b/zerver/tests/test_reactions.py@@ -1,8 +1,7 @@-from typing import Any, Dict, List, Mapping+from typing import TYPE_CHECKING, Any, Dict, List, Mappingfrom unittest import mockimport orjson-from django.http import HttpResponsefrom zerver.actions.reactions import notify_reaction_updatefrom zerver.actions.streams import do_change_stream_permission@@ -14,6 +13,9 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import zulip_reaction_infofrom zerver.models import Message, Reaction, RealmEmoji, UserMessage, get_realm+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class ReactionEmojiTest(ZulipTestCase):def test_missing_emoji(self) -> None:@@ -619,7 +621,7 @@ class EmojiReactionBase(ZulipTestCase):def __init__(self, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)- def post_reaction(self, reaction_info: Dict[str, str]) -> HttpResponse:+ def post_reaction(self, reaction_info: Dict[str, str]) -> "TestHttpResponse":message_id = 1result = self.api_post(@@ -627,7 +629,7 @@ class EmojiReactionBase(ZulipTestCase):)return result- def post_other_reaction(self, reaction_info: Dict[str, str]) -> HttpResponse:+ def post_other_reaction(self, reaction_info: Dict[str, str]) -> "TestHttpResponse":message_id = 1result = self.api_post(@@ -635,7 +637,7 @@ class EmojiReactionBase(ZulipTestCase):)return result- def delete_reaction(self, reaction_info: Dict[str, str]) -> HttpResponse:+ def delete_reaction(self, reaction_info: Dict[str, str]) -> "TestHttpResponse":message_id = 1result = self.api_delete(diff --git a/zerver/tests/test_scim.py b/zerver/tests/test_scim.pyindex cf6de15aed3..bd5e2451e8a 100644--- a/zerver/tests/test_scim.py+++ b/zerver/tests/test_scim.py@@ -1,16 +1,18 @@import copyfrom contextlib import contextmanager-from typing import Any, Dict, Iterator, Mapping+from typing import TYPE_CHECKING, Any, Dict, Iterator, Mappingfrom unittest import mockimport orjsonfrom django.conf import settings-from django.http import HttpResponsefrom zerver.actions.user_settings import do_change_full_namefrom zerver.lib.test_classes import ZulipTestCasefrom zerver.models import SCIMClient, UserProfile, get_realm+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class SCIMTestCase(ZulipTestCase):def setUp(self) -> None:@@ -39,7 +41,7 @@ class SCIMTestCase(ZulipTestCase):},}- def assert_uniqueness_error(self, result: HttpResponse, extra_message: str) -> None:+ def assert_uniqueness_error(self, result: "TestHttpResponse", extra_message: str) -> None:self.assertEqual(result.status_code, 409)output_data = orjson.loads(result.content)diff --git a/zerver/tests/test_settings.py b/zerver/tests/test_settings.pyindex ce58d69e0f1..e26f122f71a 100644--- a/zerver/tests/test_settings.py+++ b/zerver/tests/test_settings.py@@ -1,10 +1,10 @@import timefrom datetime import datetime, timezone-from typing import Any, Dict+from typing import TYPE_CHECKING, Any, Dictfrom unittest import mockimport orjson-from django.http import HttpRequest, HttpResponse+from django.http import HttpRequestfrom django.test import override_settingsfrom zerver.lib.initial_password import initial_password@@ -20,6 +20,9 @@ from zerver.models import (get_user_profile_by_api_key,)+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class ChangeSettingsTest(ZulipTestCase):# TODO: requires method consolidation, right now, there's no alternative@@ -411,7 +414,7 @@ class ChangeSettingsTest(ZulipTestCase):hamlet = self.example_user("hamlet")self.assertNotEqual(getattr(hamlet, setting_name), invalid_value)- def do_change_emojiset(self, emojiset: str) -> HttpResponse:+ def do_change_emojiset(self, emojiset: str) -> "TestHttpResponse":self.login("hamlet")data = {"emojiset": emojiset}result = self.client_patch("/json/settings", data)diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 8737082020b..7f01d95bdb5 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -2,7 +2,7 @@ import datetimeimport reimport timeimport urllib-from typing import Any, Dict, List, Optional, Sequence, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Unionfrom unittest.mock import MagicMock, patchfrom urllib.parse import urlencode@@ -112,6 +112,9 @@ from zerver.views.invite import get_invitee_emails_setfrom zerver.views.registration import accounts_homefrom zproject.backends import ExternalAuthDataDict, ExternalAuthResult+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class RedirectAndLogIntoSubdomainTestCase(ZulipTestCase):def test_data(self) -> None:@@ -1077,7 +1080,7 @@ class InviteUserBase(ZulipTestCase):invite_expires_in_minutes: Optional[int] = settings.INVITATION_LINK_VALIDITY_MINUTES,body: str = "",invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],- ) -> HttpResponse:+ ) -> "TestHttpResponse":"""Invites the specified users to Zulip with the specified streams.@@ -1162,7 +1165,7 @@ class InviteUserTest(InviteUserBase):realm.date_created = timezone_now()realm.save()- def try_invite() -> HttpResponse:+ def try_invite() -> "TestHttpResponse":with self.settings(OPEN_REALM_CREATION=True,INVITES_DEFAULT_REALM_DAILY_MAX=site_max,@@ -3860,7 +3863,7 @@ class RealmCreationTest(ZulipTestCase):class UserSignUpTest(InviteUserBase):- def _assert_redirected_to(self, result: HttpResponse, url: str) -> None:+ def _assert_redirected_to(self, result: "TestHttpResponse", url: str) -> None:self.assertEqual(result.status_code, 302)self.assertEqual(result["LOCATION"], url)@@ -3872,7 +3875,7 @@ class UserSignUpTest(InviteUserBase):full_name: str = "New user's name",realm: Optional[Realm] = None,subdomain: Optional[str] = None,- ) -> Union[UserProfile, HttpResponse]:+ ) -> Union[UserProfile, "TestHttpResponse"]:"""Common test function for signup tests. It is a goal to use thiscommon function for all signup tests to avoid code duplication; doingso will likely require adding new parameters."""@@ -4081,6 +4084,8 @@ class UserSignUpTest(InviteUserBase):"""result = self.verify_signup(full_name="<invalid>")+ # _WSGIPatchedWSGIResponse does not exist in Django, thus the inverted isinstance check.+ assert not isinstance(result, UserProfile)self.assert_in_success_response(["Invalid characters in name!"], result)# Verify that the user is asked for name and password@@ -4107,6 +4112,8 @@ class UserSignUpTest(InviteUserBase):email = "[email protected]"password = "newpassword"result = self.verify_signup(email=email, password=password, full_name="")+ # _WSGIPatchedWSGIResponse does not exist in Django, thus the inverted isinstance check.+ assert not isinstance(result, UserProfile)self.assert_in_success_response(["We just need you to do one last thing."], result)# Verify that the user is asked for name and passworddiff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex c28c3746a43..247c832eccd 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -2,7 +2,7 @@ import hashlibimport randomfrom datetime import timedeltafrom io import StringIO-from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Union+from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Set, Unionfrom unittest import mockimport orjson@@ -105,6 +105,9 @@ from zerver.models import ()from zerver.views.streams import compose_views+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class TestMiscStuff(ZulipTestCase):def test_test_helper(self) -> None:@@ -2378,7 +2381,7 @@ class StreamAdminTest(ZulipTestCase):target_users_subbed: bool = True,using_legacy_emails: bool = False,other_sub_users: Sequence[UserProfile] = [],- ) -> HttpResponse:+ ) -> "TestHttpResponse":# Set up the main user, who is in most cases an admin.if is_realm_admin:@@ -5676,7 +5679,7 @@ class GetSubscribersTest(ZulipTestCase):def make_subscriber_request(self, stream_id: int, user: Optional[UserProfile] = None- ) -> HttpResponse:+ ) -> "TestHttpResponse":if user is None:user = self.user_profilereturn self.api_get(user, f"/api/v1/streams/{stream_id}/members")diff --git a/zerver/tests/test_widgets.py b/zerver/tests/test_widgets.pyindex ab641f62d3c..9121e71cebb 100644--- a/zerver/tests/test_widgets.py+++ b/zerver/tests/test_widgets.py@@ -1,15 +1,17 @@import re-from typing import Any, Dict+from typing import TYPE_CHECKING, Any, Dictimport orjsonfrom django.core.exceptions import ValidationError-from django.http import HttpResponsefrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.validator import check_widget_contentfrom zerver.lib.widget import get_widget_data, get_widget_typefrom zerver.models import SubMessage, UserProfile+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class WidgetContentTestCase(ZulipTestCase):def test_validation(self) -> None:@@ -238,7 +240,7 @@ class WidgetContentTestCase(ZulipTestCase):message = self.get_last_message()- def post(sender: UserProfile, data: Dict[str, object]) -> HttpResponse:+ def post(sender: UserProfile, data: Dict[str, object]) -> "TestHttpResponse":payload = dict(message_id=message.id, msg_type="widget", content=orjson.dumps(data).decode())@@ -266,7 +268,7 @@ class WidgetContentTestCase(ZulipTestCase):message = self.get_last_message()- def post_submessage(content: str) -> HttpResponse:+ def post_submessage(content: str) -> "TestHttpResponse":payload = dict(message_id=message.id,msg_type="widget",@@ -324,7 +326,7 @@ class WidgetContentTestCase(ZulipTestCase):message = self.get_last_message()- def post_submessage(content: str) -> HttpResponse:+ def post_submessage(content: str) -> "TestHttpResponse":payload = dict(message_id=message.id,msg_type="widget",diff --git a/zerver/tests/test_zephyr.py b/zerver/tests/test_zephyr.pyindex 762ea2583dc..c2655b01939 100644--- a/zerver/tests/test_zephyr.py+++ b/zerver/tests/test_zephyr.py@@ -1,21 +1,23 @@import subprocess-from typing import Any+from typing import TYPE_CHECKING, Anyfrom unittest.mock import patchimport orjson-from django.http import HttpResponsefrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.users import get_api_keyfrom zerver.models import get_realm, get_user+if TYPE_CHECKING:+ from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse+class ZephyrTest(ZulipTestCase):def test_webathena_kerberos_login(self) -> None:user = self.example_user("hamlet")self.login_user(user)- def post(subdomain: Any, **kwargs: Any) -> HttpResponse:+ def post(subdomain: Any, **kwargs: Any) -> "TestHttpResponse":params = {k: orjson.dumps(v).decode() for k, v in kwargs.items()}return self.client_post("/accounts/webathena_kerberos_login/", params, subdomain=subdomain