Fix KeyError in energy websocket (#143519)

This commit is contained in:
Abílio Costa 2025-04-23 17:34:48 +01:00 committed by GitHub
parent 8df0a950f7
commit 738e39413d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 58 additions and 2 deletions

View File

@ -293,9 +293,9 @@ async def ws_get_fossil_energy_consumption(
if statistics_id not in statistic_ids:
continue
for period in stat:
if period["change"] is None:
if (change := period.get("change")) is None:
continue
result[period["start"]] += period["change"]
result[period["start"]] += change
return {key: result[key] for key in sorted(result)}

View File

@ -1165,3 +1165,59 @@ async def test_fossil_energy_consumption_check_missing_hour(
hour3.isoformat(),
hour4.isoformat(),
]
@pytest.mark.freeze_time("2021-08-01 00:00:00+00:00")
async def test_fossil_energy_consumption_missing_sum(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test fossil_energy_consumption statistics missing sum."""
now = dt_util.utcnow()
later = dt_util.as_utc(dt_util.parse_datetime("2022-09-01 00:00:00"))
await async_setup_component(hass, "history", {})
await async_setup_component(hass, "sensor", {})
await async_recorder_block_till_done(hass)
period1 = dt_util.as_utc(dt_util.parse_datetime("2021-09-01 00:00:00"))
period2 = dt_util.as_utc(dt_util.parse_datetime("2021-09-30 23:00:00"))
period3 = dt_util.as_utc(dt_util.parse_datetime("2021-10-01 00:00:00"))
period4 = dt_util.as_utc(dt_util.parse_datetime("2021-10-31 23:00:00"))
external_energy_statistics_1 = (
{"start": period1, "last_reset": None, "state": 0, "mean": 2},
{"start": period2, "last_reset": None, "state": 1, "mean": 3},
{"start": period3, "last_reset": None, "state": 2, "mean": 4},
{"start": period4, "last_reset": None, "state": 3, "mean": 5},
)
external_energy_metadata_1 = {
"has_mean": True,
"has_sum": False,
"name": "Mean imported energy",
"source": "test",
"statistic_id": "test:mean_energy_import_tariff",
"unit_of_measurement": "kWh",
}
async_add_external_statistics(
hass, external_energy_metadata_1, external_energy_statistics_1
)
await async_wait_recording_done(hass)
client = await hass_ws_client()
await client.send_json(
{
"id": 1,
"type": "energy/fossil_energy_consumption",
"start_time": now.isoformat(),
"end_time": later.isoformat(),
"energy_statistic_ids": [
"test:mean_energy_import_tariff",
],
"co2_statistic_id": "",
"period": "hour",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {}