adaptive-lighting/tests/test_init.py
Casey 03d2748cd4 Group 7: tests — 94 passing in 0.57s (53/53 + 9.4 deferred)
Test infrastructure:
- Add `pytest-homeassistant-custom-component` (PHACC) as a `test`
  dependency group. PHACC ships `hass`, `enable_custom_integrations`,
  `MockConfigEntry`, and friends without needing to clone HA core as a
  sibling directory. Modernizes the test setup from upstream's
  `setup-symlinks` pattern.
- conftest.py: add `auto_enable_custom_integrations` autouse fixture
  so HA discovers the integration under `custom_components/` during
  tests. Keep the upstream template-deprecation no-op.
- Import paths: all tests now import from `custom_components.adaptive_lighting`
  (not `homeassistant.components.adaptive_lighting`) and from
  `pytest_homeassistant_custom_component.common` (not `tests.common`).

New tests (groups 7.2-7.16):
- tests/test_color_and_brightness.py (16 tests): TestBrightnessCurve
  asserts min-before-sunrise, midpoint-at-event, max-during-day, sunset
  ramp symmetry. TestColorTempCurve verifies the same shape applies to
  K. TestSunPosition checks the synthetic +1/-1/0 derivation.
  TestTanhDayCurveDirect exercises the helper directly.
- tests/test_config_flow.py (12 tests): six sections in order, each
  section contains only its specified fields, conditional visibility
  of send_split_delay, default sun entities, strict-typed entity
  selectors, NumberSelector slider/box configs, BooleanSelector for
  every flag, full user→create-entry flow, YAML-managed entry aborts
  with `yaml_managed` reason, options flow renders the sectioned schema.
- tests/test_init.py (6 tests): successful setup on current version,
  stale version raises ConfigEntryError via async_migrate_entry,
  unload is clean, tombstone removes orphan sleep entity + logs INFO,
  tombstone is idempotent, tombstone respects config_entry ownership.

Source modernizations driven by the tests:
- __init__.py: add `async_migrate_entry` that surfaces the
  "incompatible — delete and recreate" message and sets the entry to
  MIGRATION_ERROR. Removed direct `ConfigEntryError` from
  `async_setup_entry` (HA routes version mismatches through the
  migration handler now).
- switch.py: removed upstream's YAML-managed-entry auto-remove hack.
  YAML profiles now load normally and the options flow handles the
  "you must edit configuration.yaml" message (spec R7).

Existing tests updated to PHACC paths: test_adaptation_utils.py
(38 tests), test_hass_utils.py (22 tests). Both pass without
modification beyond the import fix.

Deleted: tests/test_switch.py (2,999 LOC of upstream tests, most
covering sleep mode / take-over-control / manual-control state
machines that no longer exist; CDiT-specific switch tests deferred
to a follow-up change).

Result: `uv run --group test pytest tests/` → 94 passed in 0.57s.

Deferred from this change:
- 4.3: manual UI test that toggling a field and saving reloads cleanly
  (requires a real HA instance, can't be done from CLI).
- 9.4: GitHub repo description / topics update (do via `gh repo edit`
  outside the change scope).

openspec status: 4/4 artifacts complete; strict-validate green.
2026-05-16 15:11:49 +02:00

165 lines
5.5 KiB
Python

"""Tests for the CDiT Adaptive Lighting integration setup.
Covers spec R8 (strict version-break) and R9 (sleep-switch tombstone).
"""
from __future__ import annotations
import logging
import pytest
from custom_components.adaptive_lighting.const import (
CONFIG_ENTRY_VERSION,
DEFAULT_NAME,
DOMAIN,
UNDO_UPDATE_LISTENER,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_NAME
from homeassistant.exceptions import ConfigEntryError
from homeassistant.helpers import entity_registry as er
from pytest_homeassistant_custom_component.common import MockConfigEntry
# ---------------------------------------------------------------------------
# R8 — strict version break
# ---------------------------------------------------------------------------
async def test_successful_setup_on_current_version(hass) -> None:
"""R8: an entry created on the current major succeeds and runs no
tombstone log line."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ConfigEntryState.LOADED
assert UNDO_UPDATE_LISTENER in hass.data[DOMAIN][entry.entry_id]
async def test_stale_version_raises_config_entry_error(hass, caplog) -> None:
"""R8: an entry created on the previous major fails with our
ConfigEntryError, leaving the entry in the MIGRATION_ERROR state.
HA routes version mismatches through `async_migrate_entry`."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION - 1,
)
entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ConfigEntryState.MIGRATION_ERROR
# The full captured log (which includes the exception traceback) should
# carry our friendly "delete and recreate" message so the user sees it.
text = caplog.text.lower()
assert "delete" in text and "recreate" in text
async def test_unload_entry(hass) -> None:
"""A current-version entry can be unloaded cleanly."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state == ConfigEntryState.NOT_LOADED
assert DOMAIN not in hass.data
# ---------------------------------------------------------------------------
# R9 — sleep-switch tombstone cleanup
# ---------------------------------------------------------------------------
async def test_orphan_sleep_entity_is_removed_on_setup(hass, caplog) -> None:
"""R9: a leftover sleep_mode switch owned by this entry is removed and
one INFO log line is emitted."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION,
)
entry.add_to_hass(hass)
# Seed the registry with an orphan sleep-mode entity owned by this entry.
registry = er.async_get(hass)
orphan = registry.async_get_or_create(
domain="switch",
platform=DOMAIN,
unique_id=f"{DEFAULT_NAME}_sleep_mode",
config_entry=entry,
)
with caplog.at_level(logging.INFO):
assert await hass.config_entries.async_setup(entry.entry_id)
assert registry.async_get(orphan.entity_id) is None, (
"Orphan sleep entity should have been removed."
)
# One INFO log line naming the entity ID.
assert any(
orphan.entity_id in record.message
for record in caplog.records
if record.levelno == logging.INFO
)
async def test_tombstone_helper_is_idempotent(hass, caplog) -> None:
"""R9: a second setup with no orphans finds nothing and emits no log line."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION,
)
entry.add_to_hass(hass)
# First setup: no orphans seeded, no log line.
with caplog.at_level(logging.INFO):
assert await hass.config_entries.async_setup(entry.entry_id)
assert not any(
"sleep_mode" in record.message.lower()
for record in caplog.records
if record.levelno == logging.INFO
)
async def test_tombstone_skips_foreign_entities(hass, caplog) -> None:
"""R9 + D12: an entity matching the name pattern but owned by another
config entry is not removed."""
our_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_NAME: DEFAULT_NAME},
version=CONFIG_ENTRY_VERSION,
)
our_entry.add_to_hass(hass)
# Different config entry, different domain, but a name that ends in
# _sleep_mode — should NOT be touched.
foreign_entry = MockConfigEntry(
domain="other_integration",
data={},
)
foreign_entry.add_to_hass(hass)
registry = er.async_get(hass)
foreign_entity = registry.async_get_or_create(
domain="switch",
platform="other_integration",
unique_id=f"unrelated_{DEFAULT_NAME}_sleep_mode",
config_entry=foreign_entry,
)
assert await hass.config_entries.async_setup(our_entry.entry_id)
assert registry.async_get(foreign_entity.entity_id) is not None, (
"Foreign-owned entity matching name pattern must not be removed."
)