Improve Tractive (#54532)

* Tractive, code improve

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Tractive, code improve

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Tractive, code improve

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Update homeassistant/components/tractive/config_flow.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/tractive/const.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Tractive, comments

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Update homeassistant/components/tractive/config_flow.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/tractive/config_flow.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Tractive

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Reauth

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* Reauth

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* add tests

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

* add tests

Signed-off-by: Daniel Hjelseth Høyer <github@dahoiv.net>

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
pull/54698/head
Daniel Hjelseth Høyer 2021-08-16 12:56:10 +02:00 committed by GitHub
parent 75275254f9
commit d11c58dac8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 237 additions and 36 deletions

View File

@ -9,7 +9,7 @@ import aiotractive
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -38,6 +38,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
)
try:
creds = await client.authenticate()
except aiotractive.exceptions.UnauthorizedError as error:
await client.close()
raise ConfigEntryAuthFailed from error
except aiotractive.exceptions.TractiveError as error:
await client.close()
raise ConfigEntryNotReady from error

View File

@ -17,7 +17,9 @@ from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema({CONF_EMAIL: str, CONF_PASSWORD: str})
USER_DATA_SCHEMA = vol.Schema(
{vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str}
)
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
@ -47,9 +49,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> FlowResult:
"""Handle the initial step."""
if user_input is None:
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)
return self.async_show_form(step_id="user", data_schema=USER_DATA_SCHEMA)
errors = {}
@ -66,7 +66,39 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
step_id="user", data_schema=USER_DATA_SCHEMA, errors=errors
)
async def async_step_reauth(self, _: dict[str, Any]) -> FlowResult:
"""Handle configuration by re-auth."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] = None
) -> FlowResult:
"""Dialog that informs the user that reauth is required."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
existing_entry = await self.async_set_unique_id(info["user_id"])
if existing_entry:
await self.hass.config_entries.async_reload(existing_entry.entry_id)
return self.async_abort(reason="reauth_successful")
return self.async_abort(reason="reauth_failed_existing")
return self.async_show_form(
step_id="reauth_confirm",
data_schema=USER_DATA_SCHEMA,
errors=errors,
)

View File

@ -6,7 +6,7 @@ DOMAIN = "tractive"
RECONNECT_INTERVAL = timedelta(seconds=10)
TRACKER_HARDWARE_STATUS_UPDATED = "tracker_hardware_status_updated"
TRACKER_POSITION_UPDATED = "tracker_position_updated"
TRACKER_HARDWARE_STATUS_UPDATED = f"{DOMAIN}_tracker_hardware_status_updated"
TRACKER_POSITION_UPDATED = f"{DOMAIN}_tracker_position_updated"
SERVER_UNAVAILABLE = "tractive_server_unavailable"
SERVER_UNAVAILABLE = f"{DOMAIN}_server_unavailable"

View File

@ -94,41 +94,22 @@ class TractiveDeviceTracker(TrackerEntity):
"""Return the battery level of the device."""
return self._battery_level
async def async_added_to_hass(self):
"""Handle entity which will be added."""
@callback
def handle_hardware_status_update(event):
def _handle_hardware_status_update(self, event):
self._battery_level = event["battery_level"]
self._attr_available = True
self.async_write_ha_state()
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{TRACKER_HARDWARE_STATUS_UPDATED}-{self._tracker_id}",
handle_hardware_status_update,
)
)
@callback
def handle_position_update(event):
def _handle_position_update(self, event):
self._latitude = event["latitude"]
self._longitude = event["longitude"]
self._accuracy = event["accuracy"]
self._attr_available = True
self.async_write_ha_state()
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{TRACKER_POSITION_UPDATED}-{self._tracker_id}",
handle_position_update,
)
)
@callback
def handle_server_unavailable():
def _handle_server_unavailable(self):
self._latitude = None
self._longitude = None
self._accuracy = None
@ -136,10 +117,29 @@ class TractiveDeviceTracker(TrackerEntity):
self._attr_available = False
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Handle entity which will be added."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{TRACKER_HARDWARE_STATUS_UPDATED}-{self._tracker_id}",
self._handle_hardware_status_update,
)
)
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{TRACKER_POSITION_UPDATED}-{self._tracker_id}",
self._handle_position_update,
)
)
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{SERVER_UNAVAILABLE}-{self._user_id}",
handle_server_unavailable,
self._handle_server_unavailable,
)
)

View File

@ -13,7 +13,9 @@
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"reauth_failed_existing": "Could not update the config entry, please remove the integration and set it up again."
}
}
}

View File

@ -7,6 +7,8 @@ from homeassistant import config_entries, setup
from homeassistant.components.tractive.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
USER_INPUT = {
"email": "test-email@example.com",
"password": "test-password",
@ -76,3 +78,165 @@ async def test_form_unknown_error(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["errors"] == {"base": "unknown"}
async def test_flow_entry_already_exists(hass: HomeAssistant) -> None:
"""Test user input for config_entry that already exists."""
first_entry = MockConfigEntry(
domain="tractive",
data=USER_INPUT,
unique_id="USERID",
)
first_entry.add_to_hass(hass)
with patch("aiotractive.api.API.user_id", return_value="USERID"):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=USER_INPUT
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
async def test_reauthentication(hass):
"""Test Tractive reauthentication."""
old_entry = MockConfigEntry(
domain="tractive",
data=USER_INPUT,
unique_id="USERID",
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"unique_id": old_entry.unique_id,
"entry_id": old_entry.entry_id,
},
data=old_entry.data,
)
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == "reauth_confirm"
with patch("aiotractive.api.API.user_id", return_value="USERID"):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
await hass.async_block_till_done()
assert result2["type"] == "abort"
assert result2["reason"] == "reauth_successful"
async def test_reauthentication_failure(hass):
"""Test Tractive reauthentication failure."""
old_entry = MockConfigEntry(
domain="tractive",
data=USER_INPUT,
unique_id="USERID",
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"unique_id": old_entry.unique_id,
"entry_id": old_entry.entry_id,
},
data=old_entry.data,
)
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == "reauth_confirm"
with patch(
"aiotractive.api.API.user_id",
side_effect=aiotractive.exceptions.UnauthorizedError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
await hass.async_block_till_done()
assert result2["step_id"] == "reauth_confirm"
assert result["type"] == "form"
assert result2["errors"]["base"] == "invalid_auth"
async def test_reauthentication_unknown_failure(hass):
"""Test Tractive reauthentication failure."""
old_entry = MockConfigEntry(
domain="tractive",
data=USER_INPUT,
unique_id="USERID",
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"unique_id": old_entry.unique_id,
"entry_id": old_entry.entry_id,
},
data=old_entry.data,
)
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == "reauth_confirm"
with patch(
"aiotractive.api.API.user_id",
side_effect=Exception,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
await hass.async_block_till_done()
assert result2["step_id"] == "reauth_confirm"
assert result["type"] == "form"
assert result2["errors"]["base"] == "unknown"
async def test_reauthentication_failure_no_existing_entry(hass):
"""Test Tractive reauthentication with no existing entry."""
old_entry = MockConfigEntry(
domain="tractive",
data=USER_INPUT,
unique_id="USERID",
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"unique_id": old_entry.unique_id,
"entry_id": old_entry.entry_id,
},
data=old_entry.data,
)
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == "reauth_confirm"
with patch("aiotractive.api.API.user_id", return_value="USERID_DIFFERENT"):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
await hass.async_block_till_done()
assert result2["type"] == "abort"
assert result2["reason"] == "reauth_failed_existing"