Refactor Certificate Expiry Sensor (#32066)

* Cert Expiry refactor

* Unused parameter

* Reduce delay

* Deprecate 'name' config

* Use config entry unique_id

* Fix logic bugs found with tests

* Rewrite tests to use config flow core interfaces, validate created sensors

* Update strings

* Minor consistency fix

* Review fixes, complete test coverage

* Move error handling to helper

* Subclass exceptions

* Better tests

* Use first object reference

* Fix docstring
This commit is contained in:
jjlawren authored and GitHub committed 2020-03-02 07:44:24 -06:00
1 parent eb90cefd84
commit df3f7687d4
11 files changed
+652 -236

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
"""Constants for cert_expiry tests."""
PORT = 443
HOST = "example.com"
+181 -117
View File
@@ -1,154 +1,218 @@
"""Tests for the Cert Expiry config flow."""
import socket
import ssl
from unittest.mock import patch
import pytest
from asynctest import patch
from homeassistant import data_entry_flow
from homeassistant.components.cert_expiry import config_flow
from homeassistant.components.cert_expiry.const import DEFAULT_NAME, DEFAULT_PORT
from homeassistant.components.cert_expiry.const import DEFAULT_PORT, DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from tests.common import MockConfigEntry, mock_coro
from .const import HOST, PORT
NAME = "Cert Expiry test 1 2 3"
PORT = 443
HOST = "example.com"
from tests.common import MockConfigEntry
@pytest.fixture(name="test_connect")
def mock_controller():
"""Mock a successful _prt_in_configuration_exists."""
with patch(
"homeassistant.components.cert_expiry.config_flow.CertexpiryConfigFlow._test_connection",
side_effect=lambda *_: mock_coro(True),
):
yield
def init_config_flow(hass):
"""Init a configuration flow."""
flow = config_flow.CertexpiryConfigFlow()
flow.hass = hass
return flow
async def test_user(hass, test_connect):
async def test_user(hass):
"""Test user config."""
flow = init_config_flow(hass)
result = await flow.async_step_user()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
# tets with all provided
result = await flow.async_step_user(
{CONF_NAME: NAME, CONF_HOST: HOST, CONF_PORT: PORT}
)
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry"
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST, CONF_PORT: PORT}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
assert result["result"].unique_id == f"{HOST}:{PORT}"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_import(hass, test_connect):
"""Test import step."""
flow = init_config_flow(hass)
# import with only host
result = await flow.async_step_import({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == DEFAULT_NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == DEFAULT_PORT
# import with host and name
result = await flow.async_step_import({CONF_HOST: HOST, CONF_NAME: NAME})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == DEFAULT_PORT
# improt with host and port
result = await flow.async_step_import({CONF_HOST: HOST, CONF_PORT: PORT})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == DEFAULT_NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
# import with all
result = await flow.async_step_import(
{CONF_HOST: HOST, CONF_PORT: PORT, CONF_NAME: NAME}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
async def test_abort_if_already_setup(hass, test_connect):
"""Test we abort if the cert is already setup."""
flow = init_config_flow(hass)
MockConfigEntry(
domain="cert_expiry",
data={CONF_PORT: DEFAULT_PORT, CONF_NAME: NAME, CONF_HOST: HOST},
).add_to_hass(hass)
# Should fail, same HOST and PORT (default)
result = await flow.async_step_import(
{CONF_HOST: HOST, CONF_NAME: NAME, CONF_PORT: DEFAULT_PORT}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "host_port_exists"
# Should be the same HOST and PORT (default)
result = await flow.async_step_user(
{CONF_HOST: HOST, CONF_NAME: NAME, CONF_PORT: DEFAULT_PORT}
async def test_user_with_bad_cert(hass):
"""Test user config with bad certificate."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "host_port_exists"}
assert result["step_id"] == "user"
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=ssl.SSLError("some error"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST, CONF_PORT: PORT}
)
# SHOULD pass, same Host diff PORT
result = await flow.async_step_import(
{CONF_HOST: HOST, CONF_NAME: NAME, CONF_PORT: 888}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
assert result["result"].unique_id == f"{HOST}:{PORT}"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_import_host_only(hass):
"""Test import with host only."""
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry",
return_value=1,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data={CONF_HOST: HOST}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == DEFAULT_PORT
assert result["result"].unique_id == f"{HOST}:{DEFAULT_PORT}"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_import_host_and_port(hass):
"""Test import with host and port."""
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry",
return_value=1,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "import"},
data={CONF_HOST: HOST, CONF_PORT: PORT},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
assert result["result"].unique_id == f"{HOST}:{PORT}"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_import_non_default_port(hass):
"""Test import with host and non-default port."""
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry"
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data={CONF_HOST: HOST, CONF_PORT: 888}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == f"{HOST}:888"
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == 888
assert result["result"].unique_id == f"{HOST}:888"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_import_with_name(hass):
"""Test import with name (deprecated)."""
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry",
return_value=1,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "import"},
data={CONF_NAME: "legacy", CONF_HOST: HOST, CONF_PORT: PORT},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT
assert result["result"].unique_id == f"{HOST}:{PORT}"
with patch("homeassistant.components.cert_expiry.sensor.async_setup_entry"):
await hass.async_block_till_done()
async def test_bad_import(hass):
"""Test import step."""
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=ConnectionRefusedError(),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data={CONF_HOST: HOST}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "import_failed"
async def test_abort_if_already_setup(hass):
"""Test we abort if the cert is already setup."""
MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data={CONF_HOST: HOST, CONF_PORT: PORT}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}, data={CONF_HOST: HOST, CONF_PORT: PORT}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
async def test_abort_on_socket_failed(hass):
"""Test we abort of we have errors during socket creation."""
flow = init_config_flow(hass)
with patch("socket.create_connection", side_effect=socket.gaierror()):
result = await flow.async_step_user({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "resolve_failed"}
with patch("socket.create_connection", side_effect=socket.timeout()):
result = await flow.async_step_user({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "connection_timeout"}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
with patch(
"socket.create_connection",
side_effect=ssl.CertificateError(f"{HOST} doesn't match somethingelse.com"),
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=socket.gaierror(),
):
result = await flow.async_step_user({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "wrong_host"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "resolve_failed"}
with patch(
"socket.create_connection", side_effect=ssl.CertificateError("different error")
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=socket.timeout(),
):
result = await flow.async_step_user({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "certificate_error"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "connection_timeout"}
with patch("socket.create_connection", side_effect=ssl.SSLError()):
result = await flow.async_step_user({CONF_HOST: HOST})
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "certificate_error"}
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=ConnectionRefusedError,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: HOST}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {CONF_HOST: "connection_refused"}
+96
View File
@@ -0,0 +1,96 @@
"""Tests for Cert Expiry setup."""
from datetime import timedelta
from asynctest import patch
from homeassistant.components.cert_expiry.const import DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_START
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from .const import HOST, PORT
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_setup_with_config(hass):
"""Test setup component with config."""
config = {
SENSOR_DOMAIN: [
{"platform": DOMAIN, CONF_HOST: HOST, CONF_PORT: PORT},
{"platform": DOMAIN, CONF_HOST: HOST, CONF_PORT: 888},
],
}
assert await async_setup_component(hass, SENSOR_DOMAIN, config) is True
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
next_update = dt_util.utcnow() + timedelta(seconds=20)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.config_flow.get_cert_time_to_expiry",
return_value=100,
), patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 2
async def test_update_unique_id(hass):
"""Test updating a config entry without a unique_id."""
entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: HOST, CONF_PORT: PORT})
entry.add_to_hass(hass)
config_entries = hass.config_entries.async_entries(DOMAIN)
assert len(config_entries) == 1
assert entry is config_entries[0]
assert not entry.unique_id
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
assert await async_setup_component(hass, DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.state == ENTRY_STATE_LOADED
assert entry.unique_id == f"{HOST}:{PORT}"
async def test_unload_config_entry(hass):
"""Test unloading a config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
entry.add_to_hass(hass)
config_entries = hass.config_entries.async_entries(DOMAIN)
assert len(config_entries) == 1
assert entry is config_entries[0]
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
assert await async_setup_component(hass, DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.state == ENTRY_STATE_LOADED
state = hass.states.get("sensor.cert_expiry_example_com")
assert state.state == "100"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
await hass.config_entries.async_unload(entry.entry_id)
assert entry.state == ENTRY_STATE_NOT_LOADED
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is None
@@ -0,0 +1,211 @@
"""Tests for the Cert Expiry sensors."""
from datetime import timedelta
import socket
import ssl
from asynctest import patch
from homeassistant.const import CONF_HOST, CONF_PORT, STATE_UNAVAILABLE
import homeassistant.util.dt as dt_util
from .const import HOST, PORT
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_async_setup_entry(hass):
"""Test async_setup_entry."""
entry = MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "100"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
async def test_async_setup_entry_bad_cert(hass):
"""Test async_setup_entry with a bad/expired cert."""
entry = MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=ssl.SSLError("some error"),
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "0"
assert state.attributes.get("error") == "some error"
assert not state.attributes.get("is_valid")
async def test_async_setup_entry_host_unavailable(hass):
"""Test async_setup_entry when host is unavailable."""
entry = MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=socket.gaierror,
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is None
next_update = dt_util.utcnow() + timedelta(seconds=45)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=socket.gaierror,
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is None
async def test_update_sensor(hass):
"""Test async_update for sensor."""
entry = MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "100"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
next_update = dt_util.utcnow() + timedelta(hours=12)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=99,
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "99"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
async def test_update_sensor_network_errors(hass):
"""Test async_update for sensor."""
entry = MockConfigEntry(
domain="cert_expiry",
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=100,
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "100"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
next_update = dt_util.utcnow() + timedelta(hours=12)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=socket.gaierror,
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state.state == STATE_UNAVAILABLE
next_update = dt_util.utcnow() + timedelta(hours=12)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.sensor.get_cert_time_to_expiry",
return_value=99,
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "99"
assert state.attributes.get("error") == "None"
assert state.attributes.get("is_valid")
next_update = dt_util.utcnow() + timedelta(hours=12)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert",
side_effect=ssl.SSLError("something bad"),
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "0"
assert state.attributes.get("error") == "something bad"
assert not state.attributes.get("is_valid")
next_update = dt_util.utcnow() + timedelta(hours=12)
async_fire_time_changed(hass, next_update)
with patch(
"homeassistant.components.cert_expiry.helper.get_cert", side_effect=Exception()
):
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_example_com")
assert state.state == STATE_UNAVAILABLE