From 2bfb09cb117ece3f9cc9f71b8134dbee76fc61c3 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Mon, 23 Jun 2025 13:29:29 +0200 Subject: [PATCH] Improve test of WS command get_services cache handling (#147134) --- .../components/websocket_api/test_commands.py | 44 ++++++++++++++++--- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/tests/components/websocket_api/test_commands.py b/tests/components/websocket_api/test_commands.py index 2c9cc19c84b..6e4fa34ed26 100644 --- a/tests/components/websocket_api/test_commands.py +++ b/tests/components/websocket_api/test_commands.py @@ -17,6 +17,9 @@ from homeassistant.components.websocket_api.auth import ( TYPE_AUTH_OK, TYPE_AUTH_REQUIRED, ) +from homeassistant.components.websocket_api.commands import ( + ALL_SERVICE_DESCRIPTIONS_JSON_CACHE, +) from homeassistant.components.websocket_api.const import FEATURE_COALESCE_MESSAGES, URL from homeassistant.config_entries import ConfigEntryState from homeassistant.const import SIGNAL_BOOTSTRAP_INTEGRATIONS @@ -667,14 +670,41 @@ async def test_get_services( hass: HomeAssistant, websocket_client: MockHAClientWebSocket ) -> None: """Test get_services command.""" - for id_ in (5, 6): - await websocket_client.send_json({"id": id_, "type": "get_services"}) + assert ALL_SERVICE_DESCRIPTIONS_JSON_CACHE not in hass.data + await websocket_client.send_json_auto_id({"type": "get_services"}) + msg = await websocket_client.receive_json() + assert msg == {"id": 1, "result": {}, "success": True, "type": "result"} - msg = await websocket_client.receive_json() - assert msg["id"] == id_ - assert msg["type"] == const.TYPE_RESULT - assert msg["success"] - assert msg["result"].keys() == hass.services.async_services().keys() + # Check cache is reused + old_cache = hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] + await websocket_client.send_json_auto_id({"type": "get_services"}) + msg = await websocket_client.receive_json() + assert msg == {"id": 2, "result": {}, "success": True, "type": "result"} + assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is old_cache + + # Load a service and check cache is updated + assert await async_setup_component(hass, "logger", {}) + await websocket_client.send_json_auto_id({"type": "get_services"}) + msg = await websocket_client.receive_json() + assert msg == { + "id": 3, + "result": {"logger": {"set_default_level": ANY, "set_level": ANY}}, + "success": True, + "type": "result", + } + assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is not old_cache + + # Check cache is reused + old_cache = hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] + await websocket_client.send_json_auto_id({"type": "get_services"}) + msg = await websocket_client.receive_json() + assert msg == { + "id": 4, + "result": {"logger": {"set_default_level": ANY, "set_level": ANY}}, + "success": True, + "type": "result", + } + assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is old_cache async def test_get_config(