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.

test_classes: Refine assert_json_success output with exception chaining.

Anders Kaseorg7143e6910d8c
diff --git a/zerver/lib/response.py b/zerver/lib/response.py
index 8fb54dee309..705eb1baa36 100644
--- a/zerver/lib/response.py
+++ b/zerver/lib/response.py
@@ -15,6 +15,7 @@ class MutableJsonResponse(HttpResponse):
*,
content_type: str,
status: int,
+ exception: Exception | None = None,
) -> None:
# Mirror the behavior of Django's TemplateResponse and pass an
# empty string for the initial content value. Because that will
@@ -23,6 +24,7 @@ class MutableJsonResponse(HttpResponse):
super().__init__("", content_type=content_type, status=status)
self._data = data
self._needs_serialization = True
+ self.exception = exception
def get_data(self) -> dict[str, Any]:
"""Get data for this MutableJsonResponse. Calling this method
@@ -93,7 +95,11 @@ def json_method_not_allowed(methods: list[str]) -> HttpResponseNotAllowed:
def json_response(
- res_type: str = "success", msg: str = "", data: Mapping[str, Any] = {}, status: int = 200
+ res_type: str = "success",
+ msg: str = "",
+ data: Mapping[str, Any] = {},
+ status: int = 200,
+ exception: Exception | None = None,
) -> MutableJsonResponse:
content = {"result": res_type, "msg": msg}
content.update(data)
@@ -102,6 +108,7 @@ def json_response(
data=content,
content_type="application/json",
status=status,
+ exception=exception,
)
@@ -121,7 +128,11 @@ def json_response_from_error(exception: JsonableError) -> MutableJsonResponse:
if 200 <= exception.http_status_code < 300:
response_type = "success"
response = json_response(
- response_type, msg=exception.msg, data=exception.data, status=exception.http_status_code
+ response_type,
+ msg=exception.msg,
+ data=exception.data,
+ status=exception.http_status_code,
+ exception=exception,
)
for header, value in exception.extra_headers.items():
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index d6f5ade5898..9a76bfabaf8 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -55,6 +55,7 @@ from zerver.lib.message import access_message
from zerver.lib.notification_data import UserMessageNotificationsData
from zerver.lib.per_request_cache import flush_per_request_caches
from zerver.lib.redis_utils import bounce_redis_key_prefix_for_testing
+from zerver.lib.response import MutableJsonResponse
from zerver.lib.sessions import get_session_dict_user
from zerver.lib.soft_deactivation import do_soft_deactivate_users
from zerver.lib.stream_subscription import get_subscribed_stream_ids_for_user
@@ -1230,23 +1231,32 @@ Output:
json = orjson.loads(result.content)
except orjson.JSONDecodeError: # nocoverage
json = {"msg": "Error parsing JSON in response!"}
- self.assertEqual(result.status_code, 200, json["msg"])
- self.assertEqual(json.get("result"), "success")
- # We have a msg key for consistency with errors, but it typically has an
- # empty value.
- self.assertIn("msg", json)
- self.assertNotEqual(json["msg"], "Error parsing JSON in response!")
- # Check ignored parameters.
- if ignored_parameters is None:
- self.assertNotIn("ignored_parameters_unsupported", json)
- else:
- self.assertIn("ignored_parameters_unsupported", json)
- self.assert_length(json["ignored_parameters_unsupported"], len(ignored_parameters))
- for param in ignored_parameters:
- self.assertTrue(param in json["ignored_parameters_unsupported"])
+
+ try:
+ self.assertEqual(result.status_code, 200, json["msg"])
+ self.assertEqual(json.get("result"), "success")
+ # We have a msg key for consistency with errors, but it typically has an
+ # empty value.
+ self.assertIn("msg", json)
+ self.assertNotEqual(json["msg"], "Error parsing JSON in response!")
+ # Check ignored parameters.
+ if ignored_parameters is None:
+ self.assertNotIn("ignored_parameters_unsupported", json)
+ else:
+ self.assertIn("ignored_parameters_unsupported", json)
+ self.assert_length(json["ignored_parameters_unsupported"], len(ignored_parameters))
+ for param in ignored_parameters:
+ self.assertTrue(param in json["ignored_parameters_unsupported"])
+ except AssertionError as e: # nocoverage
+ if isinstance(result, MutableJsonResponse):
+ raise e from result.exception
+ raise
+
return json
- def get_json_error(self, result: "TestHttpResponse", status_code: int = 400) -> str:
+ def get_json_error(
+ self, result: Union["TestHttpResponse", HttpResponse], status_code: int = 400
+ ) -> str:
try:
json = orjson.loads(result.content)
except orjson.JSONDecodeError: # nocoverage
@@ -1256,13 +1266,18 @@ Output:
return json["msg"]
def assert_json_error(
- self, result: "TestHttpResponse", msg: str, status_code: int = 400
+ self, result: Union["TestHttpResponse", HttpResponse], msg: str, status_code: int = 400
) -> None:
"""
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
"""
- self.assertEqual(self.get_json_error(result, status_code=status_code), msg)
+ try:
+ self.assertEqual(self.get_json_error(result, status_code=status_code), msg)
+ except AssertionError as e: # nocoverage
+ if isinstance(result, MutableJsonResponse):
+ raise e from result.exception
+ raise
def assert_length(self, items: Collection[Any] | QuerySet[Any, Any], count: int) -> None:
actual_count = len(items)
@@ -1308,9 +1323,17 @@ Output:
)
def assert_json_error_contains(
- self, result: "TestHttpResponse", msg_substring: str, status_code: int = 400
+ self,
+ result: Union["TestHttpResponse", HttpResponse],
+ msg_substring: str,
+ status_code: int = 400,
) -> None:
- self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))
+ try:
+ self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))
+ except AssertionError as e: # nocoverage
+ if isinstance(result, MutableJsonResponse):
+ raise e from result.exception
+ raise
def assert_in_response(
self, substring: str, response: Union["TestHttpResponse", HttpResponse]
diff --git a/zerver/middleware.py b/zerver/middleware.py
index ab94d128017..b1bd413a066 100644
--- a/zerver/middleware.py
+++ b/zerver/middleware.py
@@ -392,7 +392,9 @@ class JsonErrorHandler(MiddlewareMixin):
# just return the response without logging further.
return response
elif RequestNotes.get_notes(request).error_format == "JSON" and not settings.TEST_SUITE:
- response = json_response(res_type="error", msg=_("Internal server error"), status=500)
+ response = json_response(
+ res_type="error", msg=_("Internal server error"), status=500, exception=exception
+ )
else:
return None