Refactor / update Awair integration (#34394)

* Refactor / update Awair integration

This commit does a few things, all in service of making the Awair
integration more modern and reliable. Specifically we do the following:

- Update to python_awair 0.1.1
- Begin using config entries / flow for setting up the integration.
  - YAML support is completely removed.
  - The integration now allows adding multiple Awair accounts, should a
    user wish to do so (I found it _very_ useful in development).
- Group various Awair sensors into devices, using the device registry.
- Renames various sensors and treats the "dust" sensor as a particulate sensor.
- Device update rate-limits are no longer dynamically calculated; the
  Awair API now separates rate-limits on a per-device basis.
- Supports sound pressure and illuminance sensors found on some Awair devices.
- We report the "awair index" for certain sensors as part of device_state_attributes.
  The "index" is a subjective measure of whether or not a sensor reading
  is "good" or "bad" (and to what extent). It's a component of the Awair
  score, and it is useful on its own as an input for those who wish to
  do things like "display this color if the value is 'bad'".

This is a breaking change, and requires updates to documentation and a
warning in the README. The breaking changes in detail, are:

- Support for all YAML configuration is removed, and users will need to
  re-add the integration via the UI.
- We no longer support overriding device discovery via manual
  configuration of device UUIDs. This was previously supported because
  the Awair API had severe limits on the device list endpoints; however
  those have since been removed.
- Gen 1 devices no longer show a "dust" sensor; rather we create a PM2.5
  sensor and a PM10 sensor and just keep the values in sync. This better
  reflects the sensor capabilities: it can detect particles in a range
  from 2.5 -> 10, but cannot differentiate between sizes.
- Sensors are renamed as follows:
  - "sensor.devicename_co2"   -> "sensor.devicename_carbon_dioxide"
  - "sensor.devicename_voc"   -> "sensor.devicename_volatile_organic_compounds"
  - "sensor.devicename_score" -> "sensor.devicename_air_quality_index"
  - I've chosen to call the "Awair Score" an "air quality index" sensor,
    because fundamentally the "Awair Score" and other air quality indices
    (such as CAQI) do the same thing: they calculate a value based on a
    variety of other inputs.

Under the hood, the integration has seen some improvements:

- We use the DataUpdateCoordinator class to handle updates, rather than
  rolling our own update class.
- The code no longer tracks availability based on a timestamp returned
  from the Awair service; we assert that if we have received a response
  and the response has data for our device, then we are available (and
  otherwise, not available). We don't need to test the actual Awair API
  so heavily.
- Test coverage has been expanded to handle a variety of products that
  Awair produces, not just the one I happen to own.
- Test coverage no longer concerns itself with testing behavior that is
  now handled by the DataUpdateCoordinator; nor is it concerned with
  ensuring that the overall component sets up and registers properly.
  These are assumed to be well-tested functionaity of the core and not
  things we need to re-test ourselves.

Finally - between library updates and integration updates, this
integration is well-positioned to support future updates. I have a
proof-of-concept patch for device automations, and the underlying
library now supports subclassing authentication (which clears the way
for us to use OAuth authentication for Awair).

* Wrap test fixture in mock_coro

Truthfully I'm not sure why this was passing on my local dev
environment, but I was developing with python 3.8 before. After
installing python 3.7, I was able to reproduce the CI failures and fix
them.

* Fix broken tests after #34901 and/or #34989

* Do not rename sensors so broadly

We're going to keep the sensors named as they were before, pending the
outcome of any decisions around the air_quality component and what names
should be standardized for air-quality-like devices.

If standardized names are selected (which does seem likely), then we
will update this integration to match them - at which point, it would be
a breaking change.

But for now, we'll keep names mostly identical to what users had before.

Notable in this commit is that we generate the entity_id ourselves,
rather than just allowing it to be auto-generated from the name
attribute. This allows us to provide more human friendly names, while
keeping the old format for entity ids. For example, given an Awair
device called "Living Room", we'll generate an entity id of
"sensor.living_room_voc" but show set the name of the device to "Living
Room Volatile organic compounds".

* Support import from config.yaml

We'll create a config entry from config.yaml the first time we're
loaded, and then defer to it from then on.

We ignore all keys other than the access_token, since we no longer need
to deal with per-account rate-limits (rather, everything is per-device
now).

* Add myself to CODEOWNERS

Since I wrote the initial integration, and now this re-write, it feels
appropriate for me to take care of the integration along with `danielsjf`.

* Remove name mangling

* Update homeassistant/components/awair/manifest.json

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/awair/config_flow.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/awair/sensor.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/awair/sensor.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Address some review feedback

* Set up reauth flow in a job, rather than awaiting

* Remove unnecessary title string

* Remove unnecessary config schema checking

As pointed out in review, because this comes in via import from
`configuration.yaml`, we can rely on the `PLATFORM_SCHEMA` validation instead.

* Fix tests

* Set unique_id appropriately for legacy devices

For users who have had this integration already installed (and who have
updated their home assistant installation sometime in recent history),
we want to ensure that unique_id's are set to the same thing as before,
to facilitate the upgrade process.

To do that, we add an additional property to the `SENSOR_TYPES` dict
(`ATTR_UNIQUE_ID`) which allows us to map modern sensor names from
python_awair to what older versions called them - ie: `humidity` ->
`HUMID`. We then use that value when constructing the unique ID. This
should allow users to upgrade and not lose configuration even if entity
IDs would otherwise change (because we have changed the name format that
generates entity IDs).

One note is that for the gen1 `DUST` sensor, we have to treat it
differently. This integration used to call that a "PM2.5" sensor, but
the unique_id generated would be something like `awair_12345_DUST`. So
we special-case that sensor, and do the same thing. We do not need to
special-case the PM10 sensor for gen1 devices, because we didn't create
a PM10 sensor in the past (we do now, because the "DUST" sensor is
really a hybrid PM2.5/PM10 sensor).

* Patch async_setup_entry for two tests

* Update awair config_flow to require / use an email address for unique_id

Also, only start one re-auth flow.

* Add a few more tests, try to get coverage up.

* Add another test

* Move attribution to device_state_attributes

* Don't require email

* Switch from Union[dict, None] to Optional[dict]

* Use a mock where requested

* Fix missing constant rename

* Use async_create_task

* Bump test coverage a bit for config_flow

* s/CONF_UNIQUE_ID/UNIQUE_ID/g

* Add warning about deprecated platform config

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Andrew HayworthandMartin Hjelmare authored and GitHub committed 2020-06-21 21:46:07 +02:00
1 parent 1de97e3a35
commit fed6625324
25 files changed
+1094 -602

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
"""Constants used in Awair tests."""
import json
from homeassistant.const import CONF_ACCESS_TOKEN
from tests.common import load_fixture
AWAIR_UUID = "awair_24947"
CONFIG = {CONF_ACCESS_TOKEN: "12345"}
UNIQUE_ID = "foo@bar.com"
DEVICES_FIXTURE = json.loads(load_fixture("awair/devices.json"))
GEN1_DATA_FIXTURE = json.loads(load_fixture("awair/awair.json"))
GEN2_DATA_FIXTURE = json.loads(load_fixture("awair/awair-r2.json"))
GLOW_DATA_FIXTURE = json.loads(load_fixture("awair/glow.json"))
MINT_DATA_FIXTURE = json.loads(load_fixture("awair/mint.json"))
NO_DEVICES_FIXTURE = json.loads(load_fixture("awair/no_devices.json"))
OFFLINE_FIXTURE = json.loads(load_fixture("awair/awair-offline.json"))
OMNI_DATA_FIXTURE = json.loads(load_fixture("awair/omni.json"))
USER_FIXTURE = json.loads(load_fixture("awair/user.json"))
+190
View File
@@ -0,0 +1,190 @@
"""Define tests for the Awair config flow."""
from asynctest import patch
from python_awair.exceptions import AuthError, AwairError
from homeassistant import data_entry_flow
from homeassistant.components.awair.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_ACCESS_TOKEN
from .const import CONFIG, DEVICES_FIXTURE, NO_DEVICES_FIXTURE, UNIQUE_ID, USER_FIXTURE
from tests.common import MockConfigEntry
async def test_show_form(hass):
"""Test that the form is served with no input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
async def test_invalid_access_token(hass):
"""Test that errors are shown when the access token is invalid."""
with patch("python_awair.AwairClient.query", side_effect=AuthError()):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["errors"] == {CONF_ACCESS_TOKEN: "auth"}
async def test_unexpected_api_error(hass):
"""Test that we abort on generic errors."""
with patch("python_awair.AwairClient.query", side_effect=AwairError()):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["type"] == "abort"
assert result["reason"] == "unknown"
async def test_duplicate_error(hass):
"""Test that errors are shown when adding a duplicate config."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE]
), patch(
"homeassistant.components.awair.sensor.async_setup_entry", return_value=True,
):
MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
async def test_no_devices_error(hass):
"""Test that errors are shown when the API returns no devices."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, NO_DEVICES_FIXTURE]
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["type"] == "abort"
assert result["reason"] == "no_devices"
async def test_import(hass):
"""Test config.yaml import."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE]
), patch(
"homeassistant.components.awair.sensor.async_setup_entry", return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_ACCESS_TOKEN: CONFIG[CONF_ACCESS_TOKEN]},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "foo@bar.com (32406)"
assert result["data"][CONF_ACCESS_TOKEN] == CONFIG[CONF_ACCESS_TOKEN]
assert result["result"].unique_id == UNIQUE_ID
async def test_import_aborts_on_api_error(hass):
"""Test config.yaml imports on api error."""
with patch("python_awair.AwairClient.query", side_effect=AwairError()):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_ACCESS_TOKEN: CONFIG[CONF_ACCESS_TOKEN]},
)
assert result["type"] == "abort"
assert result["reason"] == "unknown"
async def test_import_aborts_if_configured(hass):
"""Test config import doesn't re-import unnecessarily."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE]
), patch(
"homeassistant.components.awair.sensor.async_setup_entry", return_value=True,
):
MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_ACCESS_TOKEN: CONFIG[CONF_ACCESS_TOKEN]},
)
assert result["type"] == "abort"
assert result["reason"] == "already_setup"
async def test_reauth(hass):
"""Test reauth flow."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE]
), patch(
"homeassistant.components.awair.sensor.async_setup_entry", return_value=True,
):
mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
mock_config.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config, data={**CONFIG, CONF_ACCESS_TOKEN: "blah"}
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG,
)
assert result["type"] == "abort"
assert result["reason"] == "reauth_successful"
with patch("python_awair.AwairClient.query", side_effect=AuthError()):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG,
)
assert result["errors"] == {CONF_ACCESS_TOKEN: "auth"}
with patch("python_awair.AwairClient.query", side_effect=AwairError()):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG,
)
assert result["type"] == "abort"
assert result["reason"] == "unknown"
async def test_create_entry(hass):
"""Test overall flow."""
with patch(
"python_awair.AwairClient.query", side_effect=[USER_FIXTURE, DEVICES_FIXTURE]
), patch(
"homeassistant.components.awair.sensor.async_setup_entry", return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "foo@bar.com (32406)"
assert result["data"][CONF_ACCESS_TOKEN] == CONFIG[CONF_ACCESS_TOKEN]
assert result["result"].unique_id == UNIQUE_ID
+299 -269
View File
@@ -1,312 +1,342 @@
"""Tests for the Awair sensor platform."""
from contextlib import contextmanager
from datetime import timedelta
import json
import logging
from homeassistant.components.awair.sensor import (
ATTR_LAST_API_UPDATE,
ATTR_TIMESTAMP,
DEVICE_CLASS_CARBON_DIOXIDE,
DEVICE_CLASS_PM2_5,
DEVICE_CLASS_SCORE,
DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS,
from homeassistant.components.awair.const import (
API_CO2,
API_HUMID,
API_LUX,
API_PM10,
API_PM25,
API_SCORE,
API_SPL_A,
API_TEMP,
API_VOC,
ATTR_UNIQUE_ID,
DOMAIN,
SENSOR_TYPES,
)
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_BILLION,
CONCENTRATION_PARTS_PER_MILLION,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
STATE_UNAVAILABLE,
TEMP_CELSIUS,
UNIT_PERCENTAGE,
)
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import parse_datetime, utcnow
from .const import (
AWAIR_UUID,
CONFIG,
DEVICES_FIXTURE,
GEN1_DATA_FIXTURE,
GEN2_DATA_FIXTURE,
GLOW_DATA_FIXTURE,
MINT_DATA_FIXTURE,
OFFLINE_FIXTURE,
OMNI_DATA_FIXTURE,
UNIQUE_ID,
USER_FIXTURE,
)
from tests.async_mock import patch
from tests.common import async_fire_time_changed, load_fixture
DISCOVERY_CONFIG = {"sensor": {"platform": "awair", "access_token": "qwerty"}}
MANUAL_CONFIG = {
"sensor": {
"platform": "awair",
"access_token": "qwerty",
"devices": [{"uuid": "awair_foo"}],
}
}
_LOGGER = logging.getLogger(__name__)
NOW = utcnow()
AIR_DATA_FIXTURE = json.loads(load_fixture("awair_air_data_latest.json"))
AIR_DATA_FIXTURE[0][ATTR_TIMESTAMP] = str(NOW)
AIR_DATA_FIXTURE_UPDATED = json.loads(
load_fixture("awair_air_data_latest_updated.json")
)
AIR_DATA_FIXTURE_UPDATED[0][ATTR_TIMESTAMP] = str(NOW + timedelta(minutes=5))
AIR_DATA_FIXTURE_EMPTY = []
from tests.common import MockConfigEntry
@contextmanager
def alter_time(retval):
"""Manage multiple time mocks."""
patch_one = patch("homeassistant.util.dt.utcnow", return_value=retval)
patch_two = patch("homeassistant.util.utcnow", return_value=retval)
patch_three = patch(
"homeassistant.components.awair.sensor.dt.utcnow", return_value=retval
)
async def setup_awair(hass, fixtures):
"""Add Awair devices to hass, using specified fixtures for data."""
with patch_one, patch_two, patch_three:
yield
async def setup_awair(hass, config=None, data_fixture=AIR_DATA_FIXTURE):
"""Load the Awair platform."""
devices_json = json.loads(load_fixture("awair_devices.json"))
devices_mock = devices_json
devices_patch = patch("python_awair.AwairClient.devices", return_value=devices_mock)
air_data_mock = data_fixture
air_data_patch = patch(
"python_awair.AwairClient.air_data_latest", return_value=air_data_mock
)
if config is None:
config = DISCOVERY_CONFIG
with devices_patch, air_data_patch, alter_time(NOW):
assert await async_setup_component(hass, SENSOR_DOMAIN, config)
entry = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
with patch("python_awair.AwairClient.query", side_effect=fixtures):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
async def test_platform_manually_configured(hass):
"""Test that we can manually configure devices."""
await setup_awair(hass, MANUAL_CONFIG)
def assert_expected_properties(
hass, registry, name, unique_id, state_value, attributes
):
"""Assert expected properties from a dict."""
assert len(hass.states.async_all()) == 6
# Ensure that we loaded the device with uuid 'awair_foo', not the
# 'awair_12345' device that we stub out for API device discovery
entity = hass.data[SENSOR_DOMAIN].get_entity("sensor.awair_co2")
assert entity.unique_id == "awair_foo_CO2"
entry = registry.async_get(name)
assert entry.unique_id == unique_id
state = hass.states.get(name)
assert state
assert state.state == state_value
for attr, value in attributes.items():
assert state.attributes.get(attr) == value
async def test_platform_automatically_configured(hass):
"""Test that we can discover devices from the API."""
await setup_awair(hass)
async def test_awair_gen1_sensors(hass):
"""Test expected sensors on a 1st gen Awair."""
assert len(hass.states.async_all()) == 6
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN1_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
# Ensure that we loaded the device with uuid 'awair_12345', which is
# the device that we stub out for API device discovery
entity = hass.data[SENSOR_DOMAIN].get_entity("sensor.awair_co2")
assert entity.unique_id == "awair_12345_CO2"
async def test_bad_platform_setup(hass):
"""Tests that we throw correct exceptions when setting up Awair."""
from python_awair import AwairClient
auth_patch = patch(
"python_awair.AwairClient.devices", side_effect=AwairClient.AuthError
)
rate_patch = patch(
"python_awair.AwairClient.devices", side_effect=AwairClient.RatelimitError
)
generic_patch = patch(
"python_awair.AwairClient.devices", side_effect=AwairClient.GenericError
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"88",
{ATTR_ICON: "mdi:blur"},
)
with auth_patch:
assert await async_setup_component(hass, SENSOR_DOMAIN, DISCOVERY_CONFIG)
assert not hass.states.async_all()
assert_expected_properties(
hass,
registry,
"sensor.living_room_temperature",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_TEMP][ATTR_UNIQUE_ID]}",
"21.8",
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, "awair_index": 1.0},
)
with rate_patch:
assert await async_setup_component(hass, SENSOR_DOMAIN, DISCOVERY_CONFIG)
assert not hass.states.async_all()
assert_expected_properties(
hass,
registry,
"sensor.living_room_humidity",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_HUMID][ATTR_UNIQUE_ID]}",
"41.59",
{ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE, "awair_index": 0.0},
)
with generic_patch:
assert await async_setup_component(hass, SENSOR_DOMAIN, DISCOVERY_CONFIG)
assert not hass.states.async_all()
assert_expected_properties(
hass,
registry,
"sensor.living_room_carbon_dioxide",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_CO2][ATTR_UNIQUE_ID]}",
"654.0",
{
ATTR_ICON: "mdi:cloud",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_MILLION,
"awair_index": 0.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_volatile_organic_compounds",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_VOC][ATTR_UNIQUE_ID]}",
"366",
{
ATTR_ICON: "mdi:cloud",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
"awair_index": 1.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
# gen1 unique_id should be awair_12345-DUST, which matches old integration behavior
f"{AWAIR_UUID}_DUST",
"14.3",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 1.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm10",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM10][ATTR_UNIQUE_ID]}",
"14.3",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 1.0,
},
)
# We should not have a dust sensor; it's aliased as pm2.5
# and pm10 sensors.
assert hass.states.get("sensor.living_room_dust") is None
# We should not have sound or lux sensors.
assert hass.states.get("sensor.living_room_sound_level") is None
assert hass.states.get("sensor.living_room_illuminance") is None
async def test_awair_setup_no_data(hass):
"""Ensure that we do not crash during setup when no data is returned."""
await setup_awair(hass, data_fixture=AIR_DATA_FIXTURE_EMPTY)
assert not hass.states.async_all()
async def test_awair_gen2_sensors(hass):
"""Test expected sensors on a 2nd gen Awair."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN2_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"97",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}",
"2.0",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 0.0,
},
)
# The Awair 2nd gen reports specifically a pm2.5 sensor,
# and so we don't alias anything. Make sure we didn't do that.
assert hass.states.get("sensor.living_room_pm10") is None
async def test_awair_misc_attributes(hass):
"""Test that desired attributes are set."""
await setup_awair(hass)
async def test_awair_mint_sensors(hass):
"""Test expected sensors on an Awair mint."""
attributes = hass.states.get("sensor.awair_co2").attributes
assert attributes[ATTR_LAST_API_UPDATE] == parse_datetime(
AIR_DATA_FIXTURE[0][ATTR_TIMESTAMP]
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, MINT_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"98",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}",
"1.0",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 0.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_illuminance",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}",
"441.7",
{ATTR_UNIT_OF_MEASUREMENT: "lx"},
)
# The Mint does not have a CO2 sensor.
assert hass.states.get("sensor.living_room_carbon_dioxide") is None
async def test_awair_glow_sensors(hass):
"""Test expected sensors on an Awair glow."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GLOW_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"93",
{ATTR_ICON: "mdi:blur"},
)
# The glow does not have a particle sensor
assert hass.states.get("sensor.living_room_pm2_5") is None
async def test_awair_omni_sensors(hass):
"""Test expected sensors on an Awair omni."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, OMNI_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"99",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_sound_level",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SPL_A][ATTR_UNIQUE_ID]}",
"47.0",
{ATTR_ICON: "mdi:ear-hearing", ATTR_UNIT_OF_MEASUREMENT: "dBa"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_illuminance",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}",
"804.9",
{ATTR_UNIT_OF_MEASUREMENT: "lx"},
)
async def test_awair_score(hass):
"""Test that we create a sensor for the 'Awair score'."""
await setup_awair(hass)
async def test_awair_offline(hass):
"""Test expected behavior when an Awair is offline."""
sensor = hass.states.get("sensor.awair_score")
assert sensor.state == "78"
assert sensor.attributes["device_class"] == DEVICE_CLASS_SCORE
assert sensor.attributes["unit_of_measurement"] == UNIT_PERCENTAGE
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, OFFLINE_FIXTURE]
await setup_awair(hass, fixtures)
# The expected behavior is that we won't have any sensors
# if the device is not online when we set it up. python_awair
# does not make any assumptions about what sensors a device
# might have - they are created dynamically.
# We check for the absence of the "awair score", which every
# device *should* have if it's online. If we don't see it,
# then we probably didn't set anything up. Which is correct,
# in this case.
assert hass.states.get("sensor.living_room_awair_score") is None
async def test_awair_temp(hass):
"""Test that we create a temperature sensor."""
await setup_awair(hass)
async def test_awair_unavailable(hass):
"""Test expected behavior when an Awair becomes offline later."""
sensor = hass.states.get("sensor.awair_temperature")
assert sensor.state == "22.4"
assert sensor.attributes["device_class"] == DEVICE_CLASS_TEMPERATURE
assert sensor.attributes["unit_of_measurement"] == TEMP_CELSIUS
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN1_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
async def test_awair_humid(hass):
"""Test that we create a humidity sensor."""
await setup_awair(hass)
sensor = hass.states.get("sensor.awair_humidity")
assert sensor.state == "32.7"
assert sensor.attributes["device_class"] == DEVICE_CLASS_HUMIDITY
assert sensor.attributes["unit_of_measurement"] == UNIT_PERCENTAGE
async def test_awair_co2(hass):
"""Test that we create a CO2 sensor."""
await setup_awair(hass)
sensor = hass.states.get("sensor.awair_co2")
assert sensor.state == "612"
assert sensor.attributes["device_class"] == DEVICE_CLASS_CARBON_DIOXIDE
assert sensor.attributes["unit_of_measurement"] == CONCENTRATION_PARTS_PER_MILLION
async def test_awair_voc(hass):
"""Test that we create a CO2 sensor."""
await setup_awair(hass)
sensor = hass.states.get("sensor.awair_voc")
assert sensor.state == "1012"
assert sensor.attributes["device_class"] == DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS
assert sensor.attributes["unit_of_measurement"] == CONCENTRATION_PARTS_PER_BILLION
async def test_awair_dust(hass):
"""Test that we create a pm25 sensor."""
await setup_awair(hass)
# The Awair Gen1 that we mock actually returns 'DUST', but that
# is mapped to pm25 internally so that it shows up in Homekit
sensor = hass.states.get("sensor.awair_pm2_5")
assert sensor.state == "6.2"
assert sensor.attributes["device_class"] == DEVICE_CLASS_PM2_5
assert (
sensor.attributes["unit_of_measurement"]
== CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"88",
{ATTR_ICON: "mdi:blur"},
)
async def test_awair_unsupported_sensors(hass):
"""Ensure we don't create sensors the stubbed device doesn't support."""
await setup_awair(hass)
# Our tests mock an Awair Gen 1 device, which should never return
# PM10 sensor readings. Assert that we didn't create a pm10 sensor,
# which could happen if someone were ever to refactor incorrectly.
assert hass.states.get("sensor.awair_pm10") is None
async def test_availability(hass):
"""Ensure that we mark the component available/unavailable correctly."""
await setup_awair(hass)
assert hass.states.get("sensor.awair_score").state == "78"
future = NOW + timedelta(minutes=30)
data_patch = patch(
"python_awair.AwairClient.air_data_latest", return_value=AIR_DATA_FIXTURE,
)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get("sensor.awair_score").state == STATE_UNAVAILABLE
future = NOW + timedelta(hours=1)
fixture = AIR_DATA_FIXTURE_UPDATED
fixture[0][ATTR_TIMESTAMP] = str(future)
data_patch = patch("python_awair.AwairClient.air_data_latest", return_value=fixture)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get("sensor.awair_score").state == "79"
future = NOW + timedelta(minutes=90)
fixture = AIR_DATA_FIXTURE_EMPTY
data_patch = patch("python_awair.AwairClient.air_data_latest", return_value=fixture)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get("sensor.awair_score").state == STATE_UNAVAILABLE
async def test_async_update(hass):
"""Ensure we can update sensors."""
await setup_awair(hass)
future = NOW + timedelta(minutes=10)
data_patch = patch(
"python_awair.AwairClient.air_data_latest",
return_value=AIR_DATA_FIXTURE_UPDATED,
)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
score_sensor = hass.states.get("sensor.awair_score")
assert score_sensor.state == "79"
assert hass.states.get("sensor.awair_temperature").state == "23.4"
assert hass.states.get("sensor.awair_humidity").state == "33.7"
assert hass.states.get("sensor.awair_co2").state == "613"
assert hass.states.get("sensor.awair_voc").state == "1013"
assert hass.states.get("sensor.awair_pm2_5").state == "7.2"
async def test_throttle_async_update(hass):
"""Ensure we throttle updates."""
await setup_awair(hass)
future = NOW + timedelta(minutes=1)
data_patch = patch(
"python_awair.AwairClient.air_data_latest",
return_value=AIR_DATA_FIXTURE_UPDATED,
)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get("sensor.awair_score").state == "78"
future = NOW + timedelta(minutes=15)
with data_patch, alter_time(future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get("sensor.awair_score").state == "79"
with patch("python_awair.AwairClient.query", side_effect=OFFLINE_FIXTURE):
await hass.helpers.entity_component.async_update_entity(
"sensor.living_room_awair_score"
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
STATE_UNAVAILABLE,
{ATTR_ICON: "mdi:blur"},
)