Skip to content

Commit

Permalink
Keep cloud instance on config entry deletion (close #513)
Browse files Browse the repository at this point in the history
  • Loading branch information
dext0r committed May 7, 2024
1 parent 6b67285 commit c91ebb4
Show file tree
Hide file tree
Showing 4 changed files with 3 additions and 71 deletions.
8 changes: 0 additions & 8 deletions custom_components/yandex_smart_home/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import voluptuous as vol

from . import config_validation as ycv, const
from .cloud import delete_cloud_instance
from .const import CONF_SKILL, CONF_USER_ID, DOMAIN, ConnectionType, EntityFilterSource
from .entry_data import ConfigEntryData
from .helpers import SmartHomePlatform
Expand Down Expand Up @@ -358,13 +357,6 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Remove a config entry."""
if entry.data.get(const.CONF_CONNECTION_TYPE) == ConnectionType.CLOUD:
await delete_cloud_instance(
hass,
instance_id=entry.data[const.CONF_CLOUD_INSTANCE][const.CONF_CLOUD_INSTANCE_ID],
token=entry.data[const.CONF_CLOUD_INSTANCE][const.CONF_CLOUD_INSTANCE_CONNECTION_TOKEN],
)

component: YandexSmartHome | None = hass.data.get(DOMAIN)
if component:
await component.async_remove_entry(entry)
Expand Down
15 changes: 0 additions & 15 deletions custom_components/yandex_smart_home/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from asyncio import TimeoutError
from datetime import datetime, timedelta
from http import HTTPStatus
import logging
from typing import TYPE_CHECKING, Any, AsyncIterable, cast

Expand Down Expand Up @@ -163,17 +162,3 @@ async def register_cloud_instance(hass: HomeAssistant) -> CloudInstanceData:
response.raise_for_status()

return CloudInstanceData.parse_raw(await response.text())


async def delete_cloud_instance(hass: HomeAssistant, instance_id: str, token: str) -> None:
"""Delete a cloud instance from the cloud."""
session = async_create_clientsession(hass)

response = await session.delete(
f"{BASE_API_URL}/instance/{instance_id}",
headers={hdrs.AUTHORIZATION: f"Bearer {token}"},
)
if response.status != HTTPStatus.OK:
_LOGGER.error(f"Failed to delete cloud instance, status code: {response.status}")

return None
2 changes: 0 additions & 2 deletions docs/config/connection-type.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# Выбор типа подключения
!!! danger "**Не удаляйте интеграцию** с облачным подключением без надобности. При удалении происходит отвязка от УДЯ с удалением связки ID/Пароль. При повторной настройке интеграции потребуется снова выполнять связку аккаунтов в УДЯ (уже с новыми реквизитами)."

Поменять тип подключения у существующей интеграции невозможно. Однако, можно добавить новую интеграцию с желаемым типом без удаления старой.

Примерный набор шагов для перехода с прямого подключения на облачное или наоборот:
Expand Down
49 changes: 3 additions & 46 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,9 @@
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry, load_fixture, patch_yaml_files

from custom_components.yandex_smart_home import (
DOMAIN,
ConnectionType,
EntityFilterSource,
YandexSmartHome,
cloud,
const,
)
from custom_components.yandex_smart_home import DOMAIN, ConnectionType, EntityFilterSource, YandexSmartHome, const
from custom_components.yandex_smart_home.config_flow import ConfigFlowHandler

from . import test_cloud


async def test_bad_config(hass):
with patch_yaml_files({YAML_CONFIG_FILE: "yandex_smart_home:\n bad: true"}):
Expand Down Expand Up @@ -397,7 +388,7 @@ async def test_unload_entry(hass, config_entry_direct):
assert entry_data.entry.state == ConfigEntryState.NOT_LOADED


async def test_remove_entry_direct(hass, config_entry_direct):
async def test_remove_entry(hass, config_entry_direct):
config_entry_direct.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry_direct.entry_id)

Expand All @@ -407,45 +398,11 @@ async def test_remove_entry_direct(hass, config_entry_direct):
assert len(component._entry_datas) == 0


async def test_remove_entry_cloud(hass, config_entry_cloud, aioclient_mock, caplog):
await test_cloud.async_setup_entry(hass, config_entry_cloud, aiohttp_client=aioclient_mock)

aioclient_mock.delete(f"{cloud.BASE_API_URL}/instance/i-test", status=500)
await hass.config_entries.async_remove(config_entry_cloud.entry_id)
assert aioclient_mock.call_count == 1
assert caplog.messages[-1] == "Failed to delete cloud instance, status code: 500"

aioclient_mock.clear_requests()
caplog.clear()

await test_cloud.async_setup_entry(hass, config_entry_cloud, aiohttp_client=aioclient_mock)
caplog.clear()

aioclient_mock.delete(f"{cloud.BASE_API_URL}/instance/i-test", status=200)
await hass.config_entries.async_remove(config_entry_cloud.entry_id)
(method, url, data, headers) = aioclient_mock.mock_calls[0]
assert headers == {"Authorization": "Bearer token-foo"}

assert aioclient_mock.call_count == 1
assert len(caplog.records) == 0


async def test_remove_entry_direct_unloaded(hass, config_entry_direct):
async def test_remove_entry_unloaded(hass, config_entry_direct):
config_entry_direct.add_to_hass(hass)
await hass.config_entries.async_remove(config_entry_direct.entry_id)


async def test_remove_entry_cloud_unloaded(hass, config_entry_cloud, aioclient_mock):
config_entry_cloud.add_to_hass(hass)

aioclient_mock.delete(f"{cloud.BASE_API_URL}/instance/i-test", status=200)
await hass.config_entries.async_remove(config_entry_cloud.entry_id)
(method, url, data, headers) = aioclient_mock.mock_calls[0]
assert headers == {"Authorization": "Bearer token-foo"}

assert aioclient_mock.call_count == 1


async def test_remove_entry_unknown(hass):
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})

Expand Down

0 comments on commit c91ebb4

Please sign in to comment.