core/tests/components/tcp/test_sensor.py

237 lines
7.8 KiB
Python
Raw Normal View History

2016-03-09 09:25:50 +00:00
"""The tests for the TCP sensor platform."""
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 copy import copy
from unittest.mock import call, patch
import pytest
2016-02-19 17:41:51 +00:00
import homeassistant.components.tcp.common as tcp
from homeassistant.setup 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 tests.common import assert_setup_component
2016-02-19 17:41:51 +00:00
TEST_CONFIG = {
2019-07-31 19:25:30 +00:00
"sensor": {
"platform": "tcp",
tcp.CONF_NAME: "test_name",
tcp.CONF_HOST: "test_host",
2016-10-22 04:14:35 +00:00
tcp.CONF_PORT: 12345,
tcp.CONF_TIMEOUT: tcp.DEFAULT_TIMEOUT + 1,
2019-07-31 19:25:30 +00:00
tcp.CONF_PAYLOAD: "test_payload",
tcp.CONF_UNIT_OF_MEASUREMENT: "test_unit",
tcp.CONF_VALUE_TEMPLATE: "{{ 'test_' + value }}",
2019-07-31 19:25:30 +00:00
tcp.CONF_VALUE_ON: "test_on",
tcp.CONF_BUFFER_SIZE: tcp.DEFAULT_BUFFER_SIZE + 1,
}
2016-02-19 17:41:51 +00:00
}
SENSOR_TEST_CONFIG = TEST_CONFIG["sensor"]
TEST_ENTITY = "sensor.test_name"
2016-10-22 04:14:35 +00:00
2016-02-19 17:41:51 +00:00
KEYS_AND_DEFAULTS = {
tcp.CONF_NAME: tcp.DEFAULT_NAME,
2016-02-19 17:41:51 +00:00
tcp.CONF_TIMEOUT: tcp.DEFAULT_TIMEOUT,
2016-10-22 04:14:35 +00:00
tcp.CONF_UNIT_OF_MEASUREMENT: None,
2016-02-19 17:41:51 +00:00
tcp.CONF_VALUE_TEMPLATE: None,
tcp.CONF_VALUE_ON: None,
2019-07-31 19:25:30 +00:00
tcp.CONF_BUFFER_SIZE: tcp.DEFAULT_BUFFER_SIZE,
2016-02-19 17:41:51 +00:00
}
socket_test_value = "value"
2016-02-19 17:41:51 +00:00
@pytest.fixture(name="mock_socket")
def mock_socket_fixture(mock_select):
"""Mock socket."""
with patch("homeassistant.components.tcp.common.socket.socket") as mock_socket:
socket_instance = mock_socket.return_value.__enter__.return_value
socket_instance.recv.return_value = socket_test_value.encode()
yield socket_instance
2016-02-19 17:41:51 +00:00
@pytest.fixture(name="mock_select")
def mock_select_fixture():
"""Mock select."""
with patch(
"homeassistant.components.tcp.common.select.select",
return_value=(True, False, False),
) as mock_select:
yield mock_select
@pytest.fixture(name="mock_ssl_context")
def mock_ssl_context_fixture():
"""Mock select."""
with patch(
"homeassistant.components.tcp.common.ssl.create_default_context",
) as mock_ssl_context:
mock_ssl_context.return_value.wrap_socket.return_value.recv.return_value = (
socket_test_value + "_ssl"
).encode()
yield mock_ssl_context
async def test_setup_platform_valid_config(hass, mock_socket):
"""Check a valid configuration and call add_entities with sensor."""
with assert_setup_component(1, "sensor"):
assert await async_setup_component(hass, "sensor", TEST_CONFIG)
await hass.async_block_till_done()
async def test_setup_platform_invalid_config(hass, mock_socket):
"""Check an invalid configuration."""
with assert_setup_component(0):
assert await async_setup_component(
hass, "sensor", {"sensor": {"platform": "tcp", "porrt": 1234}}
2019-07-31 19:25:30 +00:00
)
await hass.async_block_till_done()
async def test_state(hass, mock_socket, mock_select):
"""Return the contents of _state."""
assert await async_setup_component(hass, "sensor", TEST_CONFIG)
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state
assert state.state == "test_value"
assert (
state.attributes["unit_of_measurement"]
== SENSOR_TEST_CONFIG[tcp.CONF_UNIT_OF_MEASUREMENT]
)
assert mock_socket.connect.called
assert mock_socket.connect.call_args == call(
(SENSOR_TEST_CONFIG["host"], SENSOR_TEST_CONFIG["port"])
)
assert mock_socket.send.called
assert mock_socket.send.call_args == call(SENSOR_TEST_CONFIG["payload"].encode())
assert mock_select.call_args == call(
[mock_socket], [], [], SENSOR_TEST_CONFIG[tcp.CONF_TIMEOUT]
)
assert mock_socket.recv.called
assert mock_socket.recv.call_args == call(SENSOR_TEST_CONFIG["buffer_size"])
async def test_config_uses_defaults(hass, mock_socket):
"""Check if defaults were set."""
config = copy(SENSOR_TEST_CONFIG)
for key in KEYS_AND_DEFAULTS:
del config[key]
with assert_setup_component(1) as result_config:
assert await async_setup_component(hass, "sensor", {"sensor": config})
await hass.async_block_till_done()
state = hass.states.get("sensor.tcp_sensor")
assert state
assert state.state == "value"
for key, default in KEYS_AND_DEFAULTS.items():
assert result_config["sensor"][0].get(key) == default
@pytest.mark.parametrize("sock_attr", ["connect", "send"])
async def test_update_socket_error(hass, mock_socket, sock_attr):
"""Test socket errors during update."""
socket_method = getattr(mock_socket, sock_attr)
socket_method.side_effect = OSError("Boom")
assert await async_setup_component(hass, "sensor", TEST_CONFIG)
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state
assert state.state == "unknown"
async def test_update_select_fails(hass, mock_socket, mock_select):
"""Test select fails to return a socket for reading."""
mock_select.return_value = (False, False, False)
assert await async_setup_component(hass, "sensor", TEST_CONFIG)
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state
assert state.state == "unknown"
async def test_update_returns_if_template_render_fails(hass, mock_socket):
"""Return None if rendering the template fails."""
config = copy(SENSOR_TEST_CONFIG)
config[tcp.CONF_VALUE_TEMPLATE] = "{{ value / 0 }}"
assert await async_setup_component(hass, "sensor", {"sensor": config})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
2016-02-19 17:41:51 +00:00
assert state
assert state.state == "unknown"
async def test_ssl_state(hass, mock_socket, mock_select, mock_ssl_context):
"""Return the contents of _state, updated over SSL."""
config = copy(SENSOR_TEST_CONFIG)
config[tcp.CONF_SSL] = "on"
assert await async_setup_component(hass, "sensor", {"sensor": config})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state
assert state.state == "test_value_ssl"
assert mock_socket.connect.called
assert mock_socket.connect.call_args == call(
(SENSOR_TEST_CONFIG["host"], SENSOR_TEST_CONFIG["port"])
)
assert not mock_socket.send.called
assert mock_ssl_context.called
assert mock_ssl_context.return_value.check_hostname
mock_ssl_socket = mock_ssl_context.return_value.wrap_socket.return_value
assert mock_ssl_socket.send.called
assert mock_ssl_socket.send.call_args == call(
SENSOR_TEST_CONFIG["payload"].encode()
)
assert mock_select.call_args == call(
[mock_ssl_socket], [], [], SENSOR_TEST_CONFIG[tcp.CONF_TIMEOUT]
)
assert mock_ssl_socket.recv.called
assert mock_ssl_socket.recv.call_args == call(SENSOR_TEST_CONFIG["buffer_size"])
async def test_ssl_state_verify_off(hass, mock_socket, mock_select, mock_ssl_context):
"""Return the contents of _state, updated over SSL (verify_ssl disabled)."""
config = copy(SENSOR_TEST_CONFIG)
config[tcp.CONF_SSL] = "on"
config[tcp.CONF_VERIFY_SSL] = "off"
assert await async_setup_component(hass, "sensor", {"sensor": config})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state
assert state.state == "test_value_ssl"
assert mock_socket.connect.called
assert mock_socket.connect.call_args == call(
(SENSOR_TEST_CONFIG["host"], SENSOR_TEST_CONFIG["port"])
)
assert not mock_socket.send.called
assert mock_ssl_context.called
assert not mock_ssl_context.return_value.check_hostname
mock_ssl_socket = mock_ssl_context.return_value.wrap_socket.return_value
assert mock_ssl_socket.send.called
assert mock_ssl_socket.send.call_args == call(
SENSOR_TEST_CONFIG["payload"].encode()
)
assert mock_select.call_args == call(
[mock_ssl_socket], [], [], SENSOR_TEST_CONFIG[tcp.CONF_TIMEOUT]
)
assert mock_ssl_socket.recv.called
assert mock_ssl_socket.recv.call_args == call(SENSOR_TEST_CONFIG["buffer_size"])