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

Add tests for Bring integration #123087

Merged
merged 3 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 16 additions & 2 deletions tests/components/bring/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
from collections.abc import Generator
from typing import cast
from unittest.mock import AsyncMock, patch
import uuid

from bring_api.types import BringAuthResponse
import pytest

from homeassistant.components.bring import DOMAIN
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD

from tests.common import MockConfigEntry
from tests.common import MockConfigEntry, load_json_object_fixture

EMAIL = "test-email"
PASSWORD = "test-password"
Expand Down Expand Up @@ -43,10 +44,23 @@ def mock_bring_client() -> Generator[AsyncMock]:
client = mock_client.return_value
client.uuid = UUID
client.login.return_value = cast(BringAuthResponse, {"name": "Bring"})
client.load_lists.return_value = {"lists": []}
client.load_lists.return_value = load_json_object_fixture("lists.json", DOMAIN)
client.get_list.return_value = load_json_object_fixture("items.json", DOMAIN)
yield client


@pytest.fixture
def mock_uuid() -> Generator[AsyncMock]:
"""Mock uuid."""

with patch(
"homeassistant.components.bring.todo.uuid.uuid4",
autospec=True,
) as mock_client:
mock_client.return_value = uuid.UUID("b669ad23-606a-4652-b302-995d34b1cb1c")
yield mock_client


@pytest.fixture(name="bring_config_entry")
def mock_bring_config_entry() -> MockConfigEntry:
"""Mock bring configuration entry."""
Expand Down
26 changes: 26 additions & 0 deletions tests/components/bring/fixtures/items.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"uuid": "77a151f8-77c4-47a3-8295-c750a0e69d4f",
"status": "REGISTERED",
"purchase": [
{
"uuid": "b5d0790b-5f32-4d5c-91da-e29066f167de",
"itemId": "Paprika",
"specification": "Rot",
"attributes": []
},
{
"uuid": "72d370ab-d8ca-4e41-b956-91df94795b4e",
"itemId": "Pouletbrüstli",
"specification": "Bio",
"attributes": []
}
],
"recently": [
{
"uuid": "fc8db30a-647e-4e6c-9d71-3b85d6a2d954",
"itemId": "Ananas",
"specification": "",
"attributes": []
}
]
}
14 changes: 14 additions & 0 deletions tests/components/bring/fixtures/lists.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"lists": [
{
"listUuid": "e542eef6-dba7-4c31-a52c-29e6ab9d83a5",
"name": "Einkauf",
"theme": "ch.publisheria.bring.theme.home"
},
{
"listUuid": "b4776778-7f6c-496e-951b-92a35d3db0dd",
"name": "Baumarkt",
"theme": "ch.publisheria.bring.theme.home"
}
]
}
95 changes: 95 additions & 0 deletions tests/components/bring/snapshots/test_todo.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# serializer version: 1
# name: test_todo[todo.baumarkt-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'todo',
'entity_category': None,
'entity_id': 'todo.baumarkt',
'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': 'Baumarkt',
'platform': 'bring',
'previous_unique_id': None,
'supported_features': <TodoListEntityFeature: 71>,
'translation_key': 'shopping_list',
'unique_id': '00000000-00000000-00000000-00000000_b4776778-7f6c-496e-951b-92a35d3db0dd',
'unit_of_measurement': None,
})
# ---
# name: test_todo[todo.baumarkt-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Baumarkt',
'supported_features': <TodoListEntityFeature: 71>,
}),
'context': <ANY>,
'entity_id': 'todo.baumarkt',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2',
})
# ---
# name: test_todo[todo.einkauf-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'todo',
'entity_category': None,
'entity_id': 'todo.einkauf',
'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': 'Einkauf',
'platform': 'bring',
'previous_unique_id': None,
'supported_features': <TodoListEntityFeature: 71>,
'translation_key': 'shopping_list',
'unique_id': '00000000-00000000-00000000-00000000_e542eef6-dba7-4c31-a52c-29e6ab9d83a5',
'unit_of_measurement': None,
})
# ---
# name: test_todo[todo.einkauf-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Einkauf',
'supported_features': <TodoListEntityFeature: 71>,
}),
'context': <ANY>,
'entity_id': 'todo.einkauf',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2',
})
# ---
45 changes: 42 additions & 3 deletions tests/components/bring/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ async def setup_integration(
await hass.async_block_till_done()


@pytest.mark.usefixtures("mock_bring_client")
async def test_load_unload(
hass: HomeAssistant,
mock_bring_client: AsyncMock,
bring_config_entry: MockConfigEntry,
) -> None:
"""Test loading and unloading of the config entry."""
Expand Down Expand Up @@ -58,7 +58,7 @@ async def test_init_failure(
mock_bring_client: AsyncMock,
status: ConfigEntryState,
exception: Exception,
bring_config_entry: MockConfigEntry | None,
bring_config_entry: MockConfigEntry,
) -> None:
"""Test an initialization error on integration load."""
mock_bring_client.login.side_effect = exception
Expand All @@ -79,11 +79,50 @@ async def test_init_exceptions(
mock_bring_client: AsyncMock,
exception: Exception,
expected: Exception,
bring_config_entry: MockConfigEntry | None,
bring_config_entry: MockConfigEntry,
) -> None:
"""Test an initialization error on integration load."""
bring_config_entry.add_to_hass(hass)
mock_bring_client.login.side_effect = exception

with pytest.raises(expected):
await async_setup_entry(hass, bring_config_entry)


@pytest.mark.parametrize("exception", [BringRequestException, BringParseException])
@pytest.mark.parametrize("bring_method", ["load_lists", "get_list"])
async def test_config_entry_not_ready(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
exception: Exception,
bring_method: str,
) -> None:
"""Test config entry not ready."""
getattr(mock_bring_client, bring_method).side_effect = exception
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()

assert bring_config_entry.state is ConfigEntryState.SETUP_RETRY


@pytest.mark.parametrize(
"exception", [None, BringAuthException, BringRequestException, BringParseException]
)
async def test_config_entry_not_ready_auth_error(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
exception: Exception | None,
) -> None:
"""Test config entry not ready from authentication error."""

mock_bring_client.load_lists.side_effect = BringAuthException
mock_bring_client.retrieve_new_access_token.side_effect = exception

bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()

assert bring_config_entry.state is ConfigEntryState.SETUP_RETRY
106 changes: 106 additions & 0 deletions tests/components/bring/test_notification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Test todo entity notification action of the Bring! integration."""

import re
from unittest.mock import AsyncMock

from bring_api import BringNotificationType, BringRequestException
import pytest

from homeassistant.components.bring.const import (
ATTR_ITEM_NAME,
ATTR_NOTIFICATION_TYPE,
DOMAIN,
SERVICE_PUSH_NOTIFICATION,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError

from tests.common import MockConfigEntry


async def test_send_notification(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
) -> None:
"""Test send bring push notification."""

bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()

assert bring_config_entry.state is ConfigEntryState.LOADED

await hass.services.async_call(
DOMAIN,
SERVICE_PUSH_NOTIFICATION,
service_data={
ATTR_NOTIFICATION_TYPE: "GOING_SHOPPING",
},
target={ATTR_ENTITY_ID: "todo.einkauf"},
blocking=True,
)

mock_bring_client.notify.assert_called_once_with(
"e542eef6-dba7-4c31-a52c-29e6ab9d83a5",
BringNotificationType.GOING_SHOPPING,
None,
)


async def test_send_notification_exception(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
) -> None:
"""Test send bring push notification with exception."""

bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()

assert bring_config_entry.state is ConfigEntryState.LOADED
mock_bring_client.notify.side_effect = BringRequestException
with pytest.raises(
HomeAssistantError,
match="Failed to send push notification for bring due to a connection error, try again later",
):
await hass.services.async_call(
DOMAIN,
SERVICE_PUSH_NOTIFICATION,
service_data={
ATTR_NOTIFICATION_TYPE: "GOING_SHOPPING",
},
target={ATTR_ENTITY_ID: "todo.einkauf"},
blocking=True,
)


async def test_send_notification_service_validation_error(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
) -> None:
"""Test send bring push notification."""

bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()

assert bring_config_entry.state is ConfigEntryState.LOADED
mock_bring_client.notify.side_effect = ValueError
with pytest.raises(
HomeAssistantError,
match=re.escape(
"Failed to perform action bring.send_message. 'URGENT_MESSAGE' requires a value @ data['item']. Got None"
Copy link
Member

Choose a reason for hiding this comment

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

Please break long strings around max 88 characters per line.

),
):
await hass.services.async_call(
DOMAIN,
SERVICE_PUSH_NOTIFICATION,
service_data={ATTR_NOTIFICATION_TYPE: "URGENT_MESSAGE", ATTR_ITEM_NAME: ""},
target={ATTR_ENTITY_ID: "todo.einkauf"},
blocking=True,
)
Loading