core/tests/components/apcupsd/test_sensor.py
Yuxin Wang 33c5d1855d
Rewrite APCUPSD sensors using DataUpdateCoordinator (#88467)
* Add test sensor.

* Fix sensor test file name.

* Add binary sensor test.

* Fix comments and styling.

* Remove apcupsd from omissions in coveragerc.

* Revert "Remove apcupsd from omissions in coveragerc."

This reverts commit 66b05fcb8829619a771a650a3d70174089e15d91.

* Implement the data coordinator for apcupsd.

* Add tests for sensor updates and throttles.

* Reorder the statement for better code clarity.

* Update docstring.

* Add more tests for checking if the coordinator works ok.

* Implement a custom debouncer with 5 second cooldown for the coordinator.

* Add more tests for checking if our integration is able to properly mark entity's availability.

* Make apcupsd a silver integration.

* Try to fix non-deterministic test behaviors

* Fix JSON format

* Use new `with` format in python 3.10 for better readability

* Update tests.

* Rebase and simplify code.

* Add an ups prefix to the property methods of the coordinator

* Replace init_integration with async_init_integration

* Lint fixes

* Fix imports

* Update BinarySensor implementation to add initial update of attributes

* Fix test failures due to rebases

* Reorder the statements for better code clarity

* Fix incorrect references to the ups_name property

* Simplify BinarySensor value getter code

* No need to update when adding coordinator-controlled sensors
2023-11-21 22:40:05 +01:00

212 lines
7.6 KiB
Python

"""Test sensors of APCUPSd integration."""
from datetime import timedelta
from unittest.mock import patch
from homeassistant.components.apcupsd import REQUEST_REFRESH_COOLDOWN
from homeassistant.components.sensor import (
ATTR_STATE_CLASS,
SensorDeviceClass,
SensorStateClass,
)
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
ATTR_UNIT_OF_MEASUREMENT,
PERCENTAGE,
STATE_UNAVAILABLE,
UnitOfElectricPotential,
UnitOfPower,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from . import MOCK_STATUS, async_init_integration
from tests.common import async_fire_time_changed
async def test_sensor(hass: HomeAssistant, entity_registry: er.EntityRegistry) -> None:
"""Test states of sensor."""
await async_init_integration(hass, status=MOCK_STATUS)
# Test a representative string sensor.
state = hass.states.get("sensor.ups_mode")
assert state
assert state.state == "Stand Alone"
entry = entity_registry.async_get("sensor.ups_mode")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_upsmode"
# Test two representative voltage sensors.
state = hass.states.get("sensor.ups_input_voltage")
assert state
assert state.state == "124.0"
assert (
state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfElectricPotential.VOLT
)
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.VOLTAGE
entry = entity_registry.async_get("sensor.ups_input_voltage")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_linev"
state = hass.states.get("sensor.ups_battery_voltage")
assert state
assert state.state == "13.7"
assert (
state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfElectricPotential.VOLT
)
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.VOLTAGE
entry = entity_registry.async_get("sensor.ups_battery_voltage")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_battv"
# test a representative time sensor.
state = hass.states.get("sensor.ups_self_test_interval")
assert state
assert state.state == "7"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfTime.DAYS
entry = entity_registry.async_get("sensor.ups_self_test_interval")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_stesti"
# Test a representative percentage sensor.
state = hass.states.get("sensor.ups_load")
assert state
assert state.state == "14.0"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
entry = entity_registry.async_get("sensor.ups_load")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_loadpct"
# Test a representative wattage sensor.
state = hass.states.get("sensor.ups_nominal_output_power")
assert state
assert state.state == "330"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfPower.WATT
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.POWER
entry = entity_registry.async_get("sensor.ups_nominal_output_power")
assert entry
assert entry.unique_id == "XXXXXXXXXXXX_nompower"
async def test_sensor_disabled(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test sensor disabled by default."""
await async_init_integration(hass)
# Test a representative integration-disabled sensor.
entry = entity_registry.async_get("sensor.ups_model")
assert entry.disabled
assert entry.unique_id == "XXXXXXXXXXXX_model"
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
# Test enabling entity.
updated_entry = entity_registry.async_update_entity(
entry.entity_id, **{"disabled_by": None}
)
assert updated_entry != entry
assert updated_entry.disabled is False
async def test_state_update(hass: HomeAssistant) -> None:
"""Ensure the sensor state changes after updating the data."""
await async_init_integration(hass)
state = hass.states.get("sensor.ups_load")
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "14.0"
new_status = MOCK_STATUS | {"LOADPCT": "15.0 Percent"}
with (
patch("apcaccess.status.parse", return_value=new_status),
patch("apcaccess.status.get", return_value=b""),
):
future = utcnow() + timedelta(minutes=2)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get("sensor.ups_load")
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "15.0"
async def test_manual_update_entity(hass: HomeAssistant) -> None:
"""Test manual update entity via service homeassistant/update_entity."""
await async_init_integration(hass)
# Assert the initial state of sensor.ups_load.
state = hass.states.get("sensor.ups_load")
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "14.0"
# Setup HASS for calling the update_entity service.
await async_setup_component(hass, "homeassistant", {})
with (
patch("apcaccess.status.parse") as mock_parse,
patch("apcaccess.status.get", return_value=b"") as mock_get,
):
mock_parse.return_value = MOCK_STATUS | {
"LOADPCT": "15.0 Percent",
"BCHARGE": "99.0 Percent",
}
# Now, we fast-forward the time to pass the debouncer cooldown, but put it
# before the normal update interval to see if the manual update works.
future = utcnow() + timedelta(seconds=REQUEST_REFRESH_COOLDOWN)
async_fire_time_changed(hass, future)
await hass.services.async_call(
"homeassistant",
"update_entity",
{ATTR_ENTITY_ID: ["sensor.ups_load", "sensor.ups_battery"]},
blocking=True,
)
# Even if we requested updates for two entities, our integration should smartly
# group the API calls to just one.
assert mock_parse.call_count == 1
assert mock_get.call_count == 1
# The new state should be effective.
state = hass.states.get("sensor.ups_load")
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "15.0"
async def test_multiple_manual_update_entity(hass: HomeAssistant) -> None:
"""Test multiple simultaneous manual update entity via service homeassistant/update_entity.
We should only do network call once for the multiple simultaneous update entity services.
"""
await async_init_integration(hass)
# Setup HASS for calling the update_entity service.
await async_setup_component(hass, "homeassistant", {})
with (
patch("apcaccess.status.parse", return_value=MOCK_STATUS) as mock_parse,
patch("apcaccess.status.get", return_value=b"") as mock_get,
):
# Fast-forward time to just pass the initial debouncer cooldown.
future = utcnow() + timedelta(seconds=REQUEST_REFRESH_COOLDOWN)
async_fire_time_changed(hass, future)
await hass.services.async_call(
"homeassistant",
"update_entity",
{ATTR_ENTITY_ID: ["sensor.ups_load", "sensor.ups_input_voltage"]},
blocking=True,
)
assert mock_parse.call_count == 1
assert mock_get.call_count == 1