init home-assistant
This commit is contained in:
1
home-assistant/tests/components/google_tasks/__init__.py
Normal file
1
home-assistant/tests/components/google_tasks/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Tests for the Google Tasks integration."""
|
||||
141
home-assistant/tests/components/google_tasks/conftest.py
Normal file
141
home-assistant/tests/components/google_tasks/conftest.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Test fixtures for Google Tasks."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from httplib2 import Response
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.application_credentials import (
|
||||
ClientCredential,
|
||||
async_import_client_credential,
|
||||
)
|
||||
from homeassistant.components.google_tasks.const import DOMAIN, OAUTH2_SCOPES
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
CLIENT_ID = "1234"
|
||||
CLIENT_SECRET = "5678"
|
||||
FAKE_ACCESS_TOKEN = "some-access-token"
|
||||
FAKE_REFRESH_TOKEN = "some-refresh-token"
|
||||
FAKE_AUTH_IMPL = "conftest-imported-cred"
|
||||
|
||||
TASK_LIST = {
|
||||
"id": "task-list-id-1",
|
||||
"title": "My tasks",
|
||||
}
|
||||
LIST_TASK_LIST_RESPONSE = {
|
||||
"items": [TASK_LIST],
|
||||
}
|
||||
|
||||
LIST_TASKS_RESPONSE_WATER = {
|
||||
"items": [
|
||||
{
|
||||
"id": "some-task-id",
|
||||
"title": "Water",
|
||||
"status": "needsAction",
|
||||
"description": "Any size is ok",
|
||||
"position": "00000000000000000001",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Fixture to specify platforms to test."""
|
||||
return []
|
||||
|
||||
|
||||
@pytest.fixture(name="expires_at")
|
||||
def mock_expires_at() -> int:
|
||||
"""Fixture to set the oauth token expiration time."""
|
||||
return time.time() + 86400
|
||||
|
||||
|
||||
@pytest.fixture(name="token_entry")
|
||||
def mock_token_entry(expires_at: int) -> dict[str, Any]:
|
||||
"""Fixture for OAuth 'token' data for a ConfigEntry."""
|
||||
return {
|
||||
"access_token": FAKE_ACCESS_TOKEN,
|
||||
"refresh_token": FAKE_REFRESH_TOKEN,
|
||||
"scope": " ".join(OAUTH2_SCOPES),
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(name="config_entry")
|
||||
def mock_config_entry(token_entry: dict[str, Any]) -> MockConfigEntry:
|
||||
"""Fixture for a config entry."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="123",
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": token_entry,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def setup_credentials(hass: HomeAssistant) -> None:
|
||||
"""Fixture to setup credentials."""
|
||||
assert await async_setup_component(hass, "application_credentials", {})
|
||||
await async_import_client_credential(
|
||||
hass,
|
||||
DOMAIN,
|
||||
ClientCredential(CLIENT_ID, CLIENT_SECRET),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="integration_setup")
|
||||
async def mock_integration_setup(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
platforms: list[str],
|
||||
) -> Callable[[], Awaitable[bool]]:
|
||||
"""Fixture to set up the integration."""
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
async def run() -> bool:
|
||||
with patch(f"homeassistant.components.{DOMAIN}.PLATFORMS", platforms):
|
||||
result = await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
return result
|
||||
|
||||
return run
|
||||
|
||||
|
||||
@pytest.fixture(name="api_responses")
|
||||
def mock_api_responses() -> list[dict | list]:
|
||||
"""Fixture forcreate_response_object API responses to return during test."""
|
||||
return []
|
||||
|
||||
|
||||
def create_response_object(api_response: dict | list) -> tuple[Response, bytes]:
|
||||
"""Create an http response."""
|
||||
return (
|
||||
Response({"Content-Type": "application/json"}),
|
||||
json.dumps(api_response).encode(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="response_handler")
|
||||
def mock_response_handler(api_responses: list[dict | list]) -> list:
|
||||
"""Create a mock http2lib response handler."""
|
||||
return [create_response_object(api_response) for api_response in api_responses]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_http_response(response_handler: list | Callable) -> Mock:
|
||||
"""Fixture to fake out http2lib responses."""
|
||||
|
||||
with patch("httplib2.Http.request", side_effect=response_handler) as mock_response:
|
||||
yield mock_response
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"error": {
|
||||
"code": 403,
|
||||
"message": "Google Tasks API has not been used in project 0 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/tasks.googleapis.com/overview?project=0 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
|
||||
"errors": [
|
||||
{
|
||||
"message": "Google Tasks API has not been used in project 0 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/tasks.googleapis.com/overview?project=0 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
|
||||
"domain": "usageLimits",
|
||||
"reason": "accessNotConfigured",
|
||||
"extendedHelp": "https://console.developers.google.com"
|
||||
}
|
||||
],
|
||||
"status": "PERMISSION_DENIED"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
# serializer version: 1
|
||||
# name: test_create_todo_list_item[description]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks?alt=json',
|
||||
'POST',
|
||||
)
|
||||
# ---
|
||||
# name: test_create_todo_list_item[description].1
|
||||
'{"title": "Soda", "status": "needsAction", "due": null, "notes": "6-pack"}'
|
||||
# ---
|
||||
# name: test_create_todo_list_item[due]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks?alt=json',
|
||||
'POST',
|
||||
)
|
||||
# ---
|
||||
# name: test_create_todo_list_item[due].1
|
||||
'{"title": "Soda", "status": "needsAction", "due": "2023-11-18T00:00:00+00:00", "notes": null}'
|
||||
# ---
|
||||
# name: test_create_todo_list_item[summary]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks?alt=json',
|
||||
'POST',
|
||||
)
|
||||
# ---
|
||||
# name: test_create_todo_list_item[summary].1
|
||||
'{"title": "Soda", "status": "needsAction", "due": null, "notes": null}'
|
||||
# ---
|
||||
# name: test_delete_todo_list_item[_handler]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/batch',
|
||||
'POST',
|
||||
)
|
||||
# ---
|
||||
# name: test_move_todo_item[api_responses0]
|
||||
list([
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Water',
|
||||
'uid': 'some-task-id-1',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Milk',
|
||||
'uid': 'some-task-id-2',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Cheese',
|
||||
'uid': 'some-task-id-3',
|
||||
}),
|
||||
])
|
||||
# ---
|
||||
# name: test_move_todo_item[api_responses0].1
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id-3/move?previous=some-task-id-1&alt=json',
|
||||
'POST',
|
||||
)
|
||||
# ---
|
||||
# name: test_move_todo_item[api_responses0].2
|
||||
None
|
||||
# ---
|
||||
# name: test_move_todo_item[api_responses0].3
|
||||
list([
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Water',
|
||||
'uid': 'some-task-id-1',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Cheese',
|
||||
'uid': 'some-task-id-3',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Milk',
|
||||
'uid': 'some-task-id-2',
|
||||
}),
|
||||
])
|
||||
# ---
|
||||
# name: test_parent_child_ordering[api_responses0]
|
||||
list([
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Task 1',
|
||||
'uid': 'task-1',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Task 2',
|
||||
'uid': 'task-2',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Task 3 (Parent)',
|
||||
'uid': 'task-3',
|
||||
}),
|
||||
dict({
|
||||
'status': 'needs_action',
|
||||
'summary': 'Task 4',
|
||||
'uid': 'task-4',
|
||||
}),
|
||||
])
|
||||
# ---
|
||||
# name: test_partial_update[clear_description]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[clear_description].1
|
||||
'{"title": "Water", "status": "needsAction", "due": null, "notes": null}'
|
||||
# ---
|
||||
# name: test_partial_update[clear_due_date]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[clear_due_date].1
|
||||
'{"title": "Water", "status": "needsAction", "due": null, "notes": null}'
|
||||
# ---
|
||||
# name: test_partial_update[description]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[description].1
|
||||
'{"title": "Water", "status": "needsAction", "due": null, "notes": "At least one gallon"}'
|
||||
# ---
|
||||
# name: test_partial_update[due_date]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[due_date].1
|
||||
'{"title": "Water", "status": "needsAction", "due": "2023-11-18T00:00:00+00:00", "notes": null}'
|
||||
# ---
|
||||
# name: test_partial_update[empty_description]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[empty_description].1
|
||||
'{"title": "Water", "status": "needsAction", "due": null, "notes": ""}'
|
||||
# ---
|
||||
# name: test_partial_update[rename]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update[rename].1
|
||||
'{"title": "Soda", "status": "needsAction", "due": null, "notes": null}'
|
||||
# ---
|
||||
# name: test_partial_update_status[api_responses0]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_partial_update_status[api_responses0].1
|
||||
'{"title": "Water", "status": "needsAction", "due": null, "notes": null}'
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-America/Regina]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-America/Regina].1
|
||||
'{"title": "Water", "status": "needsAction", "due": "2024-12-05T00:00:00+00:00", "notes": null}'
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-Asia/Tokyo]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-Asia/Tokyo].1
|
||||
'{"title": "Water", "status": "needsAction", "due": "2024-12-05T00:00:00+00:00", "notes": null}'
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-UTC]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_update_due_date[api_responses0-UTC].1
|
||||
'{"title": "Water", "status": "needsAction", "due": "2024-12-05T00:00:00+00:00", "notes": null}'
|
||||
# ---
|
||||
# name: test_update_todo_list_item[api_responses0]
|
||||
tuple(
|
||||
'https://tasks.googleapis.com/tasks/v1/lists/task-list-id-1/tasks/some-task-id?alt=json',
|
||||
'PATCH',
|
||||
)
|
||||
# ---
|
||||
# name: test_update_todo_list_item[api_responses0].1
|
||||
'{"title": "Soda", "status": "completed", "due": null, "notes": null}'
|
||||
# ---
|
||||
317
home-assistant/tests/components/google_tasks/test_config_flow.py
Normal file
317
home-assistant/tests/components/google_tasks/test_config_flow.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""Test the Google Tasks config flow."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from googleapiclient.errors import HttpError
|
||||
from httplib2 import Response
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.google_tasks.const import (
|
||||
DOMAIN,
|
||||
OAUTH2_AUTHORIZE,
|
||||
OAUTH2_TOKEN,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import config_entry_oauth2_flow
|
||||
|
||||
from tests.common import MockConfigEntry, load_fixture
|
||||
from tests.test_util.aiohttp import AiohttpClientMocker
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
CLIENT_ID = "1234"
|
||||
CLIENT_SECRET = "5678"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_identifier() -> str:
|
||||
"""Return a unique user ID."""
|
||||
return "123"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_userinfo(user_identifier: str) -> Generator[Mock]:
|
||||
"""Set up userinfo."""
|
||||
with patch("homeassistant.components.google_tasks.config_flow.build") as mock:
|
||||
mock.return_value.userinfo.return_value.get.return_value.execute.return_value = {
|
||||
"id": user_identifier,
|
||||
"name": "Test Name",
|
||||
}
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_full_flow(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
setup_credentials,
|
||||
setup_userinfo,
|
||||
) -> None:
|
||||
"""Check full flow."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
"google_tasks", context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
state = config_entry_oauth2_flow._encode_jwt(
|
||||
hass,
|
||||
{
|
||||
"flow_id": result["flow_id"],
|
||||
"redirect_uri": "https://example.com/auth/external/callback",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["url"] == (
|
||||
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
|
||||
"&redirect_uri=https://example.com/auth/external/callback"
|
||||
f"&state={state}"
|
||||
"&scope=https://www.googleapis.com/auth/tasks+"
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
"&access_type=offline&prompt=consent"
|
||||
)
|
||||
|
||||
client = await hass_client_no_auth()
|
||||
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
||||
assert resp.status == 200
|
||||
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
||||
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_tasks.async_setup_entry", return_value=True
|
||||
) as mock_setup:
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["result"].unique_id == "123"
|
||||
assert result["result"].title == "Test Name"
|
||||
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
|
||||
assert len(mock_setup.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_api_not_enabled(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
setup_credentials,
|
||||
setup_userinfo,
|
||||
) -> None:
|
||||
"""Check flow aborts if api is not enabled."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
"google_tasks", context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
state = config_entry_oauth2_flow._encode_jwt(
|
||||
hass,
|
||||
{
|
||||
"flow_id": result["flow_id"],
|
||||
"redirect_uri": "https://example.com/auth/external/callback",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["url"] == (
|
||||
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
|
||||
"&redirect_uri=https://example.com/auth/external/callback"
|
||||
f"&state={state}"
|
||||
"&scope=https://www.googleapis.com/auth/tasks+"
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
"&access_type=offline&prompt=consent"
|
||||
)
|
||||
|
||||
client = await hass_client_no_auth()
|
||||
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
||||
assert resp.status == 200
|
||||
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
||||
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_tasks.config_flow.build",
|
||||
side_effect=HttpError(
|
||||
Response({"status": "403"}),
|
||||
bytes(load_fixture("google_tasks/api_not_enabled_response.json"), "utf-8"),
|
||||
),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "access_not_configured"
|
||||
assert (
|
||||
result["description_placeholders"]["message"]
|
||||
== "Google Tasks API has not been used in project 0 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/tasks.googleapis.com/overview?project=0 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_general_exception(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
setup_credentials,
|
||||
setup_userinfo,
|
||||
) -> None:
|
||||
"""Check flow aborts if exception happens."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
"google_tasks", context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
state = config_entry_oauth2_flow._encode_jwt(
|
||||
hass,
|
||||
{
|
||||
"flow_id": result["flow_id"],
|
||||
"redirect_uri": "https://example.com/auth/external/callback",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["url"] == (
|
||||
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
|
||||
"&redirect_uri=https://example.com/auth/external/callback"
|
||||
f"&state={state}"
|
||||
"&scope=https://www.googleapis.com/auth/tasks+"
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
"&access_type=offline&prompt=consent"
|
||||
)
|
||||
|
||||
client = await hass_client_no_auth()
|
||||
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
||||
assert resp.status == 200
|
||||
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
||||
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_tasks.config_flow.build",
|
||||
side_effect=Exception,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("user_identifier", "abort_reason", "resulting_access_token", "starting_unique_id"),
|
||||
[
|
||||
(
|
||||
"123",
|
||||
"reauth_successful",
|
||||
"updated-access-token",
|
||||
"123",
|
||||
),
|
||||
(
|
||||
"123",
|
||||
"reauth_successful",
|
||||
"updated-access-token",
|
||||
None,
|
||||
),
|
||||
(
|
||||
"345",
|
||||
"wrong_account",
|
||||
"mock-access",
|
||||
"123",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_reauth(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
setup_credentials,
|
||||
setup_userinfo,
|
||||
user_identifier: str,
|
||||
abort_reason: str,
|
||||
resulting_access_token: str,
|
||||
starting_unique_id: str | None,
|
||||
) -> None:
|
||||
"""Test the re-authentication case updates the correct config entry."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id=starting_unique_id,
|
||||
data={
|
||||
"token": {
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access",
|
||||
}
|
||||
},
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
config_entry.async_start_reauth(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
result = flows[0]
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
state = config_entry_oauth2_flow._encode_jwt(
|
||||
hass,
|
||||
{
|
||||
"flow_id": result["flow_id"],
|
||||
"redirect_uri": "https://example.com/auth/external/callback",
|
||||
},
|
||||
)
|
||||
assert result["url"] == (
|
||||
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
|
||||
"&redirect_uri=https://example.com/auth/external/callback"
|
||||
f"&state={state}"
|
||||
"&scope=https://www.googleapis.com/auth/tasks+"
|
||||
"https://www.googleapis.com/auth/userinfo.profile"
|
||||
"&access_type=offline&prompt=consent"
|
||||
)
|
||||
client = await hass_client_no_auth()
|
||||
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
||||
assert resp.status == 200
|
||||
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
||||
|
||||
aioclient_mock.clear_requests()
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "updated-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_tasks.async_setup_entry", return_value=True
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
|
||||
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
|
||||
|
||||
assert result["type"] == "abort"
|
||||
assert result["reason"] == abort_reason
|
||||
|
||||
assert config_entry.unique_id == "123"
|
||||
assert "token" in config_entry.data
|
||||
# Verify access token is refreshed
|
||||
assert config_entry.data["token"]["access_token"] == resulting_access_token
|
||||
assert config_entry.data["token"]["refresh_token"] == "mock-refresh-token"
|
||||
154
home-assistant/tests/components/google_tasks/test_init.py
Normal file
154
home-assistant/tests/components/google_tasks/test_init.py
Normal file
@@ -0,0 +1,154 @@
|
||||
"""Tests for Google Tasks."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
import http
|
||||
from http import HTTPStatus
|
||||
import json
|
||||
import time
|
||||
from unittest.mock import Mock
|
||||
|
||||
from aiohttp import ClientError
|
||||
from httplib2 import Response
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.google_tasks import DOMAIN
|
||||
from homeassistant.components.google_tasks.const import OAUTH2_TOKEN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .conftest import LIST_TASK_LIST_RESPONSE, LIST_TASKS_RESPONSE_WATER
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.test_util.aiohttp import AiohttpClientMocker
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses", [[LIST_TASK_LIST_RESPONSE, LIST_TASKS_RESPONSE_WATER]]
|
||||
)
|
||||
async def test_setup(
|
||||
hass: HomeAssistant,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
config_entry: MockConfigEntry,
|
||||
setup_credentials: None,
|
||||
mock_http_response: Mock,
|
||||
) -> None:
|
||||
"""Test successful setup and unload."""
|
||||
assert config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
|
||||
await integration_setup()
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
await hass.config_entries.async_unload(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
assert not hass.services.async_services().get(DOMAIN)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("expires_at", [time.time() - 86400], ids=["expired"])
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses", [[LIST_TASK_LIST_RESPONSE, LIST_TASKS_RESPONSE_WATER]]
|
||||
)
|
||||
async def test_expired_token_refresh_success(
|
||||
hass: HomeAssistant,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_entry: MockConfigEntry,
|
||||
setup_credentials: None,
|
||||
mock_http_response: Mock,
|
||||
) -> None:
|
||||
"""Test expired token is refreshed."""
|
||||
|
||||
aioclient_mock.clear_requests()
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"access_token": "updated-access-token",
|
||||
"refresh_token": "updated-refresh-token",
|
||||
"expires_at": time.time() + 86400,
|
||||
"expires_in": 86400,
|
||||
},
|
||||
)
|
||||
|
||||
await integration_setup()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
assert config_entry.data["token"]["access_token"] == "updated-access-token"
|
||||
assert config_entry.data["token"]["expires_in"] == 86400
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("expires_at", "status", "exc", "expected_state"),
|
||||
[
|
||||
(
|
||||
time.time() - 86400,
|
||||
http.HTTPStatus.UNAUTHORIZED,
|
||||
None,
|
||||
ConfigEntryState.SETUP_ERROR,
|
||||
),
|
||||
(
|
||||
time.time() - 86400,
|
||||
http.HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
None,
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
),
|
||||
(
|
||||
time.time() - 86400,
|
||||
None,
|
||||
ClientError("error"),
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
),
|
||||
],
|
||||
ids=["unauthorized", "internal_server_error", "client_error"],
|
||||
)
|
||||
async def test_expired_token_refresh_failure(
|
||||
hass: HomeAssistant,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_entry: MockConfigEntry,
|
||||
setup_credentials: None,
|
||||
status: http.HTTPStatus | None,
|
||||
exc: Exception | None,
|
||||
expected_state: ConfigEntryState,
|
||||
) -> None:
|
||||
"""Test failure while refreshing token with a transient error."""
|
||||
|
||||
aioclient_mock.clear_requests()
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
status=status,
|
||||
exc=exc,
|
||||
)
|
||||
|
||||
await integration_setup()
|
||||
|
||||
assert config_entry.state is expected_state
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"response_handler",
|
||||
[
|
||||
([(Response({"status": HTTPStatus.INTERNAL_SERVER_ERROR}), b"")]),
|
||||
# First request succeeds, second request fails
|
||||
(
|
||||
[
|
||||
(
|
||||
Response({"status": HTTPStatus.OK}),
|
||||
json.dumps(LIST_TASK_LIST_RESPONSE),
|
||||
),
|
||||
(Response({"status": HTTPStatus.INTERNAL_SERVER_ERROR}), b""),
|
||||
]
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_setup_error(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Mock,
|
||||
config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test an error returned by the server when setting up the platform."""
|
||||
|
||||
assert not await integration_setup()
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
968
home-assistant/tests/components/google_tasks/test_todo.py
Normal file
968
home-assistant/tests/components/google_tasks/test_todo.py
Normal file
@@ -0,0 +1,968 @@
|
||||
"""Tests for Google Tasks todo platform."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from http import HTTPStatus
|
||||
import json
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from httplib2 import Response
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.google_tasks.coordinator import UPDATE_INTERVAL
|
||||
from homeassistant.components.todo import (
|
||||
ATTR_DESCRIPTION,
|
||||
ATTR_DUE_DATE,
|
||||
ATTR_ITEM,
|
||||
ATTR_RENAME,
|
||||
ATTR_STATUS,
|
||||
DOMAIN as TODO_DOMAIN,
|
||||
TodoServices,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from .conftest import (
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
create_response_object,
|
||||
)
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
from tests.typing import WebSocketGenerator
|
||||
|
||||
ENTITY_ID = "todo.my_tasks"
|
||||
EMPTY_RESPONSE = {}
|
||||
LIST_TASKS_RESPONSE = {
|
||||
"items": [],
|
||||
}
|
||||
ERROR_RESPONSE = {
|
||||
"error": {
|
||||
"code": 400,
|
||||
"message": "Invalid task ID",
|
||||
"errors": [
|
||||
{"message": "Invalid task ID", "domain": "global", "reason": "invalid"}
|
||||
],
|
||||
}
|
||||
}
|
||||
CONTENT_ID = "Content-ID"
|
||||
BOUNDARY = "batch_00972cc8-75bd-11ee-9692-0242ac110002" # Arbitrary uuid
|
||||
|
||||
LIST_TASKS_RESPONSE_MULTIPLE = {
|
||||
"items": [
|
||||
{
|
||||
"id": "some-task-id-2",
|
||||
"title": "Milk",
|
||||
"status": "needsAction",
|
||||
"position": "00000000000000000002",
|
||||
},
|
||||
{
|
||||
"id": "some-task-id-1",
|
||||
"title": "Water",
|
||||
"status": "needsAction",
|
||||
"position": "00000000000000000001",
|
||||
},
|
||||
{
|
||||
"id": "some-task-id-3",
|
||||
"title": "Cheese",
|
||||
"status": "needsAction",
|
||||
"position": "00000000000000000003",
|
||||
},
|
||||
],
|
||||
}
|
||||
LIST_TASKS_RESPONSE_REORDER = {
|
||||
"items": [
|
||||
{
|
||||
"id": "some-task-id-2",
|
||||
"title": "Milk",
|
||||
"status": "needsAction",
|
||||
"position": "00000000000000000002",
|
||||
},
|
||||
{
|
||||
"id": "some-task-id-1",
|
||||
"title": "Water",
|
||||
"status": "needsAction",
|
||||
"position": "00000000000000000001",
|
||||
},
|
||||
# Task 3 moved after task 1
|
||||
{
|
||||
"id": "some-task-id-3",
|
||||
"title": "Cheese",
|
||||
"status": "needsAction",
|
||||
"position": "000000000000000000011",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
# API responses when testing update methods
|
||||
UPDATE_API_RESPONSES = [
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
EMPTY_RESPONSE, # update
|
||||
LIST_TASKS_RESPONSE, # refresh after update
|
||||
]
|
||||
CREATE_API_RESPONSES = [
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE,
|
||||
EMPTY_RESPONSE, # create
|
||||
LIST_TASKS_RESPONSE, # refresh
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[str]:
|
||||
"""Fixture to specify platforms to test."""
|
||||
return [Platform.TODO]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def ws_get_items(
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
) -> Callable[[], Awaitable[dict[str, str]]]:
|
||||
"""Fixture to fetch items from the todo websocket."""
|
||||
|
||||
async def get() -> list[dict[str, str]]:
|
||||
# Fetch items using To-do platform
|
||||
client = await hass_ws_client()
|
||||
await client.send_json_auto_id(
|
||||
{
|
||||
"type": "todo/item/list",
|
||||
"entity_id": ENTITY_ID,
|
||||
}
|
||||
)
|
||||
resp = await client.receive_json()
|
||||
assert resp.get("success")
|
||||
return resp.get("result", {}).get("items", [])
|
||||
|
||||
return get
|
||||
|
||||
|
||||
def create_batch_response_object(
|
||||
content_ids: list[str], api_responses: list[dict | list | Response | None]
|
||||
) -> tuple[Response, bytes]:
|
||||
"""Create a batch response in the multipart/mixed format."""
|
||||
assert len(api_responses) == len(content_ids)
|
||||
content = []
|
||||
for api_response in api_responses:
|
||||
status = 200
|
||||
body = ""
|
||||
if isinstance(api_response, Response):
|
||||
status = api_response.status
|
||||
elif api_response is not None:
|
||||
body = json.dumps(api_response)
|
||||
content.extend(
|
||||
[
|
||||
f"--{BOUNDARY}",
|
||||
"Content-Type: application/http",
|
||||
f"{CONTENT_ID}: {content_ids.pop()}",
|
||||
"",
|
||||
f"HTTP/1.1 {status} OK",
|
||||
"Content-Type: application/json; charset=UTF-8",
|
||||
"",
|
||||
body,
|
||||
]
|
||||
)
|
||||
content.append(f"--{BOUNDARY}--")
|
||||
body = ("\r\n".join(content)).encode()
|
||||
return (
|
||||
Response(
|
||||
{
|
||||
"Content-Type": f"multipart/mixed; boundary={BOUNDARY}",
|
||||
"Content-ID": "1",
|
||||
}
|
||||
),
|
||||
body,
|
||||
)
|
||||
|
||||
|
||||
def create_batch_response_handler(
|
||||
api_responses: list[dict | list | Response | None],
|
||||
) -> Callable[[Any], tuple[Response, bytes]]:
|
||||
"""Create a fake http2lib response handler that supports generating batch responses.
|
||||
|
||||
Multi-part response objects are dynamically generated since they
|
||||
need to match the Content-ID of the incoming request.
|
||||
"""
|
||||
|
||||
def _handler(url, method, **kwargs) -> tuple[Response, bytes]:
|
||||
next_api_response = api_responses.pop(0)
|
||||
if method == "POST" and (body := kwargs.get("body")):
|
||||
content_ids = [
|
||||
line[len(CONTENT_ID) + 2 :]
|
||||
for line in body.splitlines()
|
||||
if line.startswith(f"{CONTENT_ID}:")
|
||||
]
|
||||
if content_ids:
|
||||
return create_batch_response_object(content_ids, next_api_response)
|
||||
return create_response_object(next_api_response)
|
||||
|
||||
return _handler
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_http_response(mock_http_response: Mock) -> None:
|
||||
"""Fixture to load the http response mock."""
|
||||
return
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timezone", ["America/Regina", "UTC", "Asia/Tokyo"])
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "task-1",
|
||||
"title": "Task 1",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000001",
|
||||
"due": "2023-11-18T00:00:00Z",
|
||||
},
|
||||
{
|
||||
"id": "task-2",
|
||||
"title": "Task 2",
|
||||
"status": "completed",
|
||||
"position": "0000000000000002",
|
||||
"notes": "long description",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_get_items(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
ws_get_items: Callable[[], Awaitable[dict[str, str]]],
|
||||
timezone: str,
|
||||
) -> None:
|
||||
"""Test getting todo list items."""
|
||||
await hass.config.async_set_time_zone(timezone)
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
await hass_ws_client(hass)
|
||||
|
||||
items = await ws_get_items()
|
||||
assert items == [
|
||||
{
|
||||
"uid": "task-1",
|
||||
"summary": "Task 1",
|
||||
"status": "needs_action",
|
||||
"due": "2023-11-18",
|
||||
},
|
||||
{
|
||||
"uid": "task-2",
|
||||
"summary": "Task 2",
|
||||
"status": "completed",
|
||||
"description": "long description",
|
||||
},
|
||||
]
|
||||
|
||||
# State reflect that one task needs action
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE,
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_empty_todo_list(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
ws_get_items: Callable[[], Awaitable[dict[str, str]]],
|
||||
) -> None:
|
||||
"""Test getting todo list items."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
await hass_ws_client(hass)
|
||||
|
||||
items = await ws_get_items()
|
||||
assert items == []
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "0"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
ERROR_RESPONSE, # Fail after one update interval
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_task_items_error_response(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test an error while the entity updates getting a new list of todo list items."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
# Test successful setup and first data fetch
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
# Next update fails
|
||||
freezer.tick(UPDATE_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
# Next update succeeds
|
||||
freezer.tick(UPDATE_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("api_responses", "item_data"),
|
||||
[
|
||||
(CREATE_API_RESPONSES, {}),
|
||||
(CREATE_API_RESPONSES, {ATTR_DUE_DATE: "2023-11-18"}),
|
||||
(CREATE_API_RESPONSES, {ATTR_DESCRIPTION: "6-pack"}),
|
||||
],
|
||||
ids=["summary", "due", "description"],
|
||||
)
|
||||
async def test_create_todo_list_item(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Mock,
|
||||
item_data: dict[str, Any],
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for creating a To-do Item."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "0"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.ADD_ITEM,
|
||||
{ATTR_ITEM: "Soda", **item_data},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
ERROR_RESPONSE,
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_create_todo_list_item_error(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Mock,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for an error response when creating a To-do Item."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="Invalid task ID"):
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.ADD_ITEM,
|
||||
{ATTR_ITEM: "Soda"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_responses", [UPDATE_API_RESPONSES])
|
||||
async def test_update_todo_list_item(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for updating a To-do Item."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: "some-task-id", ATTR_RENAME: "Soda", ATTR_STATUS: "completed"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timezone", ["America/Regina", "UTC", "Asia/Tokyo"])
|
||||
@pytest.mark.parametrize("api_responses", [UPDATE_API_RESPONSES])
|
||||
async def test_update_due_date(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
timezone: str,
|
||||
) -> None:
|
||||
"""Test for updating the due date of a To-do item and timezone."""
|
||||
await hass.config.async_set_time_zone(timezone)
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: "some-task-id", ATTR_DUE_DATE: "2024-12-5"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
ERROR_RESPONSE, # update fails
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_update_todo_list_item_error(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for an error response when updating a To-do Item."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="Invalid task ID"):
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: "some-task-id", ATTR_RENAME: "Soda", ATTR_STATUS: "completed"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("api_responses", "item_data"),
|
||||
[
|
||||
(UPDATE_API_RESPONSES, {ATTR_RENAME: "Soda"}),
|
||||
(UPDATE_API_RESPONSES, {ATTR_DUE_DATE: "2023-11-18"}),
|
||||
(UPDATE_API_RESPONSES, {ATTR_DUE_DATE: None}),
|
||||
(UPDATE_API_RESPONSES, {ATTR_DESCRIPTION: "At least one gallon"}),
|
||||
(UPDATE_API_RESPONSES, {ATTR_DESCRIPTION: ""}),
|
||||
(UPDATE_API_RESPONSES, {ATTR_DESCRIPTION: None}),
|
||||
],
|
||||
ids=(
|
||||
"rename",
|
||||
"due_date",
|
||||
"clear_due_date",
|
||||
"description",
|
||||
"empty_description",
|
||||
"clear_description",
|
||||
),
|
||||
)
|
||||
async def test_partial_update(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
item_data: dict[str, Any],
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for partial update with title only."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: "some-task-id", **item_data},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_responses", [UPDATE_API_RESPONSES])
|
||||
async def test_partial_update_status(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for partial update with status only."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "1"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: "some-task-id", ATTR_STATUS: "needs_action"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"response_handler",
|
||||
[
|
||||
(
|
||||
create_batch_response_handler(
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_MULTIPLE,
|
||||
[None, None, None], # Delete batch empty responses
|
||||
LIST_TASKS_RESPONSE, # refresh after delete
|
||||
]
|
||||
)
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_delete_todo_list_item(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for deleting multiple To-do Items."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.REMOVE_ITEM,
|
||||
{ATTR_ITEM: ["some-task-id-1", "some-task-id-2", "some-task-id-3"]},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"response_handler",
|
||||
[
|
||||
(
|
||||
create_batch_response_handler(
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_MULTIPLE,
|
||||
[
|
||||
EMPTY_RESPONSE,
|
||||
ERROR_RESPONSE, # one item is a failure
|
||||
EMPTY_RESPONSE,
|
||||
],
|
||||
LIST_TASKS_RESPONSE, # refresh after create
|
||||
]
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
async def test_delete_partial_failure(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for partial failure when deleting multiple To-do Items."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="Invalid task ID"):
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.REMOVE_ITEM,
|
||||
{ATTR_ITEM: ["some-task-id-1", "some-task-id-2", "some-task-id-3"]},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"response_handler",
|
||||
[
|
||||
(
|
||||
create_batch_response_handler(
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_MULTIPLE,
|
||||
[
|
||||
"1234-invalid-json",
|
||||
],
|
||||
]
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
async def test_delete_invalid_json_response(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test delete with an invalid json response."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="unexpected response"):
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.REMOVE_ITEM,
|
||||
{ATTR_ITEM: ["some-task-id-1"]},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"response_handler",
|
||||
[
|
||||
(
|
||||
create_batch_response_handler(
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_MULTIPLE,
|
||||
[Response({"status": HTTPStatus.INTERNAL_SERVER_ERROR})],
|
||||
]
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
async def test_delete_server_error(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test delete with an invalid json response."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="responded with error"):
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.REMOVE_ITEM,
|
||||
{ATTR_ITEM: ["some-task-id-1"]},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "task-3-2",
|
||||
"title": "Child 2",
|
||||
"status": "needsAction",
|
||||
"parent": "task-3",
|
||||
"position": "0000000000000002",
|
||||
},
|
||||
{
|
||||
"id": "task-3",
|
||||
"title": "Task 3 (Parent)",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000003",
|
||||
},
|
||||
{
|
||||
"id": "task-2",
|
||||
"title": "Task 2",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000002",
|
||||
},
|
||||
{
|
||||
"id": "task-1",
|
||||
"title": "Task 1",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000001",
|
||||
},
|
||||
{
|
||||
"id": "task-3-1",
|
||||
"title": "Child 1",
|
||||
"status": "needsAction",
|
||||
"parent": "task-3",
|
||||
"position": "0000000000000001",
|
||||
},
|
||||
{
|
||||
"id": "task-4",
|
||||
"title": "Task 4",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000004",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_parent_child_ordering(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
ws_get_items: Callable[[], Awaitable[dict[str, str]]],
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test getting todo list items."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get("todo.my_tasks")
|
||||
assert state
|
||||
assert state.state == "4"
|
||||
|
||||
items = await ws_get_items()
|
||||
assert items == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_MULTIPLE,
|
||||
EMPTY_RESPONSE, # move
|
||||
LIST_TASKS_RESPONSE_REORDER, # refresh after move
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_move_todo_item(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
ws_get_items: Callable[[], Awaitable[dict[str, str]]],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
mock_http_response: Any,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test for re-ordering a To-do Item."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
items = await ws_get_items()
|
||||
assert items == snapshot
|
||||
|
||||
# Move to second in the list
|
||||
client = await hass_ws_client()
|
||||
data = {
|
||||
"id": id,
|
||||
"type": "todo/item/move",
|
||||
"entity_id": ENTITY_ID,
|
||||
"uid": "some-task-id-3",
|
||||
"previous_uid": "some-task-id-1",
|
||||
}
|
||||
await client.send_json_auto_id(data)
|
||||
resp = await client.receive_json()
|
||||
assert resp.get("success")
|
||||
|
||||
assert len(mock_http_response.call_args_list) == 4
|
||||
call = mock_http_response.call_args_list[2]
|
||||
assert call
|
||||
assert call.args == snapshot
|
||||
assert call.kwargs.get("body") == snapshot
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state
|
||||
assert state.state == "3"
|
||||
|
||||
items = await ws_get_items()
|
||||
assert items == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"api_responses",
|
||||
[
|
||||
[
|
||||
LIST_TASK_LIST_RESPONSE,
|
||||
LIST_TASKS_RESPONSE_WATER,
|
||||
EMPTY_RESPONSE, # update
|
||||
# refresh after update
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "some-task-id",
|
||||
"title": "Milk",
|
||||
"status": "needsAction",
|
||||
"position": "0000000000000001",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_susbcribe(
|
||||
hass: HomeAssistant,
|
||||
setup_credentials: None,
|
||||
integration_setup: Callable[[], Awaitable[bool]],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
) -> None:
|
||||
"""Test subscribing to item updates."""
|
||||
|
||||
assert await integration_setup()
|
||||
|
||||
# Subscribe and get the initial list
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json_auto_id(
|
||||
{
|
||||
"type": "todo/item/subscribe",
|
||||
"entity_id": "todo.my_tasks",
|
||||
}
|
||||
)
|
||||
msg = await client.receive_json()
|
||||
assert msg["success"]
|
||||
assert msg["result"] is None
|
||||
subscription_id = msg["id"]
|
||||
|
||||
msg = await client.receive_json()
|
||||
assert msg["id"] == subscription_id
|
||||
assert msg["type"] == "event"
|
||||
items = msg["event"].get("items")
|
||||
assert items
|
||||
assert len(items) == 1
|
||||
assert items[0]["summary"] == "Water"
|
||||
assert items[0]["status"] == "needs_action"
|
||||
uid = items[0]["uid"]
|
||||
assert uid
|
||||
|
||||
# Rename item
|
||||
await hass.services.async_call(
|
||||
TODO_DOMAIN,
|
||||
TodoServices.UPDATE_ITEM,
|
||||
{ATTR_ITEM: uid, ATTR_RENAME: "Milk"},
|
||||
target={ATTR_ENTITY_ID: "todo.my_tasks"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
# Verify update is published
|
||||
msg = await client.receive_json()
|
||||
assert msg["id"] == subscription_id
|
||||
assert msg["type"] == "event"
|
||||
items = msg["event"].get("items")
|
||||
assert items
|
||||
assert len(items) == 1
|
||||
assert items[0]["summary"] == "Milk"
|
||||
assert items[0]["status"] == "needs_action"
|
||||
assert "uid" in items[0]
|
||||
Reference in New Issue
Block a user