Skip to content

Commit

Permalink
Catch InvalidAuthError in shutdown() method for Shelly gen2 devices (
Browse files Browse the repository at this point in the history
…#94563)

* Catch InvalidAuthError in shutdown() method

* Add test

* Revert unwanted change in tests
  • Loading branch information
bieniu authored and balloob committed Jun 15, 2023
1 parent 70d3312 commit f67577e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
5 changes: 4 additions & 1 deletion homeassistant/components/shelly/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,10 @@ def async_setup(self) -> None:
async def shutdown(self) -> None:
"""Shutdown the coordinator."""
if self.device.connected:
await async_stop_scanner(self.device)
try:
await async_stop_scanner(self.device)
except InvalidAuthError:
self.entry.async_start_reauth(self.hass)
await self.device.shutdown()
await self._async_disconnected()

Expand Down
55 changes: 54 additions & 1 deletion tests/components/shelly/test_coordinator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Tests for Shelly coordinator."""
from datetime import timedelta
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, patch

from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError

Expand Down Expand Up @@ -335,6 +335,59 @@ async def test_rpc_reload_on_cfg_change(
assert hass.states.get("switch.test_switch_0") is None


async def test_rpc_reload_with_invalid_auth(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC when InvalidAuthError is raising during config entry reload."""
with patch(
"homeassistant.components.shelly.coordinator.async_stop_scanner",
side_effect=[None, InvalidAuthError, None],
):
entry = await init_integration(hass, 2)

inject_rpc_device_event(
monkeypatch,
mock_rpc_device,
{
"events": [
{
"data": [],
"event": "config_changed",
"id": 1,
"ts": 1668522399.2,
},
{
"data": [],
"id": 2,
"ts": 1668522399.2,
},
],
"ts": 1668522399.2,
},
)

await hass.async_block_till_done()

# Move time to generate reconnect
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=RPC_RECONNECT_INTERVAL)
)
await hass.async_block_till_done()

assert entry.state == ConfigEntryState.LOADED

flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1

flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.get("handler") == DOMAIN

assert "context" in flow
assert flow["context"].get("source") == SOURCE_REAUTH
assert flow["context"].get("entry_id") == entry.entry_id


async def test_rpc_click_event(
hass: HomeAssistant, mock_rpc_device, events, monkeypatch
) -> None:
Expand Down

0 comments on commit f67577e

Please sign in to comment.