Skip to content

Commit

Permalink
Add clear shopping list button for Cookidoo (#133583)
Browse files Browse the repository at this point in the history
* add clear button

* set clear button to disabled per default

* add actions exception
  • Loading branch information
miaucl authored Dec 25, 2024
1 parent c383b41 commit 60774c6
Show file tree
Hide file tree
Showing 8 changed files with 218 additions and 2 deletions.
2 changes: 1 addition & 1 deletion homeassistant/components/cookidoo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from .coordinator import CookidooConfigEntry, CookidooDataUpdateCoordinator

PLATFORMS: list[Platform] = [Platform.TODO]
PLATFORMS: list[Platform] = [Platform.BUTTON, Platform.TODO]


async def async_setup_entry(hass: HomeAssistant, entry: CookidooConfigEntry) -> bool:
Expand Down
70 changes: 70 additions & 0 deletions homeassistant/components/cookidoo/button.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Support for Cookidoo buttons."""

from collections.abc import Awaitable, Callable
from dataclasses import dataclass

from cookidoo_api import Cookidoo, CookidooException

from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from .coordinator import CookidooConfigEntry, CookidooDataUpdateCoordinator
from .entity import CookidooBaseEntity

PARALLEL_UPDATES = 0


@dataclass(frozen=True, kw_only=True)
class CookidooButtonEntityDescription(ButtonEntityDescription):
"""Describes cookidoo button entity."""

press_fn: Callable[[Cookidoo], Awaitable[None]]


TODO_CLEAR = CookidooButtonEntityDescription(
key="todo_clear",
translation_key="todo_clear",
press_fn=lambda client: client.clear_shopping_list(),
entity_registry_enabled_default=False,
)


async def async_setup_entry(
hass: HomeAssistant,
entry: CookidooConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Cookidoo button entities based on a config entry."""
coordinator = entry.runtime_data

async_add_entities([CookidooButton(coordinator, TODO_CLEAR)])


class CookidooButton(CookidooBaseEntity, ButtonEntity):
"""Defines an Cookidoo button."""

entity_description: CookidooButtonEntityDescription

def __init__(
self,
coordinator: CookidooDataUpdateCoordinator,
description: CookidooButtonEntityDescription,
) -> None:
"""Initialize cookidoo button."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_{description.key}"

async def async_press(self) -> None:
"""Press the button."""
try:
await self.entity_description.press_fn(self.coordinator.cookidoo)
except CookidooException as e:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="button_clear_todo_failed",
) from e
await self.coordinator.async_refresh()
5 changes: 5 additions & 0 deletions homeassistant/components/cookidoo/icons.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
"entity": {
"button": {
"todo_clear": {
"default": "mdi:cart-off"
}
},
"todo": {
"ingredient_list": {
"default": "mdi:cart-plus"
Expand Down
8 changes: 8 additions & 0 deletions homeassistant/components/cookidoo/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
}
},
"entity": {
"button": {
"todo_clear": {
"name": "Clear shopping list and additional purchases"
}
},
"todo": {
"ingredient_list": {
"name": "Shopping list"
Expand All @@ -58,6 +63,9 @@
}
},
"exceptions": {
"button_clear_todo_failed": {
"message": "Failed to clear all items from the Cookidoo shopping list"
},
"todo_save_item_failed": {
"message": "Failed to save {name} to Cookidoo shopping list"
},
Expand Down
1 change: 1 addition & 0 deletions tests/components/cookidoo/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def mock_cookidoo_client() -> Generator[AsyncMock]:
"data"
]
]
client.login.return_value = None
yield client


Expand Down
47 changes: 47 additions & 0 deletions tests/components/cookidoo/snapshots/test_button.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# serializer version: 1
# name: test_all_entities[button.cookidoo_clear_shopping_list_and_additional_purchases-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': None,
'entity_id': 'button.cookidoo_clear_shopping_list_and_additional_purchases',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Clear shopping list and additional purchases',
'platform': 'cookidoo',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'todo_clear',
'unique_id': '01JBVVVJ87F6G5V0QJX6HBC94T_todo_clear',
'unit_of_measurement': None,
})
# ---
# name: test_all_entities[button.cookidoo_clear_shopping_list_and_additional_purchases-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Cookidoo Clear shopping list and additional purchases',
}),
'context': <ANY>,
'entity_id': 'button.cookidoo_clear_shopping_list_and_additional_purchases',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
84 changes: 84 additions & 0 deletions tests/components/cookidoo/test_button.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Tests for the Cookidoo button platform."""

from unittest.mock import AsyncMock, patch

from cookidoo_api import CookidooRequestException
import pytest
from syrupy import SnapshotAssertion

from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er

from . import setup_integration

from tests.common import MockConfigEntry, snapshot_platform


@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_cookidoo_client: AsyncMock,
cookidoo_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.cookidoo.PLATFORMS", [Platform.BUTTON]):
await setup_integration(hass, cookidoo_config_entry)

assert cookidoo_config_entry.state is ConfigEntryState.LOADED

await snapshot_platform(
hass, entity_registry, snapshot, cookidoo_config_entry.entry_id
)


@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_pressing_button(
hass: HomeAssistant,
mock_cookidoo_client: AsyncMock,
cookidoo_config_entry: MockConfigEntry,
) -> None:
"""Test pressing button."""
await setup_integration(hass, cookidoo_config_entry)

await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.cookidoo_clear_shopping_list_and_additional_purchases",
},
blocking=True,
)
mock_cookidoo_client.clear_shopping_list.assert_called_once()


@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_pressing_button_exception(
hass: HomeAssistant,
mock_cookidoo_client: AsyncMock,
cookidoo_config_entry: MockConfigEntry,
) -> None:
"""Test pressing button with exception."""

await setup_integration(hass, cookidoo_config_entry)

assert cookidoo_config_entry.state is ConfigEntryState.LOADED

mock_cookidoo_client.clear_shopping_list.side_effect = CookidooRequestException
with pytest.raises(
HomeAssistantError,
match="Failed to clear all items from the Cookidoo shopping list",
):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.cookidoo_clear_shopping_list_and_additional_purchases",
},
blocking=True,
)
3 changes: 2 additions & 1 deletion tests/components/cookidoo/test_todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ async def test_todo(
) -> None:
"""Snapshot test states of todo platform."""

await setup_integration(hass, cookidoo_config_entry)
with patch("homeassistant.components.cookidoo.PLATFORMS", [Platform.TODO]):
await setup_integration(hass, cookidoo_config_entry)

assert cookidoo_config_entry.state is ConfigEntryState.LOADED

Expand Down

0 comments on commit 60774c6

Please sign in to comment.