Skip to content

Commit

Permalink
Fix correct conversion to template for fixed config entries
Browse files Browse the repository at this point in the history
  • Loading branch information
bramstroker committed Jul 29, 2022
1 parent 10e9b32 commit 985c62d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
2 changes: 1 addition & 1 deletion custom_components/powercalc/sensor.py
Expand Up @@ -317,7 +317,7 @@ def convert_config_entry_to_sensor_config(config_entry: ConfigEntry) -> dict[str
if CONF_FIXED in sensor_config:
fixed_config = copy.copy(sensor_config.get(CONF_FIXED))
if CONF_POWER_TEMPLATE in fixed_config:
fixed_config[CONF_POWER] = fixed_config[CONF_POWER_TEMPLATE]
fixed_config[CONF_POWER] = Template(fixed_config[CONF_POWER_TEMPLATE])
del fixed_config[CONF_POWER_TEMPLATE]
sensor_config[CONF_FIXED] = fixed_config

Expand Down
44 changes: 43 additions & 1 deletion tests/strategy/test_fixed.py
@@ -1,15 +1,29 @@
import pytest
from homeassistant.components import input_number
from homeassistant.const import STATE_ON
from homeassistant.const import STATE_ON, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.event import TrackTemplate
from homeassistant.helpers.template import Template
from homeassistant.setup import async_setup_component

from custom_components.powercalc.const import (
CONF_FIXED,
CONF_SENSOR_TYPE,
DOMAIN,
CONF_POWER,
CONF_POWER_TEMPLATE,
SensorType
)
from custom_components.powercalc.errors import StrategyConfigurationError
from custom_components.powercalc.strategy.fixed import FixedStrategy

from pytest_homeassistant_custom_component.common import MockConfigEntry

from .common import create_source_entity
from ..common import (
create_input_number,
create_input_boolean
)


async def test_simple_power():
Expand Down Expand Up @@ -134,3 +148,31 @@ async def test_validation_error_state_power_only_entity_domain():
source_entity=create_source_entity("climate"),
)
await strategy.validate_config()

async def test_config_entry_with_template_rendered_correctly(hass: HomeAssistant):
await create_input_boolean(hass, "test")
await create_input_number(hass, "test", 30)

template = "{{states('input_number.test')|float}}"
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_SENSOR_TYPE: SensorType.VIRTUAL_POWER,
CONF_ENTITY_ID: "input_boolean.test",
CONF_FIXED: {
CONF_POWER: template,
CONF_POWER_TEMPLATE: template,
}
},
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

hass.states.async_set("input_boolean.test", STATE_ON)
hass.states.async_set("input_number.test", 40)
await hass.async_block_till_done()

state = hass.states.get("sensor.test_power")
assert state
assert state.state == "40.00"

0 comments on commit 985c62d

Please sign in to comment.