From 045ba4e1dd9e96fe387d05fef87dbe5ec3f1eeaf Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Thu, 4 Jun 2026 19:31:46 +0200 Subject: [PATCH] API refactor to replace assert (#172862) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- homeassistant/components/api/__init__.py | 8 +++++--- tests/components/api/test_init.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/api/__init__.py b/homeassistant/components/api/__init__.py index 3c97c2078ea..933fca543de 100644 --- a/homeassistant/components/api/__init__.py +++ b/homeassistant/components/api/__init__.py @@ -222,7 +222,7 @@ class APIStatesView(HomeAssistantView): states = ( state.as_dict_json for state in hass.states.async_all() - if entity_perm(state.entity_id, "read") + if entity_perm(state.entity_id, POLICY_READ) ) response = web.Response( body=b"".join((b"[", b",".join(states), b"]")), @@ -294,8 +294,10 @@ class APIEntityStateView(HomeAssistantView): # Read the state back for our response status_code = HTTPStatus.CREATED if is_new_state else HTTPStatus.OK - state = hass.states.get(entity_id) - assert state + if (state := hass.states.get(entity_id)) is None: + return self.json_message( + "Error storing state.", HTTPStatus.INTERNAL_SERVER_ERROR + ) resp = self.json(state.as_dict(), status_code) resp.headers.add("Location", f"/api/states/{entity_id}") diff --git a/tests/components/api/test_init.py b/tests/components/api/test_init.py index 58a227c7657..ddf31392eb5 100644 --- a/tests/components/api/test_init.py +++ b/tests/components/api/test_init.py @@ -124,6 +124,18 @@ async def test_api_state_change_with_bad_state( assert resp.status == HTTPStatus.BAD_REQUEST +async def test_api_state_change_internal_error( + hass: HomeAssistant, mock_api_client: TestClient +) -> None: + """Test 500 is returned when state cannot be read back after being set.""" + with patch.object(ha.StateMachine, "async_set"): + resp = await mock_api_client.post( + "/api/states/test.entity", json={"state": "on"} + ) + assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR + assert await resp.json() == {"message": "Error storing state."} + + async def test_api_state_change_with_bad_data( hass: HomeAssistant, mock_api_client: TestClient ) -> None: