init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for the websocket API."""

View File

@@ -0,0 +1,44 @@
"""Fixtures for websocket tests."""
from aiohttp.test_utils import TestClient
import pytest
from homeassistant.components.websocket_api.auth import TYPE_AUTH_REQUIRED
from homeassistant.components.websocket_api.http import URL
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.typing import (
ClientSessionGenerator,
MockHAClientWebSocket,
WebSocketGenerator,
)
@pytest.fixture
async def websocket_client(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> MockHAClientWebSocket:
"""Create a websocket client."""
return await hass_ws_client(hass)
@pytest.fixture
async def no_auth_websocket_client(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> TestClient:
"""Websocket connection that requires authentication."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
ws = await client.ws_connect(URL)
auth_ok = await ws.receive_json()
assert auth_ok["type"] == TYPE_AUTH_REQUIRED
ws.client = client
yield ws
if not ws.closed:
await ws.close()

View File

@@ -0,0 +1,298 @@
"""Test auth of websocket API."""
from unittest.mock import patch
import aiohttp
from aiohttp import WSMsgType
import pytest
from homeassistant.auth.providers.homeassistant import HassAuthProvider
from homeassistant.components.websocket_api.auth import (
TYPE_AUTH,
TYPE_AUTH_INVALID,
TYPE_AUTH_OK,
TYPE_AUTH_REQUIRED,
)
from homeassistant.components.websocket_api.const import (
SIGNAL_WEBSOCKET_CONNECTED,
SIGNAL_WEBSOCKET_DISCONNECTED,
URL,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.setup import async_setup_component
from tests.typing import ClientSessionGenerator
@pytest.fixture
def track_connected(hass: HomeAssistant) -> dict[str, list[int]]:
"""Track connected and disconnected events."""
connected_evt = []
@callback
def track_connected():
connected_evt.append(1)
async_dispatcher_connect(hass, SIGNAL_WEBSOCKET_CONNECTED, track_connected)
disconnected_evt = []
@callback
def track_disconnected():
disconnected_evt.append(1)
async_dispatcher_connect(hass, SIGNAL_WEBSOCKET_DISCONNECTED, track_disconnected)
return {"connected": connected_evt, "disconnected": disconnected_evt}
async def test_auth_events(
hass: HomeAssistant,
no_auth_websocket_client,
local_auth: HassAuthProvider,
hass_access_token: str,
track_connected,
) -> None:
"""Test authenticating."""
await test_auth_active_with_token(hass, no_auth_websocket_client, hass_access_token)
assert len(track_connected["connected"]) == 1
assert not track_connected["disconnected"]
await no_auth_websocket_client.close()
await hass.async_block_till_done()
assert len(track_connected["disconnected"]) == 1
async def test_auth_via_msg_incorrect_pass(no_auth_websocket_client) -> None:
"""Test authenticating."""
with patch(
"homeassistant.components.websocket_api.auth.process_wrong_login",
) as mock_process_wrong_login:
await no_auth_websocket_client.send_json(
{"type": TYPE_AUTH, "api_password": "wrong"}
)
msg = await no_auth_websocket_client.receive_json()
assert mock_process_wrong_login.called
assert msg["type"] == TYPE_AUTH_INVALID
assert msg["message"] == "Invalid access token or password"
async def test_auth_events_incorrect_pass(
no_auth_websocket_client, track_connected
) -> None:
"""Test authenticating."""
await test_auth_via_msg_incorrect_pass(no_auth_websocket_client)
assert not track_connected["connected"]
assert not track_connected["disconnected"]
await no_auth_websocket_client.close()
assert not track_connected["connected"]
assert not track_connected["disconnected"]
async def test_pre_auth_only_auth_allowed(no_auth_websocket_client) -> None:
"""Verify that before authentication, only auth messages are allowed."""
await no_auth_websocket_client.send_json(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await no_auth_websocket_client.receive_json()
assert msg["type"] == TYPE_AUTH_INVALID
assert msg["message"].startswith("Auth message incorrectly formatted")
async def test_auth_active_with_token(
hass: HomeAssistant, no_auth_websocket_client, hass_access_token: str
) -> None:
"""Test authenticating with a token."""
await no_auth_websocket_client.send_json(
{"type": TYPE_AUTH, "access_token": hass_access_token}
)
auth_msg = await no_auth_websocket_client.receive_json()
assert auth_msg["type"] == TYPE_AUTH_OK
async def test_auth_active_user_inactive(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test authenticating with a token."""
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
refresh_token.user.is_active = False
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_json({"type": TYPE_AUTH, "access_token": hass_access_token})
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_INVALID
async def test_auth_active_with_password_not_allow(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test authenticating with a token."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_json({"type": TYPE_AUTH, "api_password": "some-password"})
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_INVALID
async def test_auth_legacy_support_with_password(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
local_auth: HassAuthProvider,
) -> None:
"""Test authenticating with a token."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_json({"type": TYPE_AUTH, "api_password": "some-password"})
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_INVALID
async def test_auth_with_invalid_token(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test authenticating with a token."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_json({"type": TYPE_AUTH, "access_token": "incorrect"})
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_INVALID
async def test_auth_close_after_revoke(
hass: HomeAssistant, websocket_client, hass_access_token: str
) -> None:
"""Test that a websocket is closed after the refresh token is revoked."""
assert not websocket_client.closed
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
hass.auth.async_remove_refresh_token(refresh_token)
msg = await websocket_client.receive()
assert msg.type is aiohttp.WSMsgType.CLOSE
assert websocket_client.closed
async def test_auth_sending_invalid_json_disconnects(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test sending invalid json during auth."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_str("[--INVALID--JSON--]")
auth_msg = await ws.receive()
assert auth_msg.type == WSMsgType.close
async def test_auth_sending_binary_disconnects(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test sending bytes during auth."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_bytes(b"[INVALID]")
auth_msg = await ws.receive()
assert auth_msg.type == WSMsgType.close
async def test_auth_close_disconnects(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test closing during auth."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.close()
auth_msg = await ws.receive()
assert auth_msg.type == WSMsgType.CLOSED
async def test_auth_sending_unknown_type_disconnects(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Test sending unknown type during auth."""
assert await async_setup_component(hass, "websocket_api", {})
await hass.async_block_till_done()
client = await hass_client_no_auth()
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws._writer.send_frame(b"1" * 130, 0x30)
auth_msg = await ws.receive()
assert auth_msg.type == WSMsgType.close

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,134 @@
"""Test WebSocket Connection class."""
import logging
from typing import Any
from unittest.mock import Mock, patch
from aiohttp.test_utils import make_mocked_request
import pytest
import voluptuous as vol
from homeassistant import exceptions
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockUser
@pytest.mark.parametrize(
("exc", "code", "err", "log"),
[
(
exceptions.Unauthorized(),
websocket_api.ERR_UNAUTHORIZED,
"Unauthorized",
"Error handling message: Unauthorized (unauthorized) Mock User from 127.0.0.42 (Browser)",
),
(
vol.Invalid("Invalid something"),
websocket_api.ERR_INVALID_FORMAT,
"Invalid something. Got {'id': 5}",
"Error handling message: Invalid something. Got {'id': 5} (invalid_format) Mock User from 127.0.0.42 (Browser)",
),
(
TimeoutError(),
websocket_api.ERR_TIMEOUT,
"Timeout",
"Error handling message: Timeout (timeout) Mock User from 127.0.0.42 (Browser)",
),
(
exceptions.HomeAssistantError("Failed to do X"),
websocket_api.ERR_HOME_ASSISTANT_ERROR,
"Failed to do X",
"Error handling message: Failed to do X (home_assistant_error) Mock User from 127.0.0.42 (Browser)",
),
(
exceptions.ServiceValidationError("Failed to do X"),
websocket_api.ERR_HOME_ASSISTANT_ERROR,
"Failed to do X",
"Error handling message: Failed to do X (home_assistant_error) Mock User from 127.0.0.42 (Browser)",
),
(
ValueError("Really bad"),
websocket_api.ERR_UNKNOWN_ERROR,
"Unknown error",
"Error handling message: Unknown error (unknown_error) Mock User from 127.0.0.42 (Browser)",
),
(
exceptions.HomeAssistantError,
websocket_api.ERR_UNKNOWN_ERROR,
"Unknown error",
"Error handling message: Unknown error (unknown_error) Mock User from 127.0.0.42 (Browser)",
),
],
)
async def test_exception_handling(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
exc: Exception,
code: str,
err: str,
log: str,
) -> None:
"""Test handling of exceptions."""
send_messages = []
user = MockUser()
refresh_token = Mock()
hass.data[DOMAIN] = {}
def get_extra_info(key: str) -> Any | None:
if key == "sslcontext":
return True
if key == "peername":
return ("127.0.0.42", 8123)
return None
mocked_transport = Mock()
mocked_transport.get_extra_info = get_extra_info
mocked_request = make_mocked_request(
"GET",
"/api/websocket",
headers={"Host": "example.com", "User-Agent": "Browser"},
transport=mocked_transport,
)
with patch(
"homeassistant.components.websocket_api.connection.current_request",
) as current_request:
current_request.get.return_value = mocked_request
conn = websocket_api.ActiveConnection(
logging.getLogger(__name__), hass, send_messages.append, user, refresh_token
)
conn.async_handle_exception({"id": 5}, exc)
assert len(send_messages) == 1
assert send_messages[0]["error"]["code"] == code
assert send_messages[0]["error"]["message"] == err
assert log in caplog.text
async def test_binary_handler_registration() -> None:
"""Test binary handler registration."""
connection = websocket_api.ActiveConnection(
None, Mock(data={websocket_api.DOMAIN: None}), None, None, Mock()
)
# One filler to align indexes with prefix numbers
unsubs = [None]
fake_handler = object()
for i in range(255):
prefix, unsub = connection.async_register_binary_handler(fake_handler)
assert prefix == i + 1
unsubs.append(unsub)
with pytest.raises(RuntimeError):
connection.async_register_binary_handler(None)
unsubs[15]()
# Verify we reuse an unsubscribed prefix
prefix, unsub = connection.async_register_binary_handler(None)
assert prefix == 15

View File

@@ -0,0 +1,185 @@
"""Test decorators."""
from typing import Any
import voluptuous as vol
from homeassistant.components import http, websocket_api
from homeassistant.core import HomeAssistant
async def test_async_response_request_context(
hass: HomeAssistant, websocket_client
) -> None:
"""Test we can access current request."""
def handle_request(request, connection, msg):
if request is not None:
connection.send_result(msg["id"], request.path)
else:
connection.send_error(msg["id"], "not_found", "")
@websocket_api.websocket_command({"type": "test-get-request-executor"})
@websocket_api.async_response
async def executor_get_request(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
handle_request(
await hass.async_add_executor_job(http.current_request.get), connection, msg
)
@websocket_api.websocket_command({"type": "test-get-request-async"})
@websocket_api.async_response
async def async_get_request(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
handle_request(http.current_request.get(), connection, msg)
@websocket_api.websocket_command({"type": "test-get-request"})
def get_request(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
handle_request(http.current_request.get(), connection, msg)
@websocket_api.websocket_command(
{"type": "test-get-request-with-arg", vol.Required("arg"): str}
)
def get_with_arg_request(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
handle_request(http.current_request.get(), connection, msg)
websocket_api.async_register_command(hass, executor_get_request)
websocket_api.async_register_command(hass, async_get_request)
websocket_api.async_register_command(hass, get_request)
websocket_api.async_register_command(hass, get_with_arg_request)
await websocket_client.send_json(
{
"id": 5,
"type": "test-get-request",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["success"]
assert msg["result"] == "/api/websocket"
await websocket_client.send_json(
{
"id": 6,
"type": "test-get-request-async",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["success"]
assert msg["result"] == "/api/websocket"
await websocket_client.send_json(
{
"id": 7,
"type": "test-get-request-executor",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 7
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
await websocket_client.send_json(
{
"id": 8,
"type": "test-get-request-with-arg",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 8
assert not msg["success"]
assert msg["error"]["code"] == "invalid_format"
assert (
msg["error"]["message"] == "required key not provided @ data['arg']. Got None"
)
await websocket_client.send_json(
{
"id": 9,
"type": "test-get-request-with-arg",
"arg": "dog",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 9
assert msg["success"]
assert msg["result"] == "/api/websocket"
await websocket_client.send_json(
{
"id": -1,
"type": "test-get-request-with-arg",
"arg": "dog",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == -1
assert not msg["success"]
assert msg["error"]["code"] == "invalid_format"
assert msg["error"]["message"] == "Message incorrectly formatted."
await websocket_client.send_json(
{
"id": 10,
"type": "test-get-request",
"not_valid": "dog",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 10
assert not msg["success"]
assert msg["error"]["code"] == "invalid_format"
assert msg["error"]["message"] == (
"extra keys not allowed. "
"Got {'id': 10, 'type': 'test-get-request', 'not_valid': 'dog'}"
)
async def test_supervisor_only(hass: HomeAssistant, websocket_client) -> None:
"""Test that only the Supervisor can make requests."""
@websocket_api.ws_require_user(only_supervisor=True)
@websocket_api.websocket_command({"type": "test-require-supervisor-user"})
def require_supervisor_request(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
connection.send_result(msg["id"])
websocket_api.async_register_command(hass, require_supervisor_request)
await websocket_client.send_json(
{
"id": 5,
"type": "test-require-supervisor-user",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert not msg["success"]
assert msg["error"]["code"] == "only_supervisor"

View File

@@ -0,0 +1,525 @@
"""Test Websocket API http module."""
import asyncio
from datetime import timedelta
from typing import Any, cast
from unittest.mock import patch
from aiohttp import ServerDisconnectedError, WSMsgType, web
import pytest
from homeassistant.components.websocket_api import (
async_register_command,
const,
http,
websocket_command,
)
from homeassistant.components.websocket_api.connection import ActiveConnection
from homeassistant.core import HomeAssistant, callback
from homeassistant.util.dt import utcnow
from tests.common import async_fire_time_changed
from tests.typing import MockHAClientWebSocket, WebSocketGenerator
@pytest.fixture
def mock_low_queue():
"""Mock a low queue."""
with patch("homeassistant.components.websocket_api.http.MAX_PENDING_MSG", 1):
yield
@pytest.fixture
def mock_low_peak():
"""Mock a low queue."""
with patch("homeassistant.components.websocket_api.http.PENDING_MSG_PEAK", 5):
yield
async def test_pending_msg_overflow(
hass: HomeAssistant, mock_low_queue, websocket_client: MockHAClientWebSocket
) -> None:
"""Test pending messages overflows."""
for idx in range(10):
await websocket_client.send_json({"id": idx + 1, "type": "ping"})
msg = await websocket_client.receive()
assert msg.type is WSMsgType.CLOSE
async def test_cleanup_on_cancellation(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test cleanup on cancellation."""
subscriptions = None
# Register a handler that registers a subscription
@callback
@websocket_command(
{
"type": "fake_subscription",
}
)
def fake_subscription(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
nonlocal subscriptions
msg_id: int = msg["id"]
connection.subscriptions[msg_id] = callback(lambda: None)
connection.send_result(msg_id)
subscriptions = connection.subscriptions
async_register_command(hass, fake_subscription)
# Register a handler that raises on cancel
@callback
@websocket_command(
{
"type": "subscription_that_raises_on_cancel",
}
)
def subscription_that_raises_on_cancel(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
nonlocal subscriptions
msg_id: int = msg["id"]
@callback
def _raise():
raise ValueError
connection.subscriptions[msg_id] = _raise
connection.send_result(msg_id)
subscriptions = connection.subscriptions
async_register_command(hass, subscription_that_raises_on_cancel)
# Register a handler that cancels in handler
@callback
@websocket_command(
{
"type": "cancel_in_handler",
}
)
def cancel_in_handler(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
raise asyncio.CancelledError
async_register_command(hass, cancel_in_handler)
await websocket_client.send_json({"id": 1, "type": "ping"})
msg = await websocket_client.receive_json()
assert msg["id"] == 1
assert msg["type"] == "pong"
assert not subscriptions
await websocket_client.send_json({"id": 2, "type": "fake_subscription"})
msg = await websocket_client.receive_json()
assert msg["id"] == 2
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(subscriptions) == 2
await websocket_client.send_json(
{"id": 3, "type": "subscription_that_raises_on_cancel"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 3
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(subscriptions) == 3
await websocket_client.send_json({"id": 4, "type": "cancel_in_handler"})
await hass.async_block_till_done()
msg = await websocket_client.receive()
assert msg.type == WSMsgType.close
assert len(subscriptions) == 0
async def test_delayed_response_handler(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test a handler that responds after a connection has already been closed."""
subscriptions = None
# Register a handler that responds after it returns
@callback
@websocket_command(
{
"type": "late_responder",
}
)
def async_late_responder(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
msg_id: int = msg["id"]
nonlocal subscriptions
subscriptions = connection.subscriptions
connection.subscriptions[msg_id] = lambda: None
connection.send_result(msg_id)
async def _async_late_send_message():
await asyncio.sleep(0.05)
connection.send_event(msg_id, {"event": "any"})
hass.async_create_task(_async_late_send_message())
async_register_command(hass, async_late_responder)
await websocket_client.send_json({"id": 1, "type": "ping"})
msg = await websocket_client.receive_json()
assert msg["id"] == 1
assert msg["type"] == "pong"
assert not subscriptions
await websocket_client.send_json({"id": 2, "type": "late_responder"})
msg = await websocket_client.receive_json()
assert msg["id"] == 2
assert msg["type"] == "result"
assert len(subscriptions) == 2
assert await websocket_client.close()
await hass.async_block_till_done()
assert len(subscriptions) == 0
assert "Tried to send message" in caplog.text
assert "on closed connection" in caplog.text
async def test_ensure_disconnect_invalid_json(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test we get disconnected when sending invalid JSON."""
await websocket_client.send_json({"id": 1, "type": "ping"})
msg = await websocket_client.receive_json()
assert msg["id"] == 1
assert msg["type"] == "pong"
await websocket_client.send_str("[--INVALID-JSON--]")
msg = await websocket_client.receive()
assert msg.type == WSMsgType.CLOSE
async def test_ensure_disconnect_invalid_binary(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test we get disconnected when sending invalid bytes."""
await websocket_client.send_json({"id": 1, "type": "ping"})
msg = await websocket_client.receive_json()
assert msg["id"] == 1
assert msg["type"] == "pong"
await websocket_client.send_bytes(b"")
msg = await websocket_client.receive()
assert msg.type == WSMsgType.CLOSE
async def test_pending_msg_peak(
hass: HomeAssistant,
mock_low_peak,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test pending msg overflow command."""
orig_handler = http.WebSocketHandler
setup_instance: http.WebSocketHandler | None = None
def instantiate_handler(*args):
nonlocal setup_instance
setup_instance = orig_handler(*args)
return setup_instance
with patch(
"homeassistant.components.websocket_api.http.WebSocketHandler",
instantiate_handler,
):
websocket_client = await hass_ws_client()
instance: http.WebSocketHandler = cast(http.WebSocketHandler, setup_instance)
# Fill the queue past the allowed peak
for _ in range(10):
instance._send_message({"overload": "message"})
async_fire_time_changed(
hass, utcnow() + timedelta(seconds=const.PENDING_MSG_PEAK_TIME + 1)
)
msg = await websocket_client.receive()
assert msg.type is WSMsgType.CLOSE
assert "Client unable to keep up with pending messages" in caplog.text
assert "Stayed over 5 for 5 seconds" in caplog.text
assert "overload" in caplog.text
async def test_pending_msg_peak_recovery(
hass: HomeAssistant,
mock_low_peak,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test pending msg nears the peak but recovers."""
orig_handler = http.WebSocketHandler
setup_instance: http.WebSocketHandler | None = None
def instantiate_handler(*args):
nonlocal setup_instance
setup_instance = orig_handler(*args)
return setup_instance
with patch(
"homeassistant.components.websocket_api.http.WebSocketHandler",
instantiate_handler,
):
websocket_client = await hass_ws_client()
instance: http.WebSocketHandler = cast(http.WebSocketHandler, setup_instance)
# Make sure the call later is started
for _ in range(10):
instance._send_message({})
for _ in range(10):
msg = await websocket_client.receive()
assert msg.type == WSMsgType.TEXT
instance._send_message({})
msg = await websocket_client.receive()
assert msg.type == WSMsgType.TEXT
# Cleanly shutdown
instance._send_message({})
instance._handle_task.cancel()
msg = await websocket_client.receive()
assert msg.type is WSMsgType.CLOSE
assert "Client unable to keep up with pending messages" not in caplog.text
async def test_pending_msg_peak_but_does_not_overflow(
hass: HomeAssistant,
mock_low_peak,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test pending msg hits the low peak but recovers and does not overflow."""
orig_handler = http.WebSocketHandler
setup_instance: http.WebSocketHandler | None = None
def instantiate_handler(*args):
nonlocal setup_instance
setup_instance = orig_handler(*args)
return setup_instance
with patch(
"homeassistant.components.websocket_api.http.WebSocketHandler",
instantiate_handler,
):
websocket_client = await hass_ws_client()
instance: http.WebSocketHandler = cast(http.WebSocketHandler, setup_instance)
# Kill writer task and fill queue past peak
for _ in range(5):
instance._message_queue.append(None)
# Trigger the peak check
instance._send_message({})
# Clear the queue
instance._message_queue.clear()
# Trigger the peak clear
instance._send_message({})
async_fire_time_changed(
hass, utcnow() + timedelta(seconds=const.PENDING_MSG_PEAK_TIME + 1)
)
msg = await websocket_client.receive()
assert msg.type == WSMsgType.TEXT
assert "Client unable to keep up with pending messages" not in caplog.text
async def test_non_json_message(
hass: HomeAssistant, websocket_client, caplog: pytest.LogCaptureFixture
) -> None:
"""Test trying to serialize non JSON objects."""
bad_data = object()
hass.states.async_set("test_domain.entity", "testing", {"bad": bad_data})
await websocket_client.send_json({"id": 5, "type": "get_states"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == []
assert "Unable to serialize to JSON. Bad data found" in caplog.text
assert "State: test_domain.entity" in caplog.text
assert "bad=<object" in caplog.text
async def test_prepare_fail_timeout(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test failing to prepare due to timeout."""
with (
patch(
"homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
side_effect=(TimeoutError, web.WebSocketResponse.prepare),
),
pytest.raises(ServerDisconnectedError),
):
await hass_ws_client(hass)
assert "Timeout preparing request" in caplog.text
async def test_prepare_fail_connection_reset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test failing to prepare due to connection reset."""
with (
patch(
"homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
side_effect=(ConnectionResetError, web.WebSocketResponse.prepare),
),
pytest.raises(ServerDisconnectedError),
):
await hass_ws_client(hass)
assert "Connection reset by peer while preparing WebSocket" in caplog.text
async def test_enable_coalesce(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test enabling coalesce."""
websocket_client = await hass_ws_client(hass)
await websocket_client.send_json(
{
"id": 1,
"type": "supported_features",
"features": {const.FEATURE_COALESCE_MESSAGES: 1},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 1
assert msg["success"] is True
send_tasks: list[asyncio.Future] = []
ids: set[int] = set()
start_id = 2
for idx in range(10):
id_ = idx + start_id
ids.add(id_)
send_tasks.append(websocket_client.send_json({"id": id_, "type": "ping"}))
await asyncio.gather(*send_tasks)
returned_ids: set[int] = set()
for _ in range(10):
msg = await websocket_client.receive_json()
assert msg["type"] == "pong"
returned_ids.add(msg["id"])
assert ids == returned_ids
# Now close
send_tasks_with_close: list[asyncio.Future] = []
start_id = 12
for idx in range(10):
id_ = idx + start_id
send_tasks_with_close.append(
websocket_client.send_json({"id": id_, "type": "ping"})
)
send_tasks_with_close.append(websocket_client.close())
send_tasks_with_close.append(websocket_client.send_json({"id": 50, "type": "ping"}))
with pytest.raises(ConnectionResetError):
await asyncio.gather(*send_tasks_with_close)
async def test_binary_message(
hass: HomeAssistant, websocket_client, caplog: pytest.LogCaptureFixture
) -> None:
"""Test binary messages."""
binary_payloads = {
104: ([], asyncio.Future()),
105: ([], asyncio.Future()),
}
# Register a handler
@callback
@websocket_command(
{
"type": "get_binary_message_handler",
}
)
def get_binary_message_handler(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
):
unsub = None
@callback
def binary_message_handler(
hass: HomeAssistant, connection: ActiveConnection, payload: bytes
):
nonlocal unsub
if msg["id"] == 103:
raise ValueError("Boom")
if payload:
binary_payloads[msg["id"]][0].append(payload)
else:
binary_payloads[msg["id"]][1].set_result(
b"".join(binary_payloads[msg["id"]][0])
)
unsub()
prefix, unsub = connection.async_register_binary_handler(binary_message_handler)
connection.send_result(msg["id"], {"prefix": prefix})
async_register_command(hass, get_binary_message_handler)
# Register multiple binary handlers
for i in range(101, 106):
await websocket_client.send_json(
{"id": i, "type": "get_binary_message_handler"}
)
result = await websocket_client.receive_json()
assert result["id"] == i
assert result["type"] == const.TYPE_RESULT
assert result["success"]
assert result["result"]["prefix"] == i - 100
# Send message to binary
await websocket_client.send_bytes((0).to_bytes(1, "big") + b"test0")
await websocket_client.send_bytes((3).to_bytes(1, "big") + b"test3")
await websocket_client.send_bytes((3).to_bytes(1, "big") + b"test3")
await websocket_client.send_bytes((10).to_bytes(1, "big") + b"test10")
await websocket_client.send_bytes((4).to_bytes(1, "big") + b"test4")
await websocket_client.send_bytes((4).to_bytes(1, "big") + b"")
await websocket_client.send_bytes((5).to_bytes(1, "big") + b"test5")
await websocket_client.send_bytes((5).to_bytes(1, "big") + b"test5-2")
await websocket_client.send_bytes((5).to_bytes(1, "big") + b"")
# Verify received
assert await binary_payloads[104][1] == b"test4"
assert await binary_payloads[105][1] == b"test5test5-2"
assert "Error handling binary message" in caplog.text
assert "Received binary message for non-existing handler 0" in caplog.text
assert "Received binary message for non-existing handler 3" in caplog.text
assert "Received binary message for non-existing handler 10" in caplog.text

View File

@@ -0,0 +1,91 @@
"""Tests for the Home Assistant Websocket API."""
from unittest.mock import Mock, patch
from aiohttp import WSMsgType
import voluptuous as vol
from homeassistant.components.websocket_api import (
async_register_command,
const,
messages,
)
from homeassistant.core import HomeAssistant
async def test_invalid_message_format(websocket_client) -> None:
"""Test sending invalid JSON."""
await websocket_client.send_json({"type": 5})
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
error = msg["error"]
assert error["code"] == const.ERR_INVALID_FORMAT
assert error["message"].startswith("Message incorrectly formatted")
async def test_invalid_json(websocket_client) -> None:
"""Test sending invalid JSON."""
await websocket_client.send_str("this is not JSON")
msg = await websocket_client.receive()
assert msg.type == WSMsgType.close
async def test_quiting_hass(hass: HomeAssistant, websocket_client) -> None:
"""Test sending invalid JSON."""
with patch.object(hass.loop, "stop"):
await hass.async_stop()
msg = await websocket_client.receive()
assert msg.type is WSMsgType.CLOSE
async def test_unknown_command(websocket_client) -> None:
"""Test get_panels command."""
await websocket_client.send_json({"id": 5, "type": "unknown_command"})
msg = await websocket_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNKNOWN_COMMAND
async def test_handler_failing(hass: HomeAssistant, websocket_client) -> None:
"""Test a command that raises."""
async_register_command(
hass,
"bla",
Mock(side_effect=TypeError),
messages.BASE_COMMAND_MESSAGE_SCHEMA.extend({"type": "bla"}),
)
await websocket_client.send_json({"id": 5, "type": "bla"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNKNOWN_ERROR
async def test_invalid_vol(hass: HomeAssistant, websocket_client) -> None:
"""Test a command that raises invalid vol error."""
async_register_command(
hass,
"bla",
Mock(side_effect=TypeError),
messages.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{"type": "bla", vol.Required("test_config"): str}
),
)
await websocket_client.send_json({"id": 5, "type": "bla", "test_config": 5})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
assert "expected str for dictionary value" in msg["error"]["message"]

View File

@@ -0,0 +1,301 @@
"""Test Websocket API messages module."""
import pytest
from homeassistant.components.websocket_api.messages import (
_partial_cached_event_message as lru_event_cache,
_state_diff_event,
cached_event_message,
message_to_json_bytes,
)
from homeassistant.const import EVENT_STATE_CHANGED
from homeassistant.core import Context, Event, HomeAssistant, State, callback
from tests.common import async_capture_events
async def test_cached_event_message(hass: HomeAssistant) -> None:
"""Test that we cache event messages."""
events = []
@callback
def _event_listener(event):
events.append(event)
hass.bus.async_listen(EVENT_STATE_CHANGED, _event_listener)
hass.states.async_set("light.window", "on")
hass.states.async_set("light.window", "off")
await hass.async_block_till_done()
assert len(events) == 2
lru_event_cache.cache_clear()
msg0 = cached_event_message(b"2", events[0])
assert msg0 == cached_event_message(b"2", events[0])
msg1 = cached_event_message(b"2", events[1])
assert msg1 == cached_event_message(b"2", events[1])
assert msg0 != msg1
cache_info = lru_event_cache.cache_info()
assert cache_info.hits == 2
assert cache_info.misses == 2
assert cache_info.currsize == 2
cached_event_message(b"2", events[1])
cache_info = lru_event_cache.cache_info()
assert cache_info.hits == 3
assert cache_info.misses == 2
assert cache_info.currsize == 2
async def test_cached_event_message_with_different_idens(hass: HomeAssistant) -> None:
"""Test that we cache event messages when the subscrition idens differ."""
events = []
@callback
def _event_listener(event):
events.append(event)
hass.bus.async_listen(EVENT_STATE_CHANGED, _event_listener)
hass.states.async_set("light.window", "on")
await hass.async_block_till_done()
assert len(events) == 1
lru_event_cache.cache_clear()
msg0 = cached_event_message(b"2", events[0])
msg1 = cached_event_message(b"3", events[0])
msg2 = cached_event_message(b"4", events[0])
assert msg0 != msg1
assert msg0 != msg2
cache_info = lru_event_cache.cache_info()
assert cache_info.hits == 2
assert cache_info.misses == 1
assert cache_info.currsize == 1
async def test_state_diff_event(hass: HomeAssistant) -> None:
"""Test building state_diff_message."""
state_change_events = async_capture_events(hass, EVENT_STATE_CHANGED)
context = Context(user_id="user-id", parent_id="parent-id", id="id")
hass.states.async_set("light.window", "on", context=context)
hass.states.async_set("light.window", "off", context=context)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {"+": {"lc": new_state.last_changed_timestamp, "s": "off"}}
}
}
hass.states.async_set(
"light.window",
"red",
context=Context(user_id="user-id", parent_id="new-parent-id", id="id"),
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"c": {"parent_id": "new-parent-id"},
"lc": new_state.last_changed_timestamp,
"s": "red",
}
}
}
}
hass.states.async_set(
"light.window",
"green",
context=Context(
user_id="new-user-id", parent_id="another-new-parent-id", id="id"
),
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"c": {
"parent_id": "another-new-parent-id",
"user_id": "new-user-id",
},
"lc": new_state.last_changed_timestamp,
"s": "green",
}
}
}
}
hass.states.async_set(
"light.window",
"blue",
context=Context(
user_id="another-new-user-id", parent_id="another-new-parent-id", id="id"
),
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"c": {"user_id": "another-new-user-id"},
"lc": new_state.last_changed_timestamp,
"s": "blue",
}
}
}
}
hass.states.async_set(
"light.window",
"yellow",
context=Context(
user_id="another-new-user-id",
parent_id="another-new-parent-id",
id="id-new",
),
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"c": "id-new",
"lc": new_state.last_changed_timestamp,
"s": "yellow",
}
}
}
}
new_context = Context()
hass.states.async_set(
"light.window", "purple", {"new": "attr"}, context=new_context
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"a": {"new": "attr"},
"c": {"id": new_context.id, "parent_id": None, "user_id": None},
"lc": new_state.last_changed_timestamp,
"s": "purple",
}
}
}
}
hass.states.async_set("light.window", "green", {}, context=new_context)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {"lc": new_state.last_changed_timestamp, "s": "green"},
"-": {"a": ["new"]},
}
}
}
hass.states.async_set(
"light.window",
"green",
{"list_attr": ["a", "b", "c", "d"], "list_attr_2": ["a", "b"]},
context=new_context,
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"a": {"list_attr": ["a", "b", "c", "d"], "list_attr_2": ["a", "b"]},
"lu": new_state.last_updated_timestamp,
}
}
}
}
hass.states.async_set(
"light.window",
"green",
{"list_attr": ["a", "b", "c", "e"]},
context=new_context,
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"a": {"list_attr": ["a", "b", "c", "e"]},
"lu": new_state.last_updated_timestamp,
},
"-": {"a": ["list_attr_2"]},
}
}
}
async def test_message_to_json_bytes(caplog: pytest.LogCaptureFixture) -> None:
"""Test we can serialize websocket messages."""
json_str = message_to_json_bytes({"id": 1, "message": "xyz"})
assert json_str == b'{"id":1,"message":"xyz"}'
json_str2 = message_to_json_bytes({"id": 1, "message": _Unserializeable()})
assert (
json_str2
== b'{"id":1,"type":"result","success":false,"error":{"code":"unknown_error","message":"Invalid JSON in response"}}'
)
assert "Unable to serialize to JSON" in caplog.text
class _Unserializeable:
"""A class that cannot be serialized."""

View File

@@ -0,0 +1,47 @@
"""Test cases for the API stream sensor."""
from homeassistant.auth.providers.homeassistant import HassAuthProvider
from homeassistant.components.websocket_api.auth import TYPE_AUTH_REQUIRED
from homeassistant.components.websocket_api.http import URL
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from .test_auth import test_auth_active_with_token
from tests.typing import ClientSessionGenerator
async def test_websocket_api(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
hass_access_token: str,
local_auth: HassAuthProvider,
) -> None:
"""Test API streams."""
await async_setup_component(
hass, "sensor", {"sensor": {"platform": "websocket_api"}}
)
await hass.async_block_till_done()
client = await hass_client_no_auth()
ws = await client.ws_connect(URL)
auth_ok = await ws.receive_json()
assert auth_ok["type"] == TYPE_AUTH_REQUIRED
ws.client = client
state = hass.states.get("sensor.connected_clients")
assert state.state == "0"
await test_auth_active_with_token(hass, ws, hass_access_token)
state = hass.states.get("sensor.connected_clients")
assert state.state == "1"
await ws.close()
await hass.async_block_till_done()
state = hass.states.get("sensor.connected_clients")
assert state.state == "0"