Handle json decode exception in co2signal (#100857)

* Handle json decode exception in co2signal

* Update homeassistant/components/co2signal/coordinator.py

Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>

* Fix import

---------

Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
Jan-Philipp Benecke 2023-09-25 21:21:01 +02:00 committed by GitHub
parent ea1108503d
commit b9a3863645
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 0 deletions

View file

@ -3,6 +3,7 @@ from __future__ import annotations
from collections.abc import Mapping from collections.abc import Mapping
from datetime import timedelta from datetime import timedelta
from json import JSONDecodeError
import logging import logging
from typing import Any, cast from typing import Any, cast
@ -68,6 +69,10 @@ def get_data(hass: HomeAssistant, config: Mapping[str, Any]) -> CO2SignalRespons
wait=False, 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: except ValueError as err:
err_str = str(err) err_str = str(err)

View file

@ -1,4 +1,5 @@
"""Test the CO2 Signal config flow.""" """Test the CO2 Signal config flow."""
from json import JSONDecodeError
from unittest.mock import patch from unittest.mock import patch
import pytest 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} 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: async def test_form_error_unexpected_error(hass: HomeAssistant) -> None:
"""Test we handle unexpected error.""" """Test we handle unexpected error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(