From 67b07061163815ca82f359bed052fb422f609ca8 Mon Sep 17 00:00:00 2001 From: Poolitzer Date: Sat, 9 Dec 2023 17:35:23 +0100 Subject: [PATCH] Improve Error Handling in Built-In Webhook Handler (#3987) --- telegram/ext/_utils/webhookhandler.py | 3 +++ tests/ext/test_updater.py | 16 +++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/telegram/ext/_utils/webhookhandler.py b/telegram/ext/_utils/webhookhandler.py index 05ad223df..65f37ce7b 100644 --- a/telegram/ext/_utils/webhookhandler.py +++ b/telegram/ext/_utils/webhookhandler.py @@ -146,6 +146,9 @@ class TelegramHandler(tornado.web.RequestHandler): "Received data was *not* processed!", exc_info=exc, ) + raise tornado.web.HTTPError( + HTTPStatus.BAD_REQUEST, reason="Update could not be processed" + ) from exc if update: _LOGGER.debug( diff --git a/tests/ext/test_updater.py b/tests/ext/test_updater.py index f346b48bb..58c8804f9 100644 --- a/tests/ext/test_updater.py +++ b/tests/ext/test_updater.py @@ -63,6 +63,7 @@ class TestUpdater: cb_handler_called = None offset = 0 test_flag = False + response_text = "{1}: {0}{1}: {0}" @pytest.fixture(autouse=True) def _reset(self): @@ -732,11 +733,10 @@ class TestUpdater: if secret_token: # Returns Forbidden if no secret token is set - response_text = "403: {0}403: {0}" response = await send_webhook_message(ip, port, update.to_json(), "TOKEN") assert response.status_code == HTTPStatus.FORBIDDEN - assert response.text == response_text.format( - "Request did not include the secret token" + assert response.text == self.response_text.format( + "Request did not include the secret token", HTTPStatus.FORBIDDEN ) # Returns Forbidden if the secret token is wrong @@ -744,7 +744,9 @@ class TestUpdater: ip, port, update.to_json(), "TOKEN", secret_token="NotTheSecretToken" ) assert response.status_code == HTTPStatus.FORBIDDEN - assert response.text == response_text.format("Request had the wrong secret token") + assert response.text == self.response_text.format( + "Request had the wrong secret token", HTTPStatus.FORBIDDEN + ) await updater.stop() assert not updater.running @@ -1071,11 +1073,15 @@ class TestUpdater: # Now, we send an update to the server update = make_message_update("Webhook") with caplog.at_level(logging.CRITICAL): - await send_webhook_message(ip, port, update.to_json(), "TOKEN") + response = await send_webhook_message(ip, port, update.to_json(), "TOKEN") assert len(caplog.records) == 1 assert caplog.records[-1].getMessage().startswith("Something went wrong processing") assert caplog.records[-1].name == "telegram.ext.Updater" + assert response.status_code == 400 + assert response.text == self.response_text.format( + "Update could not be processed", HTTPStatus.BAD_REQUEST + ) # Make sure that everything works fine again when receiving proper updates caplog.clear()