Initialize energy_state without price (#97031)

Co-authored-by: Erik <erik@montnemery.com>
This commit is contained in:
Excentyl 2023-12-08 16:46:08 +00:00 committed by GitHub
parent 1c7bd3f729
commit 46d626280e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 6 deletions

View file

@ -317,6 +317,11 @@ class EnergyCostSensor(SensorEntity):
try:
energy_price = float(energy_price_state.state)
except ValueError:
if self._last_energy_sensor_state is None:
# Initialize as it's the first time all required entities except
# price are in place. This means that the cost will update the first
# time the energy is updated after the price entity is in place.
self._reset(energy_state)
return
energy_price_unit: str | None = energy_price_state.attributes.get(

View file

@ -924,7 +924,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await setup_integration(hass)
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "unknown"
assert state.state == "0.0"
# Energy use bumped by 10 kWh, price sensor still not yet available
hass.states.async_set(
@ -935,7 +935,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "unknown"
assert state.state == "0.0"
# Energy use bumped by 10 kWh, price sensor now available
hass.states.async_set("sensor.energy_price", "1", price_attributes)
@ -947,7 +947,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "0.0"
assert state.state == "20.0"
# Energy use bumped by 10 kWh, price sensor available
hass.states.async_set(
@ -958,7 +958,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "10.0"
assert state.state == "30.0"
# Energy use bumped by 10 kWh, price sensor no longer available
hass.states.async_set("sensor.energy_price", "unknown", price_attributes)
@ -970,7 +970,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "10.0"
assert state.state == "30.0"
# Energy use bumped by 10 kWh, price sensor again available
hass.states.async_set("sensor.energy_price", "2", price_attributes)
@ -982,7 +982,7 @@ async def test_cost_sensor_handle_late_price_sensor(
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == "50.0"
assert state.state == "70.0"
@pytest.mark.parametrize(