Type air_monitor's particulates and migrate the recorded statistics

Adding a unit to a sensor that recorded long-term statistics without one
is not cosmetic: Home Assistant raises a units_changed repair and then
*suppresses statistics generation* for that entity until a human resolves
it (sensor/recorder.py's compile path hits `continue`). Shipping the PM
device classes on their own would therefore have silently frozen the very
history the labels were meant to describe.

A v2 -> v3 config-entry migration relabels the statistics metadata first.
It rewrites only the metadata row, never the recorded values -- these
readings were always µg/m³ and only the label was missing, so nothing
needs converting, which is why this uses async_update_statistics_metadata
and not change_statistics_unit. It reads entity_ids back off the entity
registry rather than rebuilding them from descriptor keys, since a renamed
entity's statistic_id no longer follows from its key, and it is scoped by
device family: range_hood and airconditioner still declare no unit for
their identically-named sensors, so relabelling theirs would create the
exact mismatch this exists to prevent.

With the migration in place there is no longer a reason to hold the labels
back on air_monitor, so it takes them too. That board is one of the two
whose fixtures pin the grade bands the mapping rests on -- typing the
purifier and not the monitor was an inconsistency, not caution. It still
declines the shared state_class column, unchanged.

Recorder coupling is guarded: after_dependencies pulls it in when
configured, the import is local to the migration, and a setup without it
is a no-op. Freshly created entries mint v3 directly, having no history to
relabel.

Tested at both levels. The unit-level tests patch the recorder and assert
which entities are relabelled with which arguments, covering the renamed
entity, subdevice-prefixed and instanced keys, the near-miss keys
(dustbag_/dustbin_), the skipped families and the recorder-absent path.
Because a mock can only prove the call is made, not that it does what the
migration needs, a second suite drives a real in-memory recorder end to
end: statistics seeded unitless, migration run, metadata confirmed to read
µg/m³ / concentration, recorded means confirmed byte-identical, and the
units_changed issue confirmed present before and absent after.
This commit is contained in:
Marc Billow committed 2026-08-15 01:01:49 +00:00
1 parent 21af5708cb
commit eeece4906c
8 files changed
+469 -30

No files matched your search

+4 -2
View File
@@ -38,7 +38,9 @@ async def test_migration_recovers_serial_from_unique_id(
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 2
# Straight through to the current version: v2 -> v3 is a statistics
# relabel that no-ops for a family without particulate sensors.
assert entry.version == 3
assert entry.data[CONF_SERIAL] == MOCK_SERIAL
@@ -257,7 +259,7 @@ async def test_migration_rejects_a_future_entry_version(hass: HomeAssistant) ->
written by a newer release."""
from custom_components.localthings import async_migrate_entry
entry = MockConfigEntry(domain=DOMAIN, data=LEGACY_ENTRY_DATA, version=3)
entry = MockConfigEntry(domain=DOMAIN, data=LEGACY_ENTRY_DATA, version=4)
entry.add_to_hass(hass)
assert await async_migrate_entry(hass, entry) is False
@@ -0,0 +1,171 @@
"""The v2 -> v3 entry migration that relabels particulate statistics.
Dust/FineDust/SuperFineDust gained a pm10/pm25/pm1 device_class and a
µg/m³ unit (issue #325) after having recorded long-term statistics with no
unit at all. Home Assistant treats that as a unit change it cannot convert
and *suppresses statistics generation* for the entity until a human
resolves the repair, so the metadata is corrected during migration instead.
Only the metadata row is touched, never the recorded values -- the readings
were always µg/m³, so there is nothing to convert.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from homeassistant.const import CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.localthings import async_migrate_entry
from custom_components.localthings.const import CONF_DEVICE_TYPE, DOMAIN
from .conftest import ENTRY_DATA, MOCK_SERIAL
RELABEL = "homeassistant.components.recorder.statistics.async_update_statistics_metadata"
@pytest.fixture(autouse=True)
def _recorder_loaded(hass: HomeAssistant):
"""Most tests here assume a normal install, where after_dependencies has
pulled the recorder in. test_is_a_no_op_without_the_recorder undoes it."""
hass.config.components.add("recorder")
return hass
def _entry(hass: HomeAssistant, device_type: str) -> MockConfigEntry:
entry = MockConfigEntry(
domain=DOMAIN,
data={**ENTRY_DATA, CONF_DEVICE_TYPE: device_type},
unique_id=f"{DOMAIN}_{MOCK_SERIAL}",
version=2,
)
entry.add_to_hass(hass)
return entry
def _add_sensor(hass: HomeAssistant, entry: MockConfigEntry, key: str, **kwargs):
return er.async_get(hass).async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_SERIAL}_{key}",
config_entry=entry,
**kwargs,
)
async def test_relabels_every_particulate_sensor(hass: HomeAssistant) -> None:
entry = _entry(hass, "air_purifier")
expected = {
_add_sensor(hass, entry, key).entity_id for key in ("dust", "fine_dust", "super_fine_dust")
}
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert {call.args[1] for call in relabel.call_args_list} == expected
for call in relabel.call_args_list:
assert call.kwargs["new_unit_of_measurement"] == CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
# µg/m³ has a converter, so the class must be named, not None --
# passing neither is deprecated and breaks in HA Core 2026.11.
assert call.kwargs["new_unit_class"] == "concentration"
assert entry.version == 3
async def test_leaves_other_sensors_on_the_same_device_alone(hass: HomeAssistant) -> None:
"""Odor/CleanLevel/CO2 share the resource but keep the units they had."""
entry = _entry(hass, "air_monitor")
dust = _add_sensor(hass, entry, "dust")
for key in ("odor", "clean_level", "co2", "dustbag_usage", "dustbin_auto_close"):
_add_sensor(hass, entry, key)
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert [call.args[1] for call in relabel.call_args_list] == [dust.entity_id]
async def test_skips_families_that_did_not_gain_the_unit(hass: HomeAssistant) -> None:
"""range_hood and airconditioner still declare no unit for their
identically-named sensors. Relabelling their statistics would assert a
unit those entities don't report -- creating the very mismatch this
migration exists to prevent."""
for device_type in ("range_hood", "airconditioner"):
entry = _entry(hass, device_type)
_add_sensor(hass, entry, "dust")
_add_sensor(hass, entry, "fine_dust")
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert relabel.call_args_list == [], device_type
assert entry.version == 3
async def test_is_a_no_op_without_the_recorder(hass: HomeAssistant) -> None:
"""A setup running without the recorder has no statistics to relabel,
and importing recorder internals there would fail outright."""
entry = _entry(hass, "air_purifier")
_add_sensor(hass, entry, "dust")
hass.config.components.remove("recorder")
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert relabel.call_args_list == []
assert entry.version == 3
async def test_follows_a_renamed_entity_rather_than_rebuilding_its_id(
hass: HomeAssistant,
) -> None:
"""statistic_id is the entity_id, which the user can rename. Matching the
unique_id tail and reading entity_id back off the registry is what keeps
this correct for a renamed sensor -- reconstructing an entity_id from the
descriptor key would relabel a statistic nobody is recording."""
entry = _entry(hass, "air_purifier")
renamed = _add_sensor(hass, entry, "dust", suggested_object_id="living_room_pm10")
assert renamed.entity_id == "sensor.living_room_pm10"
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert [call.args[1] for call in relabel.call_args_list] == ["sensor.living_room_pm10"]
async def test_matches_subdevice_prefixed_and_instanced_keys(hass: HomeAssistant) -> None:
"""_key() can prefix a subdevice and append an instance number, so the
match is on the tail rather than the whole unique_id."""
entry = _entry(hass, "air_purifier")
ent_reg = er.async_get(hass)
for unique_suffix in ("indoor_0_dust", "fine_dust1", "super_fine_dust"):
ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_SERIAL}_{unique_suffix}",
config_entry=entry,
)
# Near-misses that must not match.
for unique_suffix in ("dustbag_full", "dustbin_auto_close", "dust_filter_reset"):
ent_reg.async_get_or_create(
"sensor",
DOMAIN,
f"{DOMAIN}_{MOCK_SERIAL}_{unique_suffix}",
config_entry=entry,
)
with patch(RELABEL) as relabel:
assert await async_migrate_entry(hass, entry) is True
assert len(relabel.call_args_list) == 3
async def test_a_fresh_entry_starts_at_the_migrated_version(hass: HomeAssistant) -> None:
"""A newly created entry has no statistics to relabel, so the config flow
mints v3 directly rather than walking through the migration."""
from custom_components.localthings.config_flow import LocalThingsConfigFlow
assert LocalThingsConfigFlow.VERSION == 3