realm_emoji: Stop swallowing all exceptions from upload_emoji_image.

Putting all of the logic in a `finally` block is equivalent to a bare
`except` block, which silently consumes all exceptions.

Move only the most-necessary parts into the except; this lets
`BadImageError` exceptions from `zerver/lib/upload.py` to escape,
allowing better the generic "Image file upload failed" to be replaced
with a more specific message.

It also allows unexpected exceptions, as the previous commit resolved,
to escape and 500.  This lets them be detected and resolved, rather
than give users a silently bad experience.
This commit is contained in:
Alex Vandiver
2022-02-16 23:01:27 +00:00
committed by Tim Abbott
parent 96a5fa9d78
commit a40b3e1118
4 changed files with 19 additions and 20 deletions

View File

@@ -10,6 +10,7 @@ from zerver.lib.actions import (
from zerver.lib.exceptions import JsonableError
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import get_test_image_file
from zerver.lib.upload import BadImageError
from zerver.models import Realm, RealmEmoji, UserProfile, get_realm
@@ -320,11 +321,13 @@ class RealmEmojiTest(ZulipTestCase):
def test_failed_file_upload(self) -> None:
self.login("iago")
with mock.patch("zerver.lib.upload.write_local_file", side_effect=Exception()):
with mock.patch(
"zerver.lib.upload.write_local_file", side_effect=BadImageError(msg="Broken")
):
with get_test_image_file("img.png") as fp1:
emoji_data = {"f1": fp1}
result = self.client_post("/json/realm/emoji/my_emoji", info=emoji_data)
self.assert_json_error(result, "Image file upload failed.")
self.assert_json_error(result, "Broken")
def test_check_admin_realm_emoji(self) -> None:
# Test that an user A is able to remove a realm emoji uploaded by him