core/tests/components/dsmr/test_sensor.py

208 lines
6.5 KiB
Python
Raw Normal View History

2016-11-23 07:03:39 +00:00
"""Test for DSMR components.
Tests setup of the DSMR component and ensure incoming telegrams cause
Entity to be updated with new values.
2016-11-23 07:03:39 +00:00
"""
import asyncio
import datetime
2016-11-23 07:03:39 +00:00
from decimal import Decimal
from unittest.mock import Mock
import asynctest
import pytest
2016-11-23 07:03:39 +00:00
from homeassistant.bootstrap import async_setup_component
Consolidate all platforms that have tests (#22109) * Moved climate components with tests into platform dirs. * Updated tests from climate component. * Moved binary_sensor components with tests into platform dirs. * Updated tests from binary_sensor component. * Moved calendar components with tests into platform dirs. * Updated tests from calendar component. * Moved camera components with tests into platform dirs. * Updated tests from camera component. * Moved cover components with tests into platform dirs. * Updated tests from cover component. * Moved device_tracker components with tests into platform dirs. * Updated tests from device_tracker component. * Moved fan components with tests into platform dirs. * Updated tests from fan component. * Moved geo_location components with tests into platform dirs. * Updated tests from geo_location component. * Moved image_processing components with tests into platform dirs. * Updated tests from image_processing component. * Moved light components with tests into platform dirs. * Updated tests from light component. * Moved lock components with tests into platform dirs. * Moved media_player components with tests into platform dirs. * Updated tests from media_player component. * Moved scene components with tests into platform dirs. * Moved sensor components with tests into platform dirs. * Updated tests from sensor component. * Moved switch components with tests into platform dirs. * Updated tests from sensor component. * Moved vacuum components with tests into platform dirs. * Updated tests from vacuum component. * Moved weather components with tests into platform dirs. * Fixed __init__.py files * Fixes for stuff moved as part of this branch. * Fix stuff needed to merge with balloob's branch. * Formatting issues. * Missing __init__.py files. * Fix-ups * Fixup * Regenerated requirements. * Linting errors fixed. * Fixed more broken tests. * Missing init files. * Fix broken tests. * More broken tests * There seems to be a thread race condition. I suspect the logger stuff is running in another thread, which means waiting until the aio loop is done is missing the log messages. Used sleep instead because that allows the logger thread to run. I think the api_streams sensor might not be thread safe. * Disabled tests, will remove sensor in #22147 * Updated coverage and codeowners.
2019-03-19 06:07:39 +00:00
from homeassistant.components.dsmr.sensor import DerivativeDSMREntity
from tests.common import assert_setup_component
@pytest.fixture
def mock_connection_factory(monkeypatch):
"""Mock the create functions for serial and TCP Asyncio connections."""
from dsmr_parser.clients.protocol import DSMRProtocol
2019-07-31 19:25:30 +00:00
transport = asynctest.Mock(spec=asyncio.Transport)
protocol = asynctest.Mock(spec=DSMRProtocol)
@asyncio.coroutine
def connection_factory(*args, **kwargs):
"""Return mocked out Asyncio classes."""
return (transport, protocol)
2019-07-31 19:25:30 +00:00
connection_factory = Mock(wraps=connection_factory)
# apply the mock to both connection factories
monkeypatch.setattr(
"homeassistant.components.dsmr.sensor.create_dsmr_reader", connection_factory
2019-07-31 19:25:30 +00:00
)
monkeypatch.setattr(
"homeassistant.components.dsmr.sensor.create_tcp_dsmr_reader",
connection_factory,
2019-07-31 19:25:30 +00:00
)
return connection_factory, transport, protocol
2016-11-23 07:03:39 +00:00
@asyncio.coroutine
def test_default_setup(hass, mock_connection_factory):
2016-11-23 07:03:39 +00:00
"""Test the default setup."""
(connection_factory, transport, protocol) = mock_connection_factory
2016-11-23 07:03:39 +00:00
from dsmr_parser.obis_references import (
CURRENT_ELECTRICITY_USAGE,
ELECTRICITY_ACTIVE_TARIFF,
)
from dsmr_parser.objects import CosemObject
2019-07-31 19:25:30 +00:00
config = {"platform": "dsmr"}
2016-11-23 07:03:39 +00:00
telegram = {
2019-07-31 19:25:30 +00:00
CURRENT_ELECTRICITY_USAGE: CosemObject(
[{"value": Decimal("0.0"), "unit": "kWh"}]
),
ELECTRICITY_ACTIVE_TARIFF: CosemObject([{"value": "0001", "unit": ""}]),
2016-11-23 07:03:39 +00:00
}
with assert_setup_component(1):
2019-07-31 19:25:30 +00:00
yield from async_setup_component(hass, "sensor", {"sensor": config})
2016-11-23 07:03:39 +00:00
telegram_callback = connection_factory.call_args_list[0][0][2]
2016-11-23 07:03:39 +00:00
# make sure entities have been created and return 'unknown' state
2019-07-31 19:25:30 +00:00
power_consumption = hass.states.get("sensor.power_consumption")
assert power_consumption.state == "unknown"
assert power_consumption.attributes.get("unit_of_measurement") is None
2016-11-23 07:03:39 +00:00
# simulate a telegram pushed from the smartmeter and parsed by dsmr_parser
telegram_callback(telegram)
# after receiving telegram entities need to have the chance to update
yield from asyncio.sleep(0)
2016-11-23 07:03:39 +00:00
# ensure entities have new state value after incoming telegram
2019-07-31 19:25:30 +00:00
power_consumption = hass.states.get("sensor.power_consumption")
assert power_consumption.state == "0.0"
assert power_consumption.attributes.get("unit_of_measurement") == "kWh"
2016-11-23 07:03:39 +00:00
# tariff should be translated in human readable and have no unit
2019-07-31 19:25:30 +00:00
power_tariff = hass.states.get("sensor.power_tariff")
assert power_tariff.state == "low"
assert power_tariff.attributes.get("unit_of_measurement") == ""
@asyncio.coroutine
def test_derivative():
"""Test calculation of derivative value."""
from dsmr_parser.objects import MBusObject
2019-07-31 19:25:30 +00:00
config = {"platform": "dsmr"}
2019-07-31 19:25:30 +00:00
entity = DerivativeDSMREntity("test", "1.0.0", config)
yield from entity.async_update()
2019-07-31 19:25:30 +00:00
assert entity.state is None, "initial state not unknown"
entity.telegram = {
2019-07-31 19:25:30 +00:00
"1.0.0": MBusObject(
[
{"value": datetime.datetime.fromtimestamp(1551642213)},
{"value": Decimal(745.695), "unit": "m3"},
]
)
}
yield from entity.async_update()
2019-07-31 19:25:30 +00:00
assert entity.state is None, "state after first update should still be unknown"
entity.telegram = {
2019-07-31 19:25:30 +00:00
"1.0.0": MBusObject(
[
{"value": datetime.datetime.fromtimestamp(1551642543)},
{"value": Decimal(745.698), "unit": "m3"},
]
)
}
yield from entity.async_update()
2019-07-31 19:25:30 +00:00
assert (
abs(entity.state - 0.033) < 0.00001
), "state should be hourly usage calculated from first and second update"
2019-07-31 19:25:30 +00:00
assert entity.unit_of_measurement == "m3/h"
@asyncio.coroutine
def test_tcp(hass, mock_connection_factory):
"""If proper config provided TCP connection should be made."""
(connection_factory, transport, protocol) = mock_connection_factory
2019-07-31 19:25:30 +00:00
config = {"platform": "dsmr", "host": "localhost", "port": 1234}
with assert_setup_component(1):
2019-07-31 19:25:30 +00:00
yield from async_setup_component(hass, "sensor", {"sensor": config})
2019-07-31 19:25:30 +00:00
assert connection_factory.call_args_list[0][0][0] == "localhost"
assert connection_factory.call_args_list[0][0][1] == "1234"
@asyncio.coroutine
def test_connection_errors_retry(hass, monkeypatch, mock_connection_factory):
"""Connection should be retried on error during setup."""
(connection_factory, transport, protocol) = mock_connection_factory
2019-07-31 19:25:30 +00:00
config = {"platform": "dsmr", "reconnect_interval": 0}
# override the mock to have it fail the first time
first_fail_connection_factory = Mock(
2019-07-31 19:25:30 +00:00
wraps=connection_factory, side_effect=[TimeoutError]
)
monkeypatch.setattr(
"homeassistant.components.dsmr.sensor.create_dsmr_reader",
first_fail_connection_factory,
2019-07-31 19:25:30 +00:00
)
yield from async_setup_component(hass, "sensor", {"sensor": config})
# wait for sleep to resolve
yield from hass.async_block_till_done()
2019-07-31 19:25:30 +00:00
assert first_fail_connection_factory.call_count == 2, "connecting not retried"
@asyncio.coroutine
def test_reconnect(hass, monkeypatch, mock_connection_factory):
"""If transport disconnects, the connection should be retried."""
(connection_factory, transport, protocol) = mock_connection_factory
2019-07-31 19:25:30 +00:00
config = {"platform": "dsmr", "reconnect_interval": 0}
# mock waiting coroutine while connection lasts
closed = asyncio.Event()
# Handshake so that `hass.async_block_till_done()` doesn't cycle forever
closed2 = asyncio.Event()
@asyncio.coroutine
def wait_closed():
yield from closed.wait()
closed2.set()
closed.clear()
2019-07-31 19:25:30 +00:00
protocol.wait_closed = wait_closed
2019-07-31 19:25:30 +00:00
yield from async_setup_component(hass, "sensor", {"sensor": config})
assert connection_factory.call_count == 1
# indicate disconnect, release wait lock and allow reconnect to happen
closed.set()
# wait for lock set to resolve
yield from closed2.wait()
closed2.clear()
assert not closed.is_set()
closed.set()
yield from hass.async_block_till_done()
2019-07-31 19:25:30 +00:00
assert connection_factory.call_count >= 2, "connecting not retried"