1 parent
cea79b6b48
commit
c771bc360a
12 files changed
+378
-4
No files matched your search
@@ -0,0 +1,40 @@
|
||||
"""Real Home Assistant fixtures, isolated from the offline boundary doubles."""
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from homeassistant.core import ServiceRegistry
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def custom_integrations(enable_custom_integrations):
|
||||
"""Let HA discover custom_components/heating_mpc in this checkout."""
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_actuator_calls():
|
||||
"""Reject every HA service call during all tested observer lifecycle paths."""
|
||||
with patch.object(ServiceRegistry, "async_call", side_effect=AssertionError(
|
||||
"The shadow integration must never call HA services"
|
||||
)) as calls:
|
||||
yield calls
|
||||
calls.assert_not_called()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def entry():
|
||||
return MockConfigEntry(
|
||||
domain="heating_mpc", version=2, unique_id="home_heating",
|
||||
data={"climate_entity": "climate.reference", "heater_entity": "switch.boiler",
|
||||
"room_entities": ["sensor.room"],
|
||||
"outside_temperature_sources": ["sensor.outside"],
|
||||
"weights": {"sensor.room": 1.0}, "horizon_minutes": 60},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inputs(hass):
|
||||
hass.states.async_set("sensor.room", "20", {"unit_of_measurement": "°C"})
|
||||
hass.states.async_set("sensor.outside", "5", {"unit_of_measurement": "°C"})
|
||||
hass.states.async_set("switch.boiler", "off")
|
||||
hass.states.async_set("climate.reference", "heat", {"temperature": 22, "preset_mode": "comfort"})
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Validate actual HA form schemas, options and entry migration."""
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.heating_mpc.const import DOMAIN
|
||||
|
||||
|
||||
async def test_config_flow(hass, inputs):
|
||||
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
main = {"climate_entity": "climate.reference", "heater_entity": "switch.boiler",
|
||||
"room_entities": ["sensor.room"]}
|
||||
validated = result["data_schema"](main)
|
||||
assert validated["room_max_age_minutes"] == 30
|
||||
assert validated["weather_max_age_minutes"] == 120
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], validated)
|
||||
assert result["step_id"] == "weather"
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], result["data_schema"]({"outside_temperature_sources": ["sensor.outside"]}))
|
||||
assert result["step_id"] == "weather_extra"
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], result["data_schema"]({}))
|
||||
assert result["step_id"] == "weights"
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {"weight__sensor.room": 2})
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["weights"] == {"sensor.room": 2}
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_options_flow_keeps_settings(hass, entry, inputs):
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
main = result["data_schema"]({"climate_entity": "climate.reference",
|
||||
"heater_entity": "switch.boiler", "room_entities": ["sensor.room"],
|
||||
"room_max_age_minutes": 45})
|
||||
result = await hass.config_entries.options.async_configure(result["flow_id"], main)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"], result["data_schema"]({"outside_temperature_sources": ["sensor.outside"]}))
|
||||
result = await hass.config_entries.options.async_configure(result["flow_id"], result["data_schema"]({}))
|
||||
result = await hass.config_entries.options.async_configure(result["flow_id"], {"weight__sensor.room": 3})
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
await hass.async_block_till_done()
|
||||
assert entry.options["room_max_age_minutes"] == 45
|
||||
assert hass.data[DOMAIN][entry.entry_id].config["room_max_age_minutes"] == 45
|
||||
|
||||
|
||||
async def test_v1_entry_migrates_on_setup(hass, inputs):
|
||||
entry = MockConfigEntry(domain=DOMAIN, version=1, data={
|
||||
"climate_entity": "climate.reference", "heater_entity": "switch.boiler",
|
||||
"room_entities": ["sensor.room"], "outside_entity": "sensor.outside"})
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert entry.version == 2
|
||||
assert entry.data["outside_temperature_sources"] == ["sensor.outside"]
|
||||
assert "outside_entity" not in entry.data
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Run the observer through real HA lifecycle and storage APIs."""
|
||||
from datetime import timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from homeassistant.util import dt as dt_util
|
||||
from pytest_homeassistant_custom_component.common import async_fire_time_changed
|
||||
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.storage import Store
|
||||
|
||||
from custom_components.heating_mpc.const import DOMAIN
|
||||
|
||||
|
||||
async def setup(hass, entry):
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
return hass.data[DOMAIN][entry.entry_id]
|
||||
|
||||
|
||||
async def test_setup_reload_unload(hass, entry, inputs):
|
||||
coordinator = await setup(hass, entry)
|
||||
registry = er.async_get(hass)
|
||||
entities = er.async_entries_for_config_entry(registry, entry.entry_id)
|
||||
assert len(entities) == 5
|
||||
ids = {e.unique_id: e.entity_id for e in entities}
|
||||
assert coordinator.data["status"] == "learning"
|
||||
proposal_id = registry.async_get_entity_id("binary_sensor", DOMAIN, f"{entry.entry_id}_proposal")
|
||||
assert hass.states.get(proposal_id).state == "unavailable"
|
||||
assert await hass.config_entries.async_reload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.data[DOMAIN][entry.entry_id] is not coordinator
|
||||
assert ids == {e.unique_id: e.entity_id for e in er.async_entries_for_config_entry(registry, entry.entry_id)}
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert entry.entry_id not in hass.data[DOMAIN]
|
||||
assert not coordinator._listeners
|
||||
assert coordinator._unsub_refresh is None
|
||||
|
||||
|
||||
async def test_options_reload_removes_only_old_room(hass, entry, inputs):
|
||||
await setup(hass, entry)
|
||||
registry = er.async_get(hass)
|
||||
old = registry.async_get_entity_id("sensor", DOMAIN, f"{entry.entry_id}_sensor.room_predicted_60min")
|
||||
hass.states.async_set("sensor.new", "21", {"unit_of_measurement": "°C"})
|
||||
hass.config_entries.async_update_entry(entry, options={"room_entities": ["sensor.new"]})
|
||||
await hass.async_block_till_done()
|
||||
assert hass.data[DOMAIN][entry.entry_id].rooms == ["sensor.new"]
|
||||
assert registry.async_get(old) is None
|
||||
assert registry.async_get_entity_id("sensor", DOMAIN, f"{entry.entry_id}_sensor.new_predicted_60min")
|
||||
assert len(er.async_entries_for_config_entry(registry, entry.entry_id)) == 5
|
||||
|
||||
|
||||
async def test_storage_restore_and_remove(hass, entry, inputs):
|
||||
coordinator = await setup(hass, entry)
|
||||
model = coordinator.learners["sensor.room"]
|
||||
model.count, model.on_count, model.off_count = 250, 125, 125
|
||||
await coordinator._store.async_save({"schema_version": 2, "heater_entity": "switch.boiler",
|
||||
"learners": {"sensor.room": model.as_dict()}})
|
||||
assert await hass.config_entries.async_reload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
restored = hass.data[DOMAIN][entry.entry_id]
|
||||
assert restored.learners["sensor.room"].count == 250
|
||||
assert restored.data["status"] == "ready"
|
||||
assert await hass.config_entries.async_remove(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert await Store(hass, 1, f"{DOMAIN}.{entry.entry_id}").async_load() is None
|
||||
assert not er.async_entries_for_config_entry(er.async_get(hass), entry.entry_id)
|
||||
|
||||
|
||||
async def test_missing_sensor_manual_off_and_target(hass, entry, inputs):
|
||||
coordinator = await setup(hass, entry)
|
||||
hass.states.async_set("sensor.room", "unavailable")
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.data["status"] == "waiting_for_sensors"
|
||||
hass.states.async_set("sensor.room", "20", {"unit_of_measurement": "°C"})
|
||||
hass.states.async_set("climate.reference", "off", {"temperature": 19, "preset_mode": "away"})
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.data["status"] == "paused"
|
||||
assert coordinator.data["proposal"] is None
|
||||
assert hass.states.get("climate.reference").attributes["preset_mode"] == "away"
|
||||
hass.states.async_set("climate.reference", "heat", {"temperature": 21, "preset_mode": "sleep"})
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.data["target"] == 21
|
||||
assert hass.states.get("switch.boiler").state == "off"
|
||||
|
||||
|
||||
async def test_optimizer_failure_is_unavailable(hass, entry, inputs):
|
||||
coordinator = await setup(hass, entry)
|
||||
model = coordinator.learners["sensor.room"]
|
||||
model.count, model.on_count, model.off_count = 250, 125, 125
|
||||
coordinator._update_counts()
|
||||
with patch("custom_components.heating_mpc.coordinator.optimize", side_effect=RuntimeError("test")):
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.data["status"] == "prediction_error"
|
||||
assert coordinator.data["proposal"] is None
|
||||
|
||||
|
||||
async def test_scheduled_sample_saves_and_unload_stops_polling(hass, entry, inputs, freezer, hass_storage):
|
||||
coordinator = await setup(hass, entry)
|
||||
future = dt_util.utcnow() + timedelta(minutes=5, seconds=1)
|
||||
freezer.move_to(future)
|
||||
async_fire_time_changed(hass, future)
|
||||
await hass.async_block_till_done()
|
||||
assert coordinator.learners["sensor.room"].count == 1
|
||||
payload = hass_storage[f"{DOMAIN}.{entry.entry_id}"]["data"]
|
||||
assert payload["learners"]["sensor.room"]["off_count"] == 1
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
future += timedelta(minutes=5)
|
||||
freezer.move_to(future)
|
||||
async_fire_time_changed(hass, future)
|
||||
await hass.async_block_till_done()
|
||||
assert coordinator.learners["sensor.room"].count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", ["broken", {"learners": []}, {"learners": {"sensor.room": {"theta": []}}}])
|
||||
async def test_corrupt_saved_payload_starts_learning(hass, entry, inputs, hass_storage, payload):
|
||||
hass_storage[f"{DOMAIN}.{entry.entry_id}"] = {"version": 1, "data": payload}
|
||||
coordinator = await setup(hass, entry)
|
||||
assert coordinator.data["status"] == "learning"
|
||||
assert coordinator.data["samples"] == 0
|
||||
|
||||
|
||||
async def test_startup_preserves_manual_off_with_trained_model(hass, entry, inputs, hass_storage):
|
||||
from custom_components.heating_mpc.physics import Learner
|
||||
model = Learner(count=250, on_count=125, off_count=125)
|
||||
hass_storage[f"{DOMAIN}.{entry.entry_id}"] = {"version": 1, "data": {
|
||||
"schema_version": 2, "heater_entity": "switch.boiler",
|
||||
"learners": {"sensor.room": model.as_dict()}}}
|
||||
hass.states.async_set("climate.reference", "off", {"temperature": 19, "preset_mode": "away"})
|
||||
coordinator = await setup(hass, entry)
|
||||
assert coordinator.data["status"] == "paused"
|
||||
assert coordinator.data["proposal"] is None
|
||||
assert hass.states.get("climate.reference").state == "off"
|
||||
assert hass.states.get("climate.reference").attributes["temperature"] == 19
|
||||
|
||||
|
||||
async def test_startup_missing_inputs_then_recovery(hass, entry):
|
||||
coordinator = await setup(hass, entry)
|
||||
assert coordinator.data["status"] == "waiting_for_sensors"
|
||||
hass.states.async_set("sensor.room", "20", {"unit_of_measurement": "°C"})
|
||||
hass.states.async_set("sensor.outside", "5", {"unit_of_measurement": "°C"})
|
||||
hass.states.async_set("switch.boiler", "off")
|
||||
hass.states.async_set("climate.reference", "heat", {"temperature": 22})
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.data["status"] == "learning"
|
||||
assert coordinator.data["samples"] == 0
|
||||
Reference in new issue
Block a user