Skip to content

Commit

Permalink
Improve Error Handling in Built-In Webhook Handler (#3987)
Browse files Browse the repository at this point in the history
  • Loading branch information
Poolitzer committed Dec 9, 2023
1 parent 592c6cc commit 67b0706
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
3 changes: 3 additions & 0 deletions telegram/ext/_utils/webhookhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ async def post(self) -> None:
"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(
Expand Down
16 changes: 11 additions & 5 deletions tests/ext/test_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ class TestUpdater:
cb_handler_called = None
offset = 0
test_flag = False
response_text = "<html><title>{1}: {0}</title><body>{1}: {0}</body></html>"

@pytest.fixture(autouse=True)
def _reset(self):
Expand Down Expand Up @@ -732,19 +733,20 @@ async def set_webhook(*args, **kwargs):

if secret_token:
# Returns Forbidden if no secret token is set
response_text = "<html><title>403: {0}</title><body>403: {0}</body></html>"
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
response = await send_webhook_message(
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
Expand Down Expand Up @@ -1071,11 +1073,15 @@ def de_json_fails(*args, **kwargs):
# 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()
Expand Down

0 comments on commit 67b0706

Please sign in to comment.