From b9a3863645037844cee93e37dd81f2342ae12e0c Mon Sep 17 00:00:00 2001 From: Jan-Philipp Benecke Date: Mon, 25 Sep 2023 21:21:01 +0200 Subject: [PATCH] Handle json decode exception in co2signal (#100857) * Handle json decode exception in co2signal * Update homeassistant/components/co2signal/coordinator.py Co-authored-by: Joost Lekkerkerker * Fix import --------- Co-authored-by: Joost Lekkerkerker --- .../components/co2signal/coordinator.py | 5 ++++ .../components/co2signal/test_config_flow.py | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/homeassistant/components/co2signal/coordinator.py b/homeassistant/components/co2signal/coordinator.py index dfb78326abe..c210d989c04 100644 --- a/homeassistant/components/co2signal/coordinator.py +++ b/homeassistant/components/co2signal/coordinator.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Mapping from datetime import timedelta +from json import JSONDecodeError import logging from typing import Any, cast @@ -68,6 +69,10 @@ def get_data(hass: HomeAssistant, config: Mapping[str, Any]) -> CO2SignalRespons wait=False, ) + except JSONDecodeError as err: + # raise occasional occurring json decoding errors as CO2Error so the data update coordinator retries it + raise CO2Error from err + except ValueError as err: err_str = str(err) diff --git a/tests/components/co2signal/test_config_flow.py b/tests/components/co2signal/test_config_flow.py index ddd2049800a..8f5c4cfd55c 100644 --- a/tests/components/co2signal/test_config_flow.py +++ b/tests/components/co2signal/test_config_flow.py @@ -1,4 +1,5 @@ """Test the CO2 Signal config flow.""" +from json import JSONDecodeError from unittest.mock import patch import pytest @@ -160,6 +161,28 @@ async def test_form_error_handling(hass: HomeAssistant, err_str, err_code) -> No assert result2["errors"] == {"base": err_code} +async def test_form_invalid_json(hass: HomeAssistant) -> None: + """Test we handle invalid json.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with patch( + "CO2Signal.get_latest", + side_effect=JSONDecodeError(msg="boom", doc="", pos=1), + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "location": config_flow.TYPE_USE_HOME, + "api_key": "api_key", + }, + ) + + assert result2["type"] == FlowResultType.FORM + assert result2["errors"] == {"base": "unknown"} + + async def test_form_error_unexpected_error(hass: HomeAssistant) -> None: """Test we handle unexpected error.""" result = await hass.config_entries.flow.async_init(