init home-assistant
This commit is contained in:
1
home-assistant/tests/components/telegram_bot/__init__.py
Normal file
1
home-assistant/tests/components/telegram_bot/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Tests for telegram_bot integration."""
|
||||
251
home-assistant/tests/components/telegram_bot/conftest.py
Normal file
251
home-assistant/tests/components/telegram_bot/conftest.py
Normal file
@@ -0,0 +1,251 @@
|
||||
"""Tests for the telegram_bot integration."""
|
||||
|
||||
from collections.abc import AsyncGenerator, Generator
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from telegram import Bot, Chat, Message, User
|
||||
from telegram.constants import ChatType
|
||||
|
||||
from homeassistant.components.telegram_bot import (
|
||||
CONF_ALLOWED_CHAT_IDS,
|
||||
CONF_TRUSTED_NETWORKS,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
CONF_API_KEY,
|
||||
CONF_PLATFORM,
|
||||
CONF_URL,
|
||||
EVENT_HOMEASSISTANT_START,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_webhooks() -> dict[str, Any]:
|
||||
"""Fixture for a webhooks platform configuration."""
|
||||
return {
|
||||
DOMAIN: [
|
||||
{
|
||||
CONF_PLATFORM: "webhooks",
|
||||
CONF_URL: "https://test",
|
||||
CONF_TRUSTED_NETWORKS: ["127.0.0.1"],
|
||||
CONF_API_KEY: "1234567890:ABC",
|
||||
CONF_ALLOWED_CHAT_IDS: [
|
||||
# "me"
|
||||
12345678,
|
||||
# Some chat
|
||||
-123456789,
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_polling() -> dict[str, Any]:
|
||||
"""Fixture for a polling platform configuration."""
|
||||
return {
|
||||
DOMAIN: [
|
||||
{
|
||||
CONF_PLATFORM: "polling",
|
||||
CONF_API_KEY: "1234567890:ABC",
|
||||
CONF_ALLOWED_CHAT_IDS: [
|
||||
# "me"
|
||||
12345678,
|
||||
# Some chat
|
||||
-123456789,
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_register_webhook() -> Generator[None]:
|
||||
"""Mock calls made by telegram_bot when (de)registering webhook."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.telegram_bot.webhooks.PushBot.register_webhook",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.telegram_bot.webhooks.PushBot.deregister_webhook",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_external_calls() -> Generator[None]:
|
||||
"""Mock calls that make calls to the live Telegram API."""
|
||||
test_user = User(123456, "Testbot", True)
|
||||
message = Message(
|
||||
message_id=12345,
|
||||
date=datetime.now(),
|
||||
chat=Chat(id=123456, type=ChatType.PRIVATE),
|
||||
)
|
||||
|
||||
class BotMock(Bot):
|
||||
"""Mock bot class."""
|
||||
|
||||
__slots__ = ()
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
"""Initialize BotMock instance."""
|
||||
super().__init__(*args, **kwargs)
|
||||
self._bot_user = test_user
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.telegram_bot.Bot", BotMock),
|
||||
patch.object(BotMock, "get_me", return_value=test_user),
|
||||
patch.object(BotMock, "bot", test_user),
|
||||
patch.object(BotMock, "send_message", return_value=message),
|
||||
patch("telegram.ext.Updater._bootstrap"),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_generate_secret_token() -> Generator[str]:
|
||||
"""Mock secret token generated for webhook."""
|
||||
mock_secret_token = "DEADBEEF12345678DEADBEEF87654321"
|
||||
with patch(
|
||||
"homeassistant.components.telegram_bot.webhooks.secrets.choice",
|
||||
side_effect=mock_secret_token,
|
||||
):
|
||||
yield mock_secret_token
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def incorrect_secret_token():
|
||||
"""Mock incorrect secret token."""
|
||||
return "AAAABBBBCCCCDDDDEEEEFFFF00009999"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def update_message_command():
|
||||
"""Fixture for mocking an incoming update of type message/command."""
|
||||
return {
|
||||
"update_id": 1,
|
||||
"message": {
|
||||
"message_id": 1,
|
||||
"from": {
|
||||
"id": 12345678,
|
||||
"is_bot": False,
|
||||
"first_name": "Firstname",
|
||||
"username": "some_username",
|
||||
"language_code": "en",
|
||||
},
|
||||
"chat": {
|
||||
"id": -123456789,
|
||||
"title": "SomeChat",
|
||||
"type": "group",
|
||||
"all_members_are_administrators": True,
|
||||
},
|
||||
"date": 1644518189,
|
||||
"text": "/command",
|
||||
"entities": [
|
||||
{
|
||||
"type": "bot_command",
|
||||
"offset": 0,
|
||||
"length": 7,
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def update_message_text():
|
||||
"""Fixture for mocking an incoming update of type message/text."""
|
||||
return {
|
||||
"update_id": 1,
|
||||
"message": {
|
||||
"message_id": 1,
|
||||
"date": 1441645532,
|
||||
"from": {
|
||||
"id": 12345678,
|
||||
"is_bot": False,
|
||||
"last_name": "Test Lastname",
|
||||
"first_name": "Test Firstname",
|
||||
"username": "Testusername",
|
||||
},
|
||||
"chat": {
|
||||
"last_name": "Test Lastname",
|
||||
"id": 1111111,
|
||||
"type": "private",
|
||||
"first_name": "Test Firstname",
|
||||
"username": "Testusername",
|
||||
},
|
||||
"text": "HELLO",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unauthorized_update_message_text(update_message_text):
|
||||
"""Fixture for mocking an incoming update of type message/text that is not in our `allowed_chat_ids`."""
|
||||
update_message_text["message"]["from"]["id"] = 1234
|
||||
update_message_text["message"]["chat"]["id"] = 1234
|
||||
return update_message_text
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def update_callback_query():
|
||||
"""Fixture for mocking an incoming update of type callback_query."""
|
||||
return {
|
||||
"update_id": 1,
|
||||
"callback_query": {
|
||||
"id": "4382bfdwdsb323b2d9",
|
||||
"from": {
|
||||
"id": 12345678,
|
||||
"type": "private",
|
||||
"is_bot": False,
|
||||
"last_name": "Test Lastname",
|
||||
"first_name": "Test Firstname",
|
||||
"username": "Testusername",
|
||||
},
|
||||
"chat_instance": "aaa111",
|
||||
"data": "Data from button callback",
|
||||
"inline_message_id": "1234csdbsk4839",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def webhook_platform(
|
||||
hass: HomeAssistant,
|
||||
config_webhooks: dict[str, Any],
|
||||
mock_register_webhook: None,
|
||||
mock_external_calls: None,
|
||||
mock_generate_secret_token: str,
|
||||
) -> AsyncGenerator[None]:
|
||||
"""Fixture for setting up the webhooks platform using appropriate config and mocks."""
|
||||
await async_setup_component(
|
||||
hass,
|
||||
DOMAIN,
|
||||
config_webhooks,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
yield
|
||||
await hass.async_stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def polling_platform(
|
||||
hass: HomeAssistant, config_polling: dict[str, Any], mock_external_calls: None
|
||||
) -> None:
|
||||
"""Fixture for setting up the polling platform using appropriate config and mocks."""
|
||||
await async_setup_component(
|
||||
hass,
|
||||
DOMAIN,
|
||||
config_polling,
|
||||
)
|
||||
# Fire this event to start polling
|
||||
hass.bus.fire(EVENT_HOMEASSISTANT_START)
|
||||
await hass.async_block_till_done()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Test Telegram broadcast."""
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
|
||||
async def test_setup(hass: HomeAssistant) -> None:
|
||||
"""Test setting up Telegram broadcast."""
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"telegram_bot",
|
||||
{
|
||||
"telegram_bot": {
|
||||
"platform": "broadcast",
|
||||
"api_key": "1234567890:ABC",
|
||||
"allowed_chat_ids": [1],
|
||||
}
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.services.has_service("telegram_bot", "send_message") is True
|
||||
@@ -0,0 +1,350 @@
|
||||
"""Tests for the telegram_bot component."""
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from telegram import Update
|
||||
from telegram.error import NetworkError, RetryAfter, TelegramError, TimedOut
|
||||
|
||||
from homeassistant.components.telegram_bot import (
|
||||
ATTR_MESSAGE,
|
||||
ATTR_MESSAGE_THREAD_ID,
|
||||
DOMAIN,
|
||||
SERVICE_SEND_MESSAGE,
|
||||
)
|
||||
from homeassistant.components.telegram_bot.webhooks import TELEGRAM_WEBHOOK_URL
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_START
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import async_capture_events
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def test_webhook_platform_init(hass: HomeAssistant, webhook_platform) -> None:
|
||||
"""Test initialization of the webhooks platform."""
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_SEND_MESSAGE) is True
|
||||
|
||||
|
||||
async def test_polling_platform_init(hass: HomeAssistant, polling_platform) -> None:
|
||||
"""Test initialization of the polling platform."""
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_SEND_MESSAGE) is True
|
||||
|
||||
|
||||
async def test_send_message(hass: HomeAssistant, webhook_platform) -> None:
|
||||
"""Test the send_message service."""
|
||||
context = Context()
|
||||
events = async_capture_events(hass, "telegram_sent")
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_SEND_MESSAGE,
|
||||
{ATTR_MESSAGE: "test_message", ATTR_MESSAGE_THREAD_ID: "123"},
|
||||
blocking=True,
|
||||
context=context,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].context == context
|
||||
|
||||
|
||||
async def test_send_message_thread(hass: HomeAssistant, webhook_platform) -> None:
|
||||
"""Test the send_message service for threads."""
|
||||
context = Context()
|
||||
events = async_capture_events(hass, "telegram_sent")
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_SEND_MESSAGE,
|
||||
{ATTR_MESSAGE: "test_message", ATTR_MESSAGE_THREAD_ID: "123"},
|
||||
blocking=True,
|
||||
context=context,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].context == context
|
||||
assert events[0].data[ATTR_MESSAGE_THREAD_ID] == "123"
|
||||
|
||||
|
||||
async def test_webhook_endpoint_generates_telegram_text_event(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
update_message_text,
|
||||
mock_generate_secret_token,
|
||||
) -> None:
|
||||
"""POST to the configured webhook endpoint and assert fired `telegram_text` event."""
|
||||
client = await hass_client()
|
||||
events = async_capture_events(hass, "telegram_text")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=update_message_text,
|
||||
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
|
||||
)
|
||||
assert response.status == 200
|
||||
assert (await response.read()).decode("utf-8") == ""
|
||||
|
||||
# Make sure event has fired
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].data["text"] == update_message_text["message"]["text"]
|
||||
assert isinstance(events[0].context, Context)
|
||||
|
||||
|
||||
async def test_webhook_endpoint_generates_telegram_command_event(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
update_message_command,
|
||||
mock_generate_secret_token,
|
||||
) -> None:
|
||||
"""POST to the configured webhook endpoint and assert fired `telegram_command` event."""
|
||||
client = await hass_client()
|
||||
events = async_capture_events(hass, "telegram_command")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=update_message_command,
|
||||
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
|
||||
)
|
||||
assert response.status == 200
|
||||
assert (await response.read()).decode("utf-8") == ""
|
||||
|
||||
# Make sure event has fired
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].data["command"] == update_message_command["message"]["text"]
|
||||
assert isinstance(events[0].context, Context)
|
||||
|
||||
|
||||
async def test_webhook_endpoint_generates_telegram_callback_event(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
update_callback_query,
|
||||
mock_generate_secret_token,
|
||||
) -> None:
|
||||
"""POST to the configured webhook endpoint and assert fired `telegram_callback` event."""
|
||||
client = await hass_client()
|
||||
events = async_capture_events(hass, "telegram_callback")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=update_callback_query,
|
||||
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
|
||||
)
|
||||
assert response.status == 200
|
||||
assert (await response.read()).decode("utf-8") == ""
|
||||
|
||||
# Make sure event has fired
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].data["data"] == update_callback_query["callback_query"]["data"]
|
||||
assert isinstance(events[0].context, Context)
|
||||
|
||||
|
||||
async def test_polling_platform_message_text_update(
|
||||
hass: HomeAssistant, config_polling, update_message_text
|
||||
) -> None:
|
||||
"""Provide the `BaseTelegramBotEntity.update_handler` with an `Update` and assert fired `telegram_text` event."""
|
||||
events = async_capture_events(hass, "telegram_text")
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.telegram_bot.polling.ApplicationBuilder"
|
||||
) as application_builder_class:
|
||||
await async_setup_component(
|
||||
hass,
|
||||
DOMAIN,
|
||||
config_polling,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
# Set up the integration with the polling platform inside the patch context manager.
|
||||
application = (
|
||||
application_builder_class.return_value.bot.return_value.build.return_value
|
||||
)
|
||||
# Then call the callback and assert events fired.
|
||||
handler = application.add_handler.call_args[0][0]
|
||||
handle_update_callback = handler.callback
|
||||
|
||||
# Create Update object using library API.
|
||||
application.bot.defaults.tzinfo = None
|
||||
update = Update.de_json(update_message_text, application.bot)
|
||||
|
||||
# handle_update_callback == BaseTelegramBotEntity.update_handler
|
||||
await handle_update_callback(update, None)
|
||||
|
||||
application.updater.stop = AsyncMock()
|
||||
application.stop = AsyncMock()
|
||||
application.shutdown = AsyncMock()
|
||||
|
||||
# Make sure event has fired
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].data["text"] == update_message_text["message"]["text"]
|
||||
assert isinstance(events[0].context, Context)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "log_message"),
|
||||
[
|
||||
(
|
||||
TelegramError("Telegram error"),
|
||||
'caused error: "Telegram error"',
|
||||
),
|
||||
(NetworkError("Network error"), ""),
|
||||
(RetryAfter(42), ""),
|
||||
(TimedOut("TimedOut error"), ""),
|
||||
],
|
||||
)
|
||||
async def test_polling_platform_add_error_handler(
|
||||
hass: HomeAssistant,
|
||||
config_polling: dict[str, Any],
|
||||
update_message_text: dict[str, Any],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
error: Exception,
|
||||
log_message: str,
|
||||
) -> None:
|
||||
"""Test polling add error handler."""
|
||||
with patch(
|
||||
"homeassistant.components.telegram_bot.polling.ApplicationBuilder"
|
||||
) as application_builder_class:
|
||||
await async_setup_component(
|
||||
hass,
|
||||
DOMAIN,
|
||||
config_polling,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
application = (
|
||||
application_builder_class.return_value.bot.return_value.build.return_value
|
||||
)
|
||||
application.updater.stop = AsyncMock()
|
||||
application.stop = AsyncMock()
|
||||
application.shutdown = AsyncMock()
|
||||
process_error = application.add_error_handler.call_args[0][0]
|
||||
application.bot.defaults.tzinfo = None
|
||||
update = Update.de_json(update_message_text, application.bot)
|
||||
|
||||
await process_error(update, MagicMock(error=error))
|
||||
|
||||
assert log_message in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "log_message"),
|
||||
[
|
||||
(
|
||||
TelegramError("Telegram error"),
|
||||
"TelegramError: Telegram error",
|
||||
),
|
||||
(NetworkError("Network error"), ""),
|
||||
(RetryAfter(42), ""),
|
||||
(TimedOut("TimedOut error"), ""),
|
||||
],
|
||||
)
|
||||
async def test_polling_platform_start_polling_error_callback(
|
||||
hass: HomeAssistant,
|
||||
config_polling: dict[str, Any],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
error: Exception,
|
||||
log_message: str,
|
||||
) -> None:
|
||||
"""Test polling add error handler."""
|
||||
with patch(
|
||||
"homeassistant.components.telegram_bot.polling.ApplicationBuilder"
|
||||
) as application_builder_class:
|
||||
await async_setup_component(
|
||||
hass,
|
||||
DOMAIN,
|
||||
config_polling,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
application = (
|
||||
application_builder_class.return_value.bot.return_value.build.return_value
|
||||
)
|
||||
application.initialize = AsyncMock()
|
||||
application.updater.start_polling = AsyncMock()
|
||||
application.start = AsyncMock()
|
||||
application.updater.stop = AsyncMock()
|
||||
application.stop = AsyncMock()
|
||||
application.shutdown = AsyncMock()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
|
||||
await hass.async_block_till_done()
|
||||
error_callback = application.updater.start_polling.call_args.kwargs[
|
||||
"error_callback"
|
||||
]
|
||||
|
||||
error_callback(error)
|
||||
|
||||
assert log_message in caplog.text
|
||||
|
||||
|
||||
async def test_webhook_endpoint_unauthorized_update_doesnt_generate_telegram_text_event(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
unauthorized_update_message_text,
|
||||
mock_generate_secret_token,
|
||||
) -> None:
|
||||
"""Update with unauthorized user/chat should not trigger event."""
|
||||
client = await hass_client()
|
||||
events = async_capture_events(hass, "telegram_text")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=unauthorized_update_message_text,
|
||||
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
|
||||
)
|
||||
assert response.status == 200
|
||||
assert (await response.read()).decode("utf-8") == ""
|
||||
|
||||
# Make sure any events would have fired
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(events) == 0
|
||||
|
||||
|
||||
async def test_webhook_endpoint_without_secret_token_is_denied(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
update_message_text,
|
||||
) -> None:
|
||||
"""Request without a secret token header should be denied."""
|
||||
client = await hass_client()
|
||||
async_capture_events(hass, "telegram_text")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=update_message_text,
|
||||
)
|
||||
assert response.status == 401
|
||||
|
||||
|
||||
async def test_webhook_endpoint_invalid_secret_token_is_denied(
|
||||
hass: HomeAssistant,
|
||||
webhook_platform,
|
||||
hass_client: ClientSessionGenerator,
|
||||
update_message_text,
|
||||
incorrect_secret_token,
|
||||
) -> None:
|
||||
"""Request with an invalid secret token header should be denied."""
|
||||
client = await hass_client()
|
||||
async_capture_events(hass, "telegram_text")
|
||||
|
||||
response = await client.post(
|
||||
TELEGRAM_WEBHOOK_URL,
|
||||
json=update_message_text,
|
||||
headers={"X-Telegram-Bot-Api-Secret-Token": incorrect_secret_token},
|
||||
)
|
||||
assert response.status == 401
|
||||
Reference in New Issue
Block a user