Skip to content

Commit 42a9d5d

Browse files
authored
Add webhook tests for Telegram bot (home-assistant#153998)
1 parent 93fa162 commit 42a9d5d

File tree

2 files changed

+62
-64
lines changed

2 files changed

+62
-64
lines changed

tests/components/telegram_bot/conftest.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from unittest.mock import AsyncMock, patch
77

88
import pytest
9-
from telegram import Bot, Chat, ChatFullInfo, Message, User
9+
from telegram import Bot, Chat, ChatFullInfo, Message, User, WebhookInfo
1010
from telegram.constants import AccentColor, ChatType
1111

1212
from homeassistant.components.telegram_bot import (
@@ -74,11 +74,22 @@ def mock_register_webhook() -> Generator[None]:
7474
"""Mock calls made by telegram_bot when (de)registering webhook."""
7575
with (
7676
patch(
77-
"homeassistant.components.telegram_bot.webhooks.PushBot.register_webhook",
78-
return_value=True,
77+
"homeassistant.components.telegram_bot.webhooks.Bot.delete_webhook",
78+
AsyncMock(),
79+
),
80+
patch(
81+
"homeassistant.components.telegram_bot.webhooks.Bot.get_webhook_info",
82+
AsyncMock(
83+
return_value=WebhookInfo(
84+
url="mock url",
85+
last_error_date=datetime.now(),
86+
has_custom_certificate=False,
87+
pending_update_count=0,
88+
)
89+
),
7990
),
8091
patch(
81-
"homeassistant.components.telegram_bot.webhooks.PushBot.deregister_webhook",
92+
"homeassistant.components.telegram_bot.webhooks.Bot.set_webhook",
8293
return_value=True,
8394
),
8495
):
@@ -113,9 +124,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
113124
super().__init__(*args, **kwargs)
114125
self._bot_user = test_user
115126

116-
async def delete_webhook(self) -> bool:
117-
return True
118-
119127
with (
120128
patch("homeassistant.components.telegram_bot.bot.Bot", BotMock),
121129
patch.object(BotMock, "get_chat", return_value=test_chat),
Lines changed: 47 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
"""Tests for webhooks."""
22

3-
from datetime import datetime
43
from ipaddress import IPv4Network
5-
from unittest.mock import AsyncMock, patch
4+
from unittest.mock import patch
65

7-
from telegram import WebhookInfo
86
from telegram.error import TimedOut
97

8+
from homeassistant.components.telegram_bot.const import DOMAIN
109
from homeassistant.components.telegram_bot.webhooks import TELEGRAM_WEBHOOK_URL
1110
from homeassistant.config_entries import ConfigEntryState
1211
from homeassistant.core import HomeAssistant
@@ -19,91 +18,61 @@ async def test_set_webhooks_failed(
1918
hass: HomeAssistant,
2019
mock_webhooks_config_entry: MockConfigEntry,
2120
mock_external_calls: None,
22-
mock_generate_secret_token,
21+
mock_register_webhook: None,
2322
) -> None:
2423
"""Test set webhooks failed."""
2524
mock_webhooks_config_entry.add_to_hass(hass)
2625

2726
with (
2827
patch(
29-
"homeassistant.components.telegram_bot.webhooks.Bot.get_webhook_info",
30-
AsyncMock(
31-
return_value=WebhookInfo(
32-
url="mock url",
33-
last_error_date=datetime.now(),
34-
has_custom_certificate=False,
35-
pending_update_count=0,
36-
)
37-
),
38-
) as mock_webhook_info,
28+
"homeassistant.components.telegram_bot.webhooks.secrets.choice",
29+
return_value="DEADBEEF12345678DEADBEEF87654321",
30+
),
3931
patch(
4032
"homeassistant.components.telegram_bot.webhooks.Bot.set_webhook",
4133
) as mock_set_webhook,
42-
patch(
43-
"homeassistant.components.telegram_bot.webhooks.ApplicationBuilder"
44-
) as application_builder_class,
4534
):
4635
mock_set_webhook.side_effect = [TimedOut("mock timeout"), False]
47-
application = application_builder_class.return_value.bot.return_value.updater.return_value.build.return_value
48-
application.initialize = AsyncMock()
49-
application.start = AsyncMock()
5036

5137
await hass.config_entries.async_setup(mock_webhooks_config_entry.entry_id)
5238
await hass.async_block_till_done()
5339
await hass.async_stop()
5440

55-
mock_webhook_info.assert_called_once()
56-
application.initialize.assert_called_once()
57-
application.start.assert_called_once()
58-
assert mock_set_webhook.call_count > 0
41+
# first fail with exception, second fail with False
42+
assert mock_set_webhook.call_count == 2
5943

6044
# SETUP_ERROR is result of ConfigEntryNotReady("Failed to register webhook with Telegram") in webhooks.py
6145
assert mock_webhooks_config_entry.state == ConfigEntryState.SETUP_ERROR
6246

47+
# test fail after retries
48+
49+
mock_set_webhook.reset_mock()
50+
mock_set_webhook.side_effect = TimedOut("mock timeout")
51+
52+
await hass.config_entries.async_reload(mock_webhooks_config_entry.entry_id)
53+
await hass.async_block_till_done()
54+
55+
# 3 retries
56+
assert mock_set_webhook.call_count == 3
57+
58+
assert mock_webhooks_config_entry.state == ConfigEntryState.SETUP_ERROR
59+
await hass.async_block_till_done()
60+
6361

6462
async def test_set_webhooks(
6563
hass: HomeAssistant,
6664
mock_webhooks_config_entry: MockConfigEntry,
6765
mock_external_calls: None,
66+
mock_register_webhook: None,
6867
mock_generate_secret_token,
6968
) -> None:
7069
"""Test set webhooks success."""
7170
mock_webhooks_config_entry.add_to_hass(hass)
71+
await hass.config_entries.async_setup(mock_webhooks_config_entry.entry_id)
7272

73-
with (
74-
patch(
75-
"homeassistant.components.telegram_bot.webhooks.Bot.get_webhook_info",
76-
AsyncMock(
77-
return_value=WebhookInfo(
78-
url="mock url",
79-
last_error_date=datetime.now(),
80-
has_custom_certificate=False,
81-
pending_update_count=0,
82-
)
83-
),
84-
) as mock_webhook_info,
85-
patch(
86-
"homeassistant.components.telegram_bot.webhooks.Bot.set_webhook",
87-
AsyncMock(return_value=True),
88-
) as mock_set_webhook,
89-
patch(
90-
"homeassistant.components.telegram_bot.webhooks.ApplicationBuilder"
91-
) as application_builder_class,
92-
):
93-
application = application_builder_class.return_value.bot.return_value.updater.return_value.build.return_value
94-
application.initialize = AsyncMock()
95-
application.start = AsyncMock()
96-
97-
await hass.config_entries.async_setup(mock_webhooks_config_entry.entry_id)
98-
await hass.async_block_till_done()
99-
await hass.async_stop()
100-
101-
mock_webhook_info.assert_called_once()
102-
application.initialize.assert_called_once()
103-
application.start.assert_called_once()
104-
mock_set_webhook.assert_called_once()
73+
await hass.async_block_till_done()
10574

106-
assert mock_webhooks_config_entry.state == ConfigEntryState.LOADED
75+
assert mock_webhooks_config_entry.state == ConfigEntryState.LOADED
10776

10877

10978
async def test_webhooks_update_invalid_json(
@@ -148,3 +117,24 @@ async def test_webhooks_unauthorized_network(
148117

149118
await hass.async_block_till_done()
150119
mock_remote.assert_called_once()
120+
121+
122+
async def test_webhooks_deregister_failed(
123+
hass: HomeAssistant,
124+
webhook_platform,
125+
mock_external_calls: None,
126+
mock_generate_secret_token,
127+
) -> None:
128+
"""Test deregister webhooks."""
129+
130+
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
131+
assert config_entry.state == ConfigEntryState.LOADED
132+
133+
with patch(
134+
"homeassistant.components.telegram_bot.webhooks.Bot.delete_webhook",
135+
) as mock_delete_webhook:
136+
mock_delete_webhook.side_effect = TimedOut("mock timeout")
137+
await hass.config_entries.async_unload(config_entry.entry_id)
138+
139+
mock_delete_webhook.assert_called_once()
140+
assert config_entry.state == ConfigEntryState.NOT_LOADED

0 commit comments

Comments
 (0)