init home-assistant
This commit is contained in:
1
home-assistant/tests/components/matrix/__init__.py
Normal file
1
home-assistant/tests/components/matrix/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Tests for the Matrix component."""
|
||||
316
home-assistant/tests/components/matrix/conftest.py
Normal file
316
home-assistant/tests/components/matrix/conftest.py
Normal file
@@ -0,0 +1,316 @@
|
||||
"""Define fixtures available for all tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from nio import (
|
||||
AsyncClient,
|
||||
ErrorResponse,
|
||||
JoinError,
|
||||
JoinResponse,
|
||||
LocalProtocolError,
|
||||
LoginError,
|
||||
LoginResponse,
|
||||
Response,
|
||||
RoomResolveAliasError,
|
||||
RoomResolveAliasResponse,
|
||||
UploadResponse,
|
||||
WhoamiError,
|
||||
WhoamiResponse,
|
||||
)
|
||||
from PIL import Image
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.matrix import (
|
||||
CONF_COMMANDS,
|
||||
CONF_EXPRESSION,
|
||||
CONF_HOMESERVER,
|
||||
CONF_ROOMS,
|
||||
CONF_WORD,
|
||||
EVENT_MATRIX_COMMAND,
|
||||
MatrixBot,
|
||||
RoomAlias,
|
||||
RoomAnyID,
|
||||
RoomID,
|
||||
)
|
||||
from homeassistant.components.matrix.const import DOMAIN as MATRIX_DOMAIN
|
||||
from homeassistant.components.matrix.notify import CONF_DEFAULT_ROOM
|
||||
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
|
||||
from homeassistant.const import (
|
||||
CONF_NAME,
|
||||
CONF_PASSWORD,
|
||||
CONF_PLATFORM,
|
||||
CONF_USERNAME,
|
||||
CONF_VERIFY_SSL,
|
||||
)
|
||||
from homeassistant.core import Event, HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import async_capture_events
|
||||
|
||||
TEST_NOTIFIER_NAME = "matrix_notify"
|
||||
|
||||
TEST_HOMESERVER = "example.com"
|
||||
TEST_DEFAULT_ROOM = RoomID("!DefaultNotificationRoom:example.com")
|
||||
TEST_ROOM_A_ID = RoomID("!RoomA-ID:example.com")
|
||||
TEST_ROOM_B_ID = RoomID("!RoomB-ID:example.com")
|
||||
TEST_ROOM_B_ALIAS = RoomAlias("#RoomB-Alias:example.com")
|
||||
TEST_ROOM_C_ID = RoomID("!RoomC-ID:example.com")
|
||||
TEST_JOINABLE_ROOMS: dict[RoomAnyID, RoomID] = {
|
||||
TEST_ROOM_A_ID: TEST_ROOM_A_ID,
|
||||
TEST_ROOM_B_ALIAS: TEST_ROOM_B_ID,
|
||||
TEST_ROOM_C_ID: TEST_ROOM_C_ID,
|
||||
}
|
||||
TEST_BAD_ROOM = "!UninvitedRoom:example.com"
|
||||
TEST_MXID = "@user:example.com"
|
||||
TEST_DEVICE_ID = "FAKEID"
|
||||
TEST_PASSWORD = "password"
|
||||
TEST_TOKEN = "access_token"
|
||||
|
||||
NIO_IMPORT_PREFIX = "homeassistant.components.matrix.nio."
|
||||
|
||||
|
||||
class _MockAsyncClient(AsyncClient):
|
||||
"""Mock class to simulate MatrixBot._client's I/O methods."""
|
||||
|
||||
async def close(self):
|
||||
return None
|
||||
|
||||
async def room_resolve_alias(self, room_alias: RoomAnyID):
|
||||
if room_id := TEST_JOINABLE_ROOMS.get(room_alias):
|
||||
return RoomResolveAliasResponse(
|
||||
room_alias=room_alias, room_id=room_id, servers=[TEST_HOMESERVER]
|
||||
)
|
||||
return RoomResolveAliasError(message=f"Could not resolve {room_alias}")
|
||||
|
||||
async def join(self, room_id: RoomID):
|
||||
if room_id in TEST_JOINABLE_ROOMS.values():
|
||||
return JoinResponse(room_id=room_id)
|
||||
return JoinError(message="Not allowed to join this room.")
|
||||
|
||||
async def login(self, *args, **kwargs):
|
||||
if kwargs.get("password") == TEST_PASSWORD or kwargs.get("token") == TEST_TOKEN:
|
||||
self.access_token = TEST_TOKEN
|
||||
return LoginResponse(
|
||||
access_token=TEST_TOKEN,
|
||||
device_id="test_device",
|
||||
user_id=TEST_MXID,
|
||||
)
|
||||
self.access_token = ""
|
||||
return LoginError(message="LoginError", status_code="status_code")
|
||||
|
||||
async def logout(self, *args, **kwargs):
|
||||
self.access_token = ""
|
||||
|
||||
async def whoami(self):
|
||||
if self.access_token == TEST_TOKEN:
|
||||
self.user_id = TEST_MXID
|
||||
self.device_id = TEST_DEVICE_ID
|
||||
return WhoamiResponse(
|
||||
user_id=TEST_MXID, device_id=TEST_DEVICE_ID, is_guest=False
|
||||
)
|
||||
self.access_token = ""
|
||||
return WhoamiError(
|
||||
message="Invalid access token passed.", status_code="M_UNKNOWN_TOKEN"
|
||||
)
|
||||
|
||||
async def room_send(self, *args, **kwargs):
|
||||
if not self.logged_in:
|
||||
raise LocalProtocolError
|
||||
if kwargs["room_id"] not in TEST_JOINABLE_ROOMS.values():
|
||||
return ErrorResponse(message="Cannot send a message in this room.")
|
||||
return Response()
|
||||
|
||||
async def sync(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
async def sync_forever(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
async def upload(self, *args, **kwargs):
|
||||
return UploadResponse(content_uri="mxc://example.com/randomgibberish"), None
|
||||
|
||||
|
||||
MOCK_CONFIG_DATA = {
|
||||
MATRIX_DOMAIN: {
|
||||
CONF_HOMESERVER: "https://matrix.example.com",
|
||||
CONF_USERNAME: TEST_MXID,
|
||||
CONF_PASSWORD: TEST_PASSWORD,
|
||||
CONF_VERIFY_SSL: True,
|
||||
CONF_ROOMS: list(TEST_JOINABLE_ROOMS),
|
||||
CONF_COMMANDS: [
|
||||
{
|
||||
CONF_WORD: "WordTrigger",
|
||||
CONF_NAME: "WordTriggerEventName",
|
||||
},
|
||||
{
|
||||
CONF_EXPRESSION: "My name is (?P<name>.*)",
|
||||
CONF_NAME: "ExpressionTriggerEventName",
|
||||
},
|
||||
{
|
||||
CONF_WORD: "WordTriggerSubset",
|
||||
CONF_NAME: "WordTriggerSubsetEventName",
|
||||
CONF_ROOMS: [TEST_ROOM_B_ALIAS, TEST_ROOM_C_ID],
|
||||
},
|
||||
{
|
||||
CONF_EXPRESSION: "Your name is (?P<name>.*)",
|
||||
CONF_NAME: "ExpressionTriggerSubsetEventName",
|
||||
CONF_ROOMS: [TEST_ROOM_B_ALIAS, TEST_ROOM_C_ID],
|
||||
},
|
||||
],
|
||||
},
|
||||
NOTIFY_DOMAIN: {
|
||||
CONF_NAME: TEST_NOTIFIER_NAME,
|
||||
CONF_PLATFORM: MATRIX_DOMAIN,
|
||||
CONF_DEFAULT_ROOM: TEST_DEFAULT_ROOM,
|
||||
},
|
||||
}
|
||||
|
||||
MOCK_WORD_COMMANDS = {
|
||||
TEST_ROOM_A_ID: {
|
||||
"WordTrigger": {
|
||||
"word": "WordTrigger",
|
||||
"name": "WordTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
}
|
||||
},
|
||||
TEST_ROOM_B_ID: {
|
||||
"WordTrigger": {
|
||||
"word": "WordTrigger",
|
||||
"name": "WordTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
},
|
||||
"WordTriggerSubset": {
|
||||
"word": "WordTriggerSubset",
|
||||
"name": "WordTriggerSubsetEventName",
|
||||
"rooms": [TEST_ROOM_B_ID, TEST_ROOM_C_ID],
|
||||
},
|
||||
},
|
||||
TEST_ROOM_C_ID: {
|
||||
"WordTrigger": {
|
||||
"word": "WordTrigger",
|
||||
"name": "WordTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
},
|
||||
"WordTriggerSubset": {
|
||||
"word": "WordTriggerSubset",
|
||||
"name": "WordTriggerSubsetEventName",
|
||||
"rooms": [TEST_ROOM_B_ID, TEST_ROOM_C_ID],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
MOCK_EXPRESSION_COMMANDS = {
|
||||
TEST_ROOM_A_ID: [
|
||||
{
|
||||
"expression": re.compile("My name is (?P<name>.*)"),
|
||||
"name": "ExpressionTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
}
|
||||
],
|
||||
TEST_ROOM_B_ID: [
|
||||
{
|
||||
"expression": re.compile("My name is (?P<name>.*)"),
|
||||
"name": "ExpressionTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
},
|
||||
{
|
||||
"expression": re.compile("Your name is (?P<name>.*)"),
|
||||
"name": "ExpressionTriggerSubsetEventName",
|
||||
"rooms": [TEST_ROOM_B_ID, TEST_ROOM_C_ID],
|
||||
},
|
||||
],
|
||||
TEST_ROOM_C_ID: [
|
||||
{
|
||||
"expression": re.compile("My name is (?P<name>.*)"),
|
||||
"name": "ExpressionTriggerEventName",
|
||||
"rooms": list(TEST_JOINABLE_ROOMS.values()),
|
||||
},
|
||||
{
|
||||
"expression": re.compile("Your name is (?P<name>.*)"),
|
||||
"name": "ExpressionTriggerSubsetEventName",
|
||||
"rooms": [TEST_ROOM_B_ID, TEST_ROOM_C_ID],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client():
|
||||
"""Return mocked AsyncClient."""
|
||||
with patch("homeassistant.components.matrix.AsyncClient", _MockAsyncClient) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_save_json():
|
||||
"""Prevent saving test access_tokens."""
|
||||
with patch("homeassistant.components.matrix.save_json") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_load_json():
|
||||
"""Mock loading access_tokens from a file."""
|
||||
with patch(
|
||||
"homeassistant.components.matrix.load_json_object",
|
||||
return_value={TEST_MXID: TEST_TOKEN},
|
||||
) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_allowed_path():
|
||||
"""Allow using NamedTemporaryFile for mock image."""
|
||||
with patch(
|
||||
"homeassistant.core_config.Config.is_allowed_path", return_value=True
|
||||
) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def matrix_bot(
|
||||
hass: HomeAssistant, mock_client, mock_save_json, mock_allowed_path
|
||||
) -> MatrixBot:
|
||||
"""Set up Matrix and Notify component.
|
||||
|
||||
The resulting MatrixBot will have a mocked _client.
|
||||
"""
|
||||
|
||||
assert await async_setup_component(hass, MATRIX_DOMAIN, MOCK_CONFIG_DATA)
|
||||
assert await async_setup_component(hass, NOTIFY_DOMAIN, MOCK_CONFIG_DATA)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Accessing hass.data in tests is not desirable, but all the tests here
|
||||
# currently do this.
|
||||
assert isinstance(matrix_bot := hass.data[MATRIX_DOMAIN], MatrixBot)
|
||||
|
||||
await hass.async_start()
|
||||
|
||||
return matrix_bot
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def matrix_events(hass: HomeAssistant) -> list[Event]:
|
||||
"""Track event calls."""
|
||||
return async_capture_events(hass, MATRIX_DOMAIN)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def command_events(hass: HomeAssistant) -> list[Event]:
|
||||
"""Track event calls."""
|
||||
return async_capture_events(hass, EVENT_MATRIX_COMMAND)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def image_path(tmp_path: Path) -> Generator[tempfile._TemporaryFileWrapper]:
|
||||
"""Provide the Path to a mock image."""
|
||||
image = Image.new("RGBA", size=(50, 50), color=(256, 0, 0))
|
||||
with tempfile.NamedTemporaryFile(dir=tmp_path) as image_file:
|
||||
image.save(image_file, "PNG")
|
||||
yield image_file
|
||||
181
home-assistant/tests/components/matrix/test_commands.py
Normal file
181
home-assistant/tests/components/matrix/test_commands.py
Normal file
@@ -0,0 +1,181 @@
|
||||
"""Test MatrixBot's ability to parse and respond to commands in matrix rooms."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
from itertools import chain
|
||||
from typing import Any
|
||||
|
||||
from nio import MatrixRoom, RoomMessageText
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.matrix import MatrixBot, RoomID
|
||||
from homeassistant.core import Event, HomeAssistant
|
||||
|
||||
from .conftest import (
|
||||
MOCK_EXPRESSION_COMMANDS,
|
||||
MOCK_WORD_COMMANDS,
|
||||
TEST_MXID,
|
||||
TEST_ROOM_A_ID,
|
||||
TEST_ROOM_B_ID,
|
||||
TEST_ROOM_C_ID,
|
||||
)
|
||||
|
||||
ALL_ROOMS = (TEST_ROOM_A_ID, TEST_ROOM_B_ID, TEST_ROOM_C_ID)
|
||||
SUBSET_ROOMS = (TEST_ROOM_B_ID, TEST_ROOM_C_ID)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CommandTestParameters:
|
||||
"""Dataclass of parameters representing the command config parameters and expected result state.
|
||||
|
||||
Switches behavior based on `room_id` and `expected_event_room_data`.
|
||||
"""
|
||||
|
||||
room_id: RoomID
|
||||
room_message: RoomMessageText
|
||||
expected_event_data_extra: dict[str, Any] | None
|
||||
|
||||
@property
|
||||
def expected_event_data(self) -> dict[str, Any] | None:
|
||||
"""Fully-constructed expected event data.
|
||||
|
||||
Commands that are named with 'Subset' are expected not to be read from Room A.
|
||||
"""
|
||||
|
||||
if (
|
||||
self.expected_event_data_extra is None
|
||||
or "Subset" in self.expected_event_data_extra["command"]
|
||||
and self.room_id not in SUBSET_ROOMS
|
||||
):
|
||||
return None
|
||||
return {
|
||||
"sender": "@SomeUser:example.com",
|
||||
"room": self.room_id,
|
||||
} | self.expected_event_data_extra
|
||||
|
||||
|
||||
room_message_base = partial(
|
||||
RoomMessageText,
|
||||
formatted_body=None,
|
||||
format=None,
|
||||
source={
|
||||
"event_id": "fake_event_id",
|
||||
"sender": "@SomeUser:example.com",
|
||||
"origin_server_ts": 123456789,
|
||||
},
|
||||
)
|
||||
word_command_global = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(body="!WordTrigger arg1 arg2"),
|
||||
expected_event_data_extra={
|
||||
"command": "WordTriggerEventName",
|
||||
"args": ["arg1", "arg2"],
|
||||
},
|
||||
)
|
||||
expr_command_global = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(body="My name is FakeName"),
|
||||
expected_event_data_extra={
|
||||
"command": "ExpressionTriggerEventName",
|
||||
"args": {"name": "FakeName"},
|
||||
},
|
||||
)
|
||||
word_command_subset = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(body="!WordTriggerSubset arg1 arg2"),
|
||||
expected_event_data_extra={
|
||||
"command": "WordTriggerSubsetEventName",
|
||||
"args": ["arg1", "arg2"],
|
||||
},
|
||||
)
|
||||
expr_command_subset = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(body="Your name is FakeName"),
|
||||
expected_event_data_extra={
|
||||
"command": "ExpressionTriggerSubsetEventName",
|
||||
"args": {"name": "FakeName"},
|
||||
},
|
||||
)
|
||||
# Messages without commands should trigger nothing
|
||||
fake_command_global = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(body="This is not a real command!"),
|
||||
expected_event_data_extra=None,
|
||||
)
|
||||
# Valid commands sent by the bot user should trigger nothing
|
||||
self_command_global = partial(
|
||||
CommandTestParameters,
|
||||
room_message=room_message_base(
|
||||
body="!WordTrigger arg1 arg2",
|
||||
source={
|
||||
"event_id": "fake_event_id",
|
||||
"sender": TEST_MXID,
|
||||
"origin_server_ts": 123456789,
|
||||
},
|
||||
),
|
||||
expected_event_data_extra=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"command_params",
|
||||
chain(
|
||||
(word_command_global(room_id) for room_id in ALL_ROOMS),
|
||||
(expr_command_global(room_id) for room_id in ALL_ROOMS),
|
||||
(word_command_subset(room_id) for room_id in SUBSET_ROOMS),
|
||||
(expr_command_subset(room_id) for room_id in SUBSET_ROOMS),
|
||||
),
|
||||
)
|
||||
async def test_commands(
|
||||
hass: HomeAssistant,
|
||||
matrix_bot: MatrixBot,
|
||||
command_events: list[Event],
|
||||
command_params: CommandTestParameters,
|
||||
) -> None:
|
||||
"""Test that the configured commands are used correctly."""
|
||||
room = MatrixRoom(room_id=command_params.room_id, own_user_id=matrix_bot._mx_id)
|
||||
|
||||
await hass.async_start()
|
||||
assert len(command_events) == 0
|
||||
await matrix_bot._handle_room_message(room, command_params.room_message)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# MatrixBot should emit exactly one Event with matching data from this Command
|
||||
assert len(command_events) == 1
|
||||
event = command_events[0]
|
||||
assert event.data == command_params.expected_event_data
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"command_params",
|
||||
chain(
|
||||
(word_command_subset(TEST_ROOM_A_ID),),
|
||||
(expr_command_subset(TEST_ROOM_A_ID),),
|
||||
(fake_command_global(room_id) for room_id in ALL_ROOMS),
|
||||
(self_command_global(room_id) for room_id in ALL_ROOMS),
|
||||
),
|
||||
)
|
||||
async def test_non_commands(
|
||||
hass: HomeAssistant,
|
||||
matrix_bot: MatrixBot,
|
||||
command_events: list[Event],
|
||||
command_params: CommandTestParameters,
|
||||
) -> None:
|
||||
"""Test that normal/non-qualifying messages don't wrongly trigger commands."""
|
||||
room = MatrixRoom(room_id=command_params.room_id, own_user_id=matrix_bot._mx_id)
|
||||
|
||||
await hass.async_start()
|
||||
assert len(command_events) == 0
|
||||
await matrix_bot._handle_room_message(room, command_params.room_message)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# MatrixBot should not treat this message as a Command
|
||||
assert len(command_events) == 0
|
||||
|
||||
|
||||
async def test_commands_parsing(hass: HomeAssistant, matrix_bot: MatrixBot) -> None:
|
||||
"""Test that the configured commands were parsed correctly."""
|
||||
|
||||
await hass.async_start()
|
||||
assert matrix_bot._word_commands == MOCK_WORD_COMMANDS
|
||||
assert matrix_bot._expression_commands == MOCK_EXPRESSION_COMMANDS
|
||||
113
home-assistant/tests/components/matrix/test_login.py
Normal file
113
home-assistant/tests/components/matrix/test_login.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""Test MatrixBot._login."""
|
||||
|
||||
from pydantic.dataclasses import dataclass
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.matrix import MatrixBot
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
|
||||
|
||||
from .conftest import TEST_DEVICE_ID, TEST_MXID, TEST_PASSWORD, TEST_TOKEN
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoginTestParameters:
|
||||
"""Dataclass of parameters representing the login parameters and expected result state."""
|
||||
|
||||
password: str
|
||||
access_token: dict[str, str]
|
||||
expected_login_state: bool
|
||||
expected_caplog_messages: set[str]
|
||||
expected_expection: type(Exception) | None = None
|
||||
|
||||
|
||||
good_password_missing_token = LoginTestParameters(
|
||||
password=TEST_PASSWORD,
|
||||
access_token={},
|
||||
expected_login_state=True,
|
||||
expected_caplog_messages={"Logging in using password"},
|
||||
)
|
||||
|
||||
good_password_bad_token = LoginTestParameters(
|
||||
password=TEST_PASSWORD,
|
||||
access_token={TEST_MXID: "WrongToken"},
|
||||
expected_login_state=True,
|
||||
expected_caplog_messages={
|
||||
"Restoring login from stored access token",
|
||||
"Restoring login from access token failed: M_UNKNOWN_TOKEN, Invalid access token passed.",
|
||||
"Logging in using password",
|
||||
},
|
||||
)
|
||||
|
||||
bad_password_good_access_token = LoginTestParameters(
|
||||
password="WrongPassword",
|
||||
access_token={TEST_MXID: TEST_TOKEN},
|
||||
expected_login_state=True,
|
||||
expected_caplog_messages={
|
||||
"Restoring login from stored access token",
|
||||
f"Successfully restored login from access token: user_id '{TEST_MXID}', device_id '{TEST_DEVICE_ID}'",
|
||||
},
|
||||
)
|
||||
|
||||
bad_password_bad_access_token = LoginTestParameters(
|
||||
password="WrongPassword",
|
||||
access_token={TEST_MXID: "WrongToken"},
|
||||
expected_login_state=False,
|
||||
expected_caplog_messages={
|
||||
"Restoring login from stored access token",
|
||||
"Restoring login from access token failed: M_UNKNOWN_TOKEN, Invalid access token passed.",
|
||||
"Logging in using password",
|
||||
"Login by password failed: status_code, LoginError",
|
||||
},
|
||||
expected_expection=ConfigEntryAuthFailed,
|
||||
)
|
||||
|
||||
bad_password_missing_access_token = LoginTestParameters(
|
||||
password="WrongPassword",
|
||||
access_token={},
|
||||
expected_login_state=False,
|
||||
expected_caplog_messages={
|
||||
"Logging in using password",
|
||||
"Login by password failed: status_code, LoginError",
|
||||
},
|
||||
expected_expection=ConfigEntryAuthFailed,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"params",
|
||||
[
|
||||
good_password_missing_token,
|
||||
good_password_bad_token,
|
||||
bad_password_good_access_token,
|
||||
bad_password_bad_access_token,
|
||||
bad_password_missing_access_token,
|
||||
],
|
||||
)
|
||||
async def test_login(
|
||||
matrix_bot: MatrixBot, caplog: pytest.LogCaptureFixture, params: LoginTestParameters
|
||||
) -> None:
|
||||
"""Test logging in with the given parameters and expected state."""
|
||||
await matrix_bot._client.logout()
|
||||
matrix_bot._password = params.password
|
||||
matrix_bot._access_tokens = params.access_token
|
||||
|
||||
if params.expected_expection:
|
||||
with pytest.raises(params.expected_expection):
|
||||
await matrix_bot._login()
|
||||
else:
|
||||
await matrix_bot._login()
|
||||
assert matrix_bot._client.logged_in == params.expected_login_state
|
||||
assert set(caplog.messages).issuperset(params.expected_caplog_messages)
|
||||
|
||||
|
||||
async def test_get_auth_tokens(matrix_bot: MatrixBot, mock_load_json) -> None:
|
||||
"""Test loading access_tokens from a mocked file."""
|
||||
|
||||
# Test loading good tokens.
|
||||
loaded_tokens = await matrix_bot._get_auth_tokens()
|
||||
assert loaded_tokens == {TEST_MXID: TEST_TOKEN}
|
||||
|
||||
# Test miscellaneous error from hass.
|
||||
mock_load_json.side_effect = HomeAssistantError()
|
||||
loaded_tokens = await matrix_bot._get_auth_tokens()
|
||||
assert loaded_tokens == {}
|
||||
25
home-assistant/tests/components/matrix/test_matrix_bot.py
Normal file
25
home-assistant/tests/components/matrix/test_matrix_bot.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""Configure and test MatrixBot."""
|
||||
|
||||
from homeassistant.components.matrix import (
|
||||
DOMAIN as MATRIX_DOMAIN,
|
||||
SERVICE_SEND_MESSAGE,
|
||||
MatrixBot,
|
||||
)
|
||||
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .conftest import TEST_NOTIFIER_NAME
|
||||
|
||||
|
||||
async def test_services(hass: HomeAssistant, matrix_bot: MatrixBot) -> None:
|
||||
"""Test hass/MatrixBot state."""
|
||||
|
||||
services = hass.services.async_services()
|
||||
|
||||
# Verify that the matrix service is registered
|
||||
assert (matrix_service := services.get(MATRIX_DOMAIN))
|
||||
assert SERVICE_SEND_MESSAGE in matrix_service
|
||||
|
||||
# Verify that the matrix notifier is registered
|
||||
assert (notify_service := services.get(NOTIFY_DOMAIN))
|
||||
assert TEST_NOTIFIER_NAME in notify_service
|
||||
48
home-assistant/tests/components/matrix/test_rooms.py
Normal file
48
home-assistant/tests/components/matrix/test_rooms.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""Test MatrixBot._join."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.matrix import MatrixBot
|
||||
from homeassistant.components.matrix.const import DOMAIN as MATRIX_DOMAIN
|
||||
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_START
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .conftest import MOCK_CONFIG_DATA, TEST_BAD_ROOM, TEST_JOINABLE_ROOMS
|
||||
|
||||
|
||||
async def test_join(
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
mock_client,
|
||||
mock_save_json,
|
||||
mock_allowed_path,
|
||||
) -> None:
|
||||
"""Test joining configured rooms."""
|
||||
assert await async_setup_component(hass, MATRIX_DOMAIN, MOCK_CONFIG_DATA)
|
||||
assert await async_setup_component(hass, NOTIFY_DOMAIN, MOCK_CONFIG_DATA)
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
# Accessing hass.data in tests is not desirable, but all the tests here
|
||||
# currently do this.
|
||||
matrix_bot = hass.data[MATRIX_DOMAIN]
|
||||
|
||||
for room_id in TEST_JOINABLE_ROOMS:
|
||||
assert f"Joined or already in room '{room_id}'" in caplog.messages
|
||||
|
||||
# Joining a disallowed room should not raise an exception.
|
||||
matrix_bot._listening_rooms = {TEST_BAD_ROOM: TEST_BAD_ROOM}
|
||||
await matrix_bot._join_rooms()
|
||||
assert (
|
||||
f"Could not join room '{TEST_BAD_ROOM}': JoinError: Not allowed to join this room."
|
||||
in caplog.messages
|
||||
)
|
||||
|
||||
|
||||
async def test_resolve_aliases(hass: HomeAssistant, matrix_bot: MatrixBot) -> None:
|
||||
"""Test resolving configured room aliases into room ids."""
|
||||
|
||||
await hass.async_start()
|
||||
assert matrix_bot._listening_rooms == TEST_JOINABLE_ROOMS
|
||||
82
home-assistant/tests/components/matrix/test_send_message.py
Normal file
82
home-assistant/tests/components/matrix/test_send_message.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""Test the send_message service."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.matrix import (
|
||||
ATTR_FORMAT,
|
||||
ATTR_IMAGES,
|
||||
DOMAIN as MATRIX_DOMAIN,
|
||||
MatrixBot,
|
||||
)
|
||||
from homeassistant.components.matrix.const import FORMAT_HTML, SERVICE_SEND_MESSAGE
|
||||
from homeassistant.components.notify import ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET
|
||||
from homeassistant.core import Event, HomeAssistant
|
||||
|
||||
from .conftest import TEST_BAD_ROOM, TEST_JOINABLE_ROOMS
|
||||
|
||||
|
||||
async def test_send_message(
|
||||
hass: HomeAssistant,
|
||||
matrix_bot: MatrixBot,
|
||||
image_path,
|
||||
matrix_events: list[Event],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the send_message service."""
|
||||
|
||||
await hass.async_start()
|
||||
assert len(matrix_events) == 0
|
||||
await matrix_bot._login()
|
||||
|
||||
# Send a message without an attached image.
|
||||
data = {ATTR_MESSAGE: "Test message", ATTR_TARGET: list(TEST_JOINABLE_ROOMS)}
|
||||
await hass.services.async_call(
|
||||
MATRIX_DOMAIN, SERVICE_SEND_MESSAGE, data, blocking=True
|
||||
)
|
||||
|
||||
for room_alias_or_id in TEST_JOINABLE_ROOMS:
|
||||
assert f"Message delivered to room '{room_alias_or_id}'" in caplog.messages
|
||||
|
||||
# Send an HTML message without an attached image.
|
||||
data = {
|
||||
ATTR_MESSAGE: "Test message",
|
||||
ATTR_TARGET: list(TEST_JOINABLE_ROOMS),
|
||||
ATTR_DATA: {ATTR_FORMAT: FORMAT_HTML},
|
||||
}
|
||||
await hass.services.async_call(
|
||||
MATRIX_DOMAIN, SERVICE_SEND_MESSAGE, data, blocking=True
|
||||
)
|
||||
|
||||
for room_alias_or_id in TEST_JOINABLE_ROOMS:
|
||||
assert f"Message delivered to room '{room_alias_or_id}'" in caplog.messages
|
||||
|
||||
# Send a message with an attached image.
|
||||
data[ATTR_DATA] = {ATTR_IMAGES: [image_path.name]}
|
||||
await hass.services.async_call(
|
||||
MATRIX_DOMAIN, SERVICE_SEND_MESSAGE, data, blocking=True
|
||||
)
|
||||
|
||||
for room_alias_or_id in TEST_JOINABLE_ROOMS:
|
||||
assert f"Message delivered to room '{room_alias_or_id}'" in caplog.messages
|
||||
|
||||
|
||||
async def test_unsendable_message(
|
||||
hass: HomeAssistant,
|
||||
matrix_bot: MatrixBot,
|
||||
matrix_events: list[Event],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the send_message service with an invalid room."""
|
||||
assert len(matrix_events) == 0
|
||||
await matrix_bot._login()
|
||||
|
||||
data = {ATTR_MESSAGE: "Test message", ATTR_TARGET: TEST_BAD_ROOM}
|
||||
|
||||
await hass.services.async_call(
|
||||
MATRIX_DOMAIN, SERVICE_SEND_MESSAGE, data, blocking=True
|
||||
)
|
||||
|
||||
assert (
|
||||
f"Unable to deliver message to room '{TEST_BAD_ROOM}': ErrorResponse: Cannot send a message in this room."
|
||||
in caplog.messages
|
||||
)
|
||||
Reference in New Issue
Block a user