Smart Meter Texas integration (#37966)

* Run scaffold script

* Update version

* Bump version

* Initial commit

* Move meter and ESIID to device attributes

* Update internal to hourly due to api limit

* Format with Black

* Fix typo

* Update tests

* Update description

* Disable Pylint error

* Don't commit translations

* Remove meter number from sensor name

* Allow multiple meters per account

* Move data updates to a DataUpdateCoordinator

* Use setdefault to setup the component

* Move strings to const.py

* Fix tests

* Remove meter last updated attribute

* Bump smart-meter-texas version

* Fix logger call

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove unneeded manifest keys

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon property

Co-authored-by: J. Nick Koston <nick@koston.org>

* Handle instance where user already setup an account

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon constant

* Fix indentation

* Handle config flow errors better

* Use ESIID + meter number as unique ID for sensor

* Update config flow tests to reach 100% coverage

* Avoid reading meters on startup

Cherrypick @bdraco's suggestion

* Run scaffold script

* Update version

* Bump version

* Initial commit

* Move meter and ESIID to device attributes

* Update internal to hourly due to api limit

* Format with Black

* Fix typo

* Update tests

* Update description

* Disable Pylint error

* Don't commit translations

* Remove meter number from sensor name

* Allow multiple meters per account

* Move data updates to a DataUpdateCoordinator

* Use setdefault to setup the component

* Move strings to const.py

* Fix tests

* Remove meter last updated attribute

* Bump smart-meter-texas version

* Fix logger call

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove unneeded manifest keys

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon property

Co-authored-by: J. Nick Koston <nick@koston.org>

* Handle instance where user already setup an account

Co-authored-by: J. Nick Koston <nick@koston.org>

* Remove icon constant

* Fix indentation

* Handle config flow errors better

* Use ESIID + meter number as unique ID for sensor

* Update config flow tests to reach 100% coverage

* Remove unnecessary try/except block

This checks for the same exception just prior in execution on L51.

* Remove unused return values

* Add tests

* Improve tests and coverage

* Use more pythonic control flow

* Remove all uses of hass.data

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Graham WetzlerandJ. Nick Koston authored and GitHub committed 2020-08-19 13:16:45 -05:00
1 parent e626937147
commit bb164bb32c
17 files changed
+780

No files matched your search

@@ -0,0 +1 @@
"""Tests for the Smart Meter Texas integration."""
@@ -0,0 +1,100 @@
"""Test configuration and mocks for Smart Meter Texas."""
import asyncio
import json
from pathlib import Path
import pytest
from smart_meter_texas.const import (
AUTH_ENDPOINT,
BASE_ENDPOINT,
BASE_URL,
LATEST_OD_READ_ENDPOINT,
METER_ENDPOINT,
OD_READ_ENDPOINT,
)
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.smart_meter_texas.const import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, load_fixture
TEST_ENTITY_ID = "sensor.electric_meter_123456789"
def load_smt_fixture(name):
"""Return a dict of the json fixture."""
json_fixture = load_fixture(Path() / DOMAIN / f"{name}.json")
return json.loads(json_fixture)
async def setup_integration(hass, config_entry, aioclient_mock):
"""Initialize the Smart Meter Texas integration for testing."""
mock_connection(aioclient_mock)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
async def refresh_data(hass, config_entry, aioclient_mock):
"""Request a DataUpdateCoordinator refresh."""
mock_connection(aioclient_mock)
await async_setup_component(hass, HA_DOMAIN, {})
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
def mock_connection(
aioclient_mock, auth_fail=False, auth_timeout=False, bad_reading=False
):
"""Mock all calls to the API."""
aioclient_mock.get(BASE_URL)
auth_endpoint = f"{BASE_ENDPOINT}{AUTH_ENDPOINT}"
if not auth_fail and not auth_timeout:
aioclient_mock.post(
auth_endpoint, json={"token": "token123"},
)
elif auth_fail:
aioclient_mock.post(
auth_endpoint,
status=400,
json={"errormessage": "ERR-USR-INVALIDPASSWORDERROR"},
)
else: # auth_timeout
aioclient_mock.post(auth_endpoint, exc=asyncio.TimeoutError)
aioclient_mock.post(
f"{BASE_ENDPOINT}{METER_ENDPOINT}", json=load_smt_fixture("meter"),
)
aioclient_mock.post(f"{BASE_ENDPOINT}{OD_READ_ENDPOINT}", json={"data": None})
if not bad_reading:
aioclient_mock.post(
f"{BASE_ENDPOINT}{LATEST_OD_READ_ENDPOINT}",
json=load_smt_fixture("latestodrread"),
)
else:
aioclient_mock.post(
f"{BASE_ENDPOINT}{LATEST_OD_READ_ENDPOINT}", json={},
)
@pytest.fixture(name="config_entry")
def mock_config_entry(hass):
"""Return a mock config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id="user123",
data={"username": "user123", "password": "password123"},
)
config_entry.add_to_hass(hass)
return config_entry
@@ -0,0 +1,120 @@
"""Test the Smart Meter Texas config flow."""
import asyncio
from aiohttp import ClientError
import pytest
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant import config_entries, setup
from homeassistant.components.smart_meter_texas.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from tests.async_mock import patch
from tests.common import MockConfigEntry
TEST_LOGIN = {CONF_USERNAME: "test-username", CONF_PASSWORD: "test-password"}
async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch("smart_meter_texas.Client.authenticate", return_value=True), patch(
"homeassistant.components.smart_meter_texas.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.smart_meter_texas.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_LOGIN
)
assert result2["type"] == "create_entry"
assert result2["title"] == TEST_LOGIN[CONF_USERNAME]
assert result2["data"] == TEST_LOGIN
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_invalid_auth(hass):
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"smart_meter_texas.Client.authenticate", side_effect=SmartMeterTexasAuthError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_LOGIN,
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "invalid_auth"}
@pytest.mark.parametrize(
"side_effect", [asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError]
)
async def test_form_cannot_connect(hass, side_effect):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"smart_meter_texas.Client.authenticate", side_effect=side_effect,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_LOGIN
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_unknown_exception(hass):
"""Test base exception is handled."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"smart_meter_texas.Client.authenticate", side_effect=Exception,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_LOGIN,
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "unknown"}
async def test_form_duplicate_account(hass):
"""Test that a duplicate account cannot be configured."""
MockConfigEntry(
domain=DOMAIN,
unique_id="user123",
data={"username": "user123", "password": "password123"},
).add_to_hass(hass)
with patch(
"smart_meter_texas.Client.authenticate", return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={"username": "user123", "password": "password123"},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
@@ -0,0 +1,74 @@
"""Test the Smart Meter Texas module."""
import pytest
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.smart_meter_texas import async_setup_entry
from homeassistant.components.smart_meter_texas.const import DOMAIN
from homeassistant.config_entries import ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.setup import async_setup_component
from .conftest import TEST_ENTITY_ID, mock_connection, setup_integration
from tests.async_mock import patch
async def test_setup_with_no_config(hass):
"""Test that no config is successful."""
assert await async_setup_component(hass, DOMAIN, {}) is True
await hass.async_block_till_done()
# Assert no flows were started.
assert len(hass.config_entries.flow.async_progress()) == 0
async def test_auth_failure(hass, config_entry, aioclient_mock):
"""Test if user's username or password is not accepted."""
mock_connection(aioclient_mock, auth_fail=True)
result = await async_setup_entry(hass, config_entry)
assert result is False
async def test_api_timeout(hass, config_entry, aioclient_mock):
"""Test that a timeout results in ConfigEntryNotReady."""
mock_connection(aioclient_mock, auth_timeout=True)
with pytest.raises(ConfigEntryNotReady):
await async_setup_entry(hass, config_entry)
assert config_entry.state == ENTRY_STATE_NOT_LOADED
async def test_update_failure(hass, config_entry, aioclient_mock):
"""Test that the coordinator handles a bad response."""
mock_connection(aioclient_mock, bad_reading=True)
await setup_integration(hass, config_entry, aioclient_mock)
await async_setup_component(hass, HA_DOMAIN, {})
with patch("smart_meter_texas.Meter.read_meter") as updater:
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
updater.assert_called_once()
async def test_unload_config_entry(hass, config_entry, aioclient_mock):
"""Test entry unloading."""
await setup_integration(hass, config_entry, aioclient_mock)
config_entries = hass.config_entries.async_entries(DOMAIN)
assert len(config_entries) == 1
assert config_entries[0] is config_entry
assert config_entry.state == ENTRY_STATE_LOADED
await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state == ENTRY_STATE_NOT_LOADED
@@ -0,0 +1,65 @@
"""Test the Smart Meter Texas sensor entity."""
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.smart_meter_texas.const import (
ELECTRIC_METER,
ESIID,
METER_NUMBER,
)
from homeassistant.const import ATTR_ENTITY_ID, CONF_ADDRESS
from homeassistant.setup import async_setup_component
from .conftest import TEST_ENTITY_ID, mock_connection, refresh_data, setup_integration
from tests.async_mock import patch
async def test_sensor(hass, config_entry, aioclient_mock):
"""Test that the sensor is setup."""
mock_connection(aioclient_mock)
await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock)
meter = hass.states.get(TEST_ENTITY_ID)
assert meter
assert meter.state == "9751.212"
async def test_name(hass, config_entry, aioclient_mock):
"""Test sensor name property."""
mock_connection(aioclient_mock)
await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock)
meter = hass.states.get(TEST_ENTITY_ID)
assert meter.name == f"{ELECTRIC_METER} 123456789"
async def test_attributes(hass, config_entry, aioclient_mock):
"""Test meter attributes."""
mock_connection(aioclient_mock)
await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock)
meter = hass.states.get(TEST_ENTITY_ID)
assert meter.attributes[METER_NUMBER] == "123456789"
assert meter.attributes[ESIID] == "12345678901234567"
assert meter.attributes[CONF_ADDRESS] == "123 MAIN ST"
async def test_generic_entity_update_service(hass, config_entry, aioclient_mock):
"""Test generic update entity service homeasasistant/update_entity."""
mock_connection(aioclient_mock)
await setup_integration(hass, config_entry, aioclient_mock)
await async_setup_component(hass, HA_DOMAIN, {})
with patch("smart_meter_texas.Meter.read_meter") as updater:
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
updater.assert_called_once()