Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove deprecated Mastodon yaml config import #134040

Merged
merged 2 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 2 additions & 35 deletions homeassistant/components/mastodon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassistant.util import slugify

from .const import CONF_BASE_URL, DOMAIN, LOGGER
from .const import CONF_BASE_URL, DOMAIN
from .coordinator import MastodonCoordinator
from .utils import construct_mastodon_username, create_mastodon_client
from .utils import create_mastodon_client

PLATFORMS: list[Platform] = [Platform.NOTIFY, Platform.SENSOR]

Expand Down Expand Up @@ -81,38 +80,6 @@ async def async_unload_entry(hass: HomeAssistant, entry: MastodonConfigEntry) ->
)


async def async_migrate_entry(hass: HomeAssistant, entry: MastodonConfigEntry) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we remove this? I don't know when it was implemented but it should be in a separate PR in that case.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I shouldn't have removed that, got carried away with anything that said migrate.
I've added this back.

"""Migrate old config."""

if entry.version == 1 and entry.minor_version == 1:
# Version 1.1 had the unique_id as client_id, this isn't necessarily unique
LOGGER.debug("Migrating config entry from version %s", entry.version)

try:
_, instance, account = await hass.async_add_executor_job(
setup_mastodon,
entry,
)
except MastodonError as ex:
LOGGER.error("Migration failed with error %s", ex)
return False

hass.config_entries.async_update_entry(
entry,
minor_version=2,
unique_id=slugify(construct_mastodon_username(instance, account)),
)

LOGGER.debug(
"Entry %s successfully migrated to version %s.%s",
entry.entry_id,
entry.version,
entry.minor_version,
)

return True


def setup_mastodon(entry: MastodonConfigEntry) -> tuple[Mastodon, dict, dict]:
"""Get mastodon details."""
client = create_mastodon_client(
Expand Down
50 changes: 2 additions & 48 deletions homeassistant/components/mastodon/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,15 @@
from yarl import URL

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_NAME,
)
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from homeassistant.util import slugify

from .const import CONF_BASE_URL, DEFAULT_URL, DOMAIN, LOGGER
from .const import CONF_BASE_URL, DOMAIN, LOGGER
from .utils import construct_mastodon_username, create_mastodon_client

STEP_USER_DATA_SCHEMA = vol.Schema(
Expand Down Expand Up @@ -130,44 +125,3 @@ async def async_step_user(
)

return self.show_user_form(user_input, errors)

async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Import a config entry from configuration.yaml."""
errors: dict[str, str] | None = None

LOGGER.debug("Importing Mastodon from configuration.yaml")

base_url = base_url_from_url(str(import_data.get(CONF_BASE_URL, DEFAULT_URL)))
client_id = str(import_data.get(CONF_CLIENT_ID))
client_secret = str(import_data.get(CONF_CLIENT_SECRET))
access_token = str(import_data.get(CONF_ACCESS_TOKEN))
name = import_data.get(CONF_NAME)

instance, account, errors = await self.hass.async_add_executor_job(
self.check_connection,
base_url,
client_id,
client_secret,
access_token,
)

if not errors:
name = construct_mastodon_username(instance, account)
await self.async_set_unique_id(slugify(name))
self._abort_if_unique_id_configured()

if not name:
name = construct_mastodon_username(instance, account)

return self.async_create_entry(
title=name,
data={
CONF_BASE_URL: base_url,
CONF_CLIENT_ID: client_id,
CONF_CLIENT_SECRET: client_secret,
CONF_ACCESS_TOKEN: access_token,
},
)

reason = next(iter(errors.items()))[1]
return self.async_abort(reason=reason)
54 changes: 4 additions & 50 deletions homeassistant/components/mastodon/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@
PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from .const import CONF_BASE_URL, DEFAULT_URL, DOMAIN, LOGGER
from .const import CONF_BASE_URL, DEFAULT_URL, LOGGER

ATTR_MEDIA = "media"
ATTR_TARGET = "target"
Expand All @@ -46,51 +44,7 @@ async def async_get_service(
discovery_info: DiscoveryInfoType | None = None,
) -> MastodonNotificationService | None:
"""Get the Mastodon notification service."""

if not discovery_info:
# Import config entry

import_result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=config,
)

if (
import_result["type"] == FlowResultType.ABORT
and import_result["reason"] != "already_configured"
):
ir.async_create_issue(
hass,
DOMAIN,
f"deprecated_yaml_import_issue_{import_result["reason"]}",
breaks_in_ha_version="2025.2.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=ir.IssueSeverity.WARNING,
translation_key=f"deprecated_yaml_import_issue_{import_result["reason"]}",
translation_placeholders={
"domain": DOMAIN,
"integration_title": INTEGRATION_TITLE,
},
)
return None

ir.async_create_issue(
hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
breaks_in_ha_version="2025.2.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=ir.IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={
"domain": DOMAIN,
"integration_title": INTEGRATION_TITLE,
},
)

if discovery_info is None:
return None

client: Mastodon = discovery_info.get("client")
Expand Down
14 changes: 0 additions & 14 deletions homeassistant/components/mastodon/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,6 @@
"unknown": "Unknown error occured when connecting to the Mastodon instance."
}
},
"issues": {
"deprecated_yaml_import_issue_unauthorized_error": {
"title": "YAML import failed due to an authentication error",
"description": "Configuring {integration_title} using YAML is being removed but there was an authentication error while importing your existing configuration.\nPlease use the UI to configure Mastodon. Don't forget to delete the YAML configuration."
},
"deprecated_yaml_import_issue_network_error": {
"title": "YAML import failed because the instance was not found",
"description": "Configuring {integration_title} using YAML is being removed but no instance was found while importing your existing configuration.\nPlease use the UI to configure Mastodon. Don't forget to delete the YAML configuration."
},
"deprecated_yaml_import_issue_unknown": {
"title": "YAML import failed with unknown error",
"description": "Configuring {integration_title} using YAML is being removed but there was an unknown error while importing your existing configuration.\nPlease use the UI to configure Mastodon. Don't forget to delete the YAML configuration."
}
},
"entity": {
"sensor": {
"followers": {
Expand Down
52 changes: 1 addition & 51 deletions tests/components/mastodon/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import pytest

from homeassistant.components.mastodon.const import CONF_BASE_URL, DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
Expand Down Expand Up @@ -160,53 +160,3 @@ async def test_duplicate(

assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"


async def test_import_flow(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test importing yaml config."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_BASE_URL: "https://mastodon.social",
CONF_CLIENT_ID: "import_client_id",
CONF_CLIENT_SECRET: "import_client_secret",
CONF_ACCESS_TOKEN: "import_access_token",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY


@pytest.mark.parametrize(
("exception", "error"),
[
(MastodonNetworkError, "network_error"),
(MastodonUnauthorizedError, "unauthorized_error"),
(Exception, "unknown"),
],
)
async def test_import_flow_abort(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test importing yaml config abort."""
mock_mastodon_client.account_verify_credentials.side_effect = exception

result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_BASE_URL: "https://mastodon.social",
CONF_CLIENT_ID: "import_client_id",
CONF_CLIENT_SECRET: "import_client_secret",
CONF_ACCESS_TOKEN: "import_access_token",
},
)
assert result["type"] is FlowResultType.ABORT
40 changes: 1 addition & 39 deletions tests/components/mastodon/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
from mastodon.Mastodon import MastodonError
from syrupy.assertion import SnapshotAssertion

from homeassistant.components.mastodon.config_flow import MastodonConfigFlow
from homeassistant.components.mastodon.const import CONF_BASE_URL, DOMAIN
from homeassistant.components.mastodon.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr

Expand Down Expand Up @@ -44,39 +42,3 @@ async def test_initialization_failure(
await setup_integration(hass, mock_config_entry)

assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY


async def test_migrate(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
) -> None:
"""Test migration."""
# Setup the config entry
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_BASE_URL: "https://mastodon.social",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
CONF_ACCESS_TOKEN: "access_token",
},
title="@[email protected]",
unique_id="client_id",
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

# Check migration was successful
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.data == {
CONF_BASE_URL: "https://mastodon.social",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
CONF_ACCESS_TOKEN: "access_token",
}
assert config_entry.version == MastodonConfigFlow.VERSION
assert config_entry.minor_version == MastodonConfigFlow.MINOR_VERSION
assert config_entry.unique_id == "trwnh_mastodon_social"