Compare commits

...

1 Commits

Author SHA1 Message Date
Robert Resch
61f8d0a015 Migrate config entries to string unique id 2026-01-21 09:40:45 +00:00
18 changed files with 207 additions and 13 deletions

View File

@@ -2,14 +2,35 @@
from __future__ import annotations
import logging
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .coordinator import ArveConfigEntry, ArveCoordinator
_LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.SENSOR]
async def async_migrate_entry(hass: HomeAssistant, entry: ArveConfigEntry) -> bool:
"""Migrate entry."""
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
if entry.version == 1:
# 1 -> 1.2: Unique ID from integer to string
if entry.minor_version == 1:
minor_version = 2
hass.config_entries.async_update_entry(
entry, unique_id=str(entry.unique_id), minor_version=minor_version
)
_LOGGER.debug("Migration successful")
return True
async def async_setup_entry(hass: HomeAssistant, entry: ArveConfigEntry) -> bool:
"""Set up Arve from a config entry."""

View File

@@ -19,6 +19,9 @@ _LOGGER = logging.getLogger(__name__)
class ArveConfigFlowHandler(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Arve."""
VERSION = 1
MINOR_VERSION = 2
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
@@ -35,7 +38,7 @@ class ArveConfigFlowHandler(ConfigFlow, domain=DOMAIN):
except ArveConnectionError:
errors["base"] = "cannot_connect"
else:
await self.async_set_unique_id(customer.customerId)
await self.async_set_unique_id(str(customer.customerId))
self._abort_if_unique_id_configured()
return self.async_create_entry(
title="Arve",

View File

@@ -2,6 +2,7 @@
from dataclasses import dataclass
from http import HTTPStatus
import logging
import aiohttp
from microBeesPy import MicroBees
@@ -15,6 +16,8 @@ from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN, PLATFORMS
from .coordinator import MicroBeesUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class HomeAssistantMicroBeesData:
@@ -25,6 +28,23 @@ class HomeAssistantMicroBeesData:
session: config_entry_oauth2_flow.OAuth2Session
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate entry."""
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
if entry.version == 1:
# 1 -> 1.2: Unique ID from integer to string
if entry.minor_version == 1:
minor_version = 2
hass.config_entries.async_update_entry(
entry, unique_id=str(entry.unique_id), minor_version=minor_version
)
_LOGGER.debug("Migration successful")
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up microBees from a config entry."""
implementation = (

View File

@@ -19,6 +19,8 @@ class OAuth2FlowHandler(
"""Handle a config flow for microBees."""
DOMAIN = DOMAIN
VERSION = 1
MINOR_VERSION = 2
@property
def logger(self) -> logging.Logger:
@@ -47,7 +49,7 @@ class OAuth2FlowHandler(
self.logger.exception("Unexpected error")
return self.async_abort(reason="unknown")
await self.async_set_unique_id(current_user.id)
await self.async_set_unique_id(str(current_user.id))
if self.source != SOURCE_REAUTH:
self._abort_if_unique_id_configured()
return self.async_create_entry(

View File

@@ -2,6 +2,8 @@
from __future__ import annotations
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
@@ -15,9 +17,28 @@ from .api import AuthenticatedMonzoAPI
from .const import DOMAIN
from .coordinator import MonzoCoordinator
_LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.SENSOR]
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate entry."""
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
if entry.version == 1:
# 1 -> 1.2: Unique ID from integer to string
if entry.minor_version == 1:
minor_version = 2
hass.config_entries.async_update_entry(
entry, unique_id=str(entry.unique_id), minor_version=minor_version
)
_LOGGER.debug("Migration successful")
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Monzo from a config entry."""
implementation = await async_get_config_entry_implementation(hass, entry)

View File

@@ -21,6 +21,8 @@ class MonzoFlowHandler(
"""Handle a config flow."""
DOMAIN = DOMAIN
VERSION = 1
MINOR_VERSION = 2
oauth_data: dict[str, Any]
@@ -51,7 +53,7 @@ class MonzoFlowHandler(
"""Create an entry for the flow."""
self.oauth_data = data
user_id = data[CONF_TOKEN]["user_id"]
await self.async_set_unique_id(user_id)
await self.async_set_unique_id(str(user_id))
if self.source != SOURCE_REAUTH:
self._abort_if_unique_id_configured()
else:

View File

@@ -83,6 +83,14 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
)
return False
if entry.version == 2:
# 2 -> 2.2: Unique ID from integer to string
if entry.minor_version == 1:
minor_version = 2
hass.config_entries.async_update_entry(
entry, unique_id=str(entry.unique_id), minor_version=minor_version
)
return True

View File

@@ -20,6 +20,7 @@ class ToonFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN):
DOMAIN = DOMAIN
VERSION = 2
MINOR_VERSION = 2
agreements: list[Agreement]
data: dict[str, Any]
@@ -92,7 +93,7 @@ class ToonFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN):
if self.migrate_entry:
await self.hass.config_entries.async_remove(self.migrate_entry)
await self.async_set_unique_id(agreement.agreement_id)
await self.async_set_unique_id(str(agreement.agreement_id))
self._abort_if_unique_id_configured()
self.data[CONF_AGREEMENT_ID] = agreement.agreement_id

View File

@@ -27,7 +27,10 @@ def mock_setup_entry() -> Generator[AsyncMock]:
def mock_config_entry(hass: HomeAssistant, mock_arve: MagicMock) -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="Arve", domain=DOMAIN, data=USER_INPUT, unique_id=mock_arve.customer_id
title="Arve",
domain=DOMAIN,
data=USER_INPUT,
unique_id=str(mock_arve.customer_id),
)

View File

@@ -34,7 +34,7 @@ async def test_correct_flow(
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["data"] == USER_INPUT
assert len(mock_setup_entry.mock_calls) == 1
assert result2["result"].unique_id == 12345
assert result2["result"].unique_id == "12345"
async def test_form_cannot_connect(

View File

@@ -0,0 +1,26 @@
"""Tests for the Arve component."""
from unittest.mock import patch
from homeassistant.components.arve.const import DOMAIN
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
"""Test migrating a 1.1 config entry to 1.2."""
with patch("homeassistant.components.arve.async_setup_entry", return_value=True):
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_ACCESS_TOKEN: "mock", CONF_CLIENT_SECRET: "mock"},
version=1,
minor_version=1,
unique_id=12345,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.version == 1
assert entry.minor_version == 2
assert entry.unique_id == "12345"

View File

@@ -59,7 +59,7 @@ def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry:
return MockConfigEntry(
domain=DOMAIN,
title=TITLE,
unique_id=54321,
unique_id="54321",
data={
"auth_implementation": DOMAIN,
"token": {

View File

@@ -74,7 +74,7 @@ async def test_full_flow(
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@microbees.com"
assert "result" in result
assert result["result"].unique_id == 54321
assert result["result"].unique_id == "54321"
assert "token" in result["result"].data
assert result["result"].data["token"]["access_token"] == "mock-access-token"
assert result["result"].data["token"]["refresh_token"] == "mock-refresh-token"
@@ -197,7 +197,7 @@ async def test_config_reauth_wrong_account(
) -> None:
"""Test reauth with wrong account."""
await setup_integration(hass, config_entry)
microbees.return_value.getMyProfile.return_value.id = 12345
microbees.return_value.getMyProfile.return_value.id = "12345"
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"

View File

@@ -0,0 +1,35 @@
"""Tests for the microBees component."""
from unittest.mock import patch
from homeassistant.components.microbees.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
"""Test migrating a 1.1 config entry to 1.2."""
with patch(
"homeassistant.components.microbees.async_setup_entry", return_value=True
):
entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
},
version=1,
minor_version=1,
unique_id=54321,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.version == 1
assert entry.minor_version == 2
assert entry.unique_id == "54321"

View File

@@ -244,7 +244,7 @@ async def test_config_reauth_wrong_account(
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
"user_id": 12346,
"user_id": "12346",
},
)

View File

@@ -1,7 +1,7 @@
"""Tests for component initialisation."""
from datetime import timedelta
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from monzopy import AuthorisationExpiredError
@@ -35,3 +35,29 @@ async def test_api_can_trigger_reauth(
assert flow["step_id"] == "reauth_confirm"
assert flow["handler"] == DOMAIN
assert flow["context"]["source"] == SOURCE_REAUTH
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
"""Test migrating a 1.1 config entry to 1.2."""
with patch("homeassistant.components.monzo.async_setup_entry", return_value=True):
entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
"user_id": "600",
},
},
version=1,
minor_version=1,
unique_id=600,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.version == 1
assert entry.minor_version == 2
assert entry.unique_id == "600"

View File

@@ -213,7 +213,7 @@ async def test_agreement_already_set_up(
) -> None:
"""Test showing display form again if display already exists."""
await setup_component(hass)
MockConfigEntry(domain=DOMAIN, unique_id=123).add_to_hass(hass)
MockConfigEntry(domain=DOMAIN, unique_id="123").add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
@@ -312,7 +312,7 @@ async def test_import_migration(
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test if importing step with migration works."""
old_entry = MockConfigEntry(domain=DOMAIN, unique_id=123, version=1)
old_entry = MockConfigEntry(domain=DOMAIN, unique_id="123", version=1)
old_entry.add_to_hass(hass)
await setup_component(hass)

View File

@@ -40,3 +40,29 @@ async def test_oauth_implementation_not_available(
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_migrate_entry_minor_version_2_2(hass: HomeAssistant) -> None:
"""Test migrating a 2.1 config entry to 2.2."""
with patch("homeassistant.components.toon.async_setup_entry", return_value=True):
entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
"agreement_id": 123,
},
version=2,
minor_version=1,
unique_id=123,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.version == 2
assert entry.minor_version == 2
assert entry.unique_id == "123"