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 service response and exception handling to Habitica service #116430

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
69 changes: 41 additions & 28 deletions homeassistant/components/habitica/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,38 @@

import logging

from aiohttp import ClientResponseError
from habitipy.aio import HabitipyAsync
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_NAME,
CONF_API_KEY,
CONF_NAME,
CONF_SENSORS,
CONF_URL,
Platform,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
)
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.selector import ConfigEntrySelector
from homeassistant.helpers.typing import ConfigType

from .const import (
ATTR_ARGS,
ATTR_DATA,
ATTR_CONFIG_ENTRY,
ATTR_PATH,
CONF_API_USER,
DEFAULT_URL,
DOMAIN,
EVENT_API_CALL_SUCCESS,
SERVICE_API_CALL,
)

Expand Down Expand Up @@ -80,7 +86,7 @@ def has_all_unique_users_names(value):

SERVICE_API_CALL_SCHEMA = vol.Schema(
{
vol.Required(ATTR_NAME): str,
vol.Required(ATTR_CONFIG_ENTRY): ConfigEntrySelector(),
vol.Required(ATTR_PATH): vol.All(cv.ensure_list, [str]),
vol.Optional(ATTR_ARGS): dict,
}
Expand Down Expand Up @@ -113,31 +119,34 @@ class HAHabitipyAsync(HabitipyAsync):
def __call__(self, **kwargs):
return super().__call__(websession, **kwargs)

async def handle_api_call(call: ServiceCall) -> None:
name = call.data[ATTR_NAME]
async def handle_api_call(call: ServiceCall) -> ServiceResponse:
path = call.data[ATTR_PATH]
entries = hass.config_entries.async_entries(DOMAIN)
api = None
for entry in entries:
if entry.data[CONF_NAME] == name:
api = hass.data[DOMAIN].get(entry.entry_id)
break
if api is None:
_LOGGER.error("API_CALL: User '%s' not configured", name)
return
try:
for element in path:
entry_id: str = call.data[ATTR_CONFIG_ENTRY]

api = hass.data[DOMAIN][entry_id]

for element in path:
try:
api = api[element]
except KeyError:
_LOGGER.error(
"API_CALL: Path %s is invalid for API on '{%s}' element", path, element
)
return
except (KeyError, IndexError) as e:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="sevice_invalid_path",
translation_placeholders={
"service": f"{DOMAIN}.{SERVICE_API_CALL}",
"path": "/".join(path),
"element": element,
},
) from e

kwargs = call.data.get(ATTR_ARGS, {})
data = await api(**kwargs)
hass.bus.async_fire(
EVENT_API_CALL_SUCCESS, {ATTR_NAME: name, ATTR_PATH: path, ATTR_DATA: data}
)

try:
data = await api(**kwargs)
except (ValueError, TypeError, ClientResponseError) as e:
raise HomeAssistantError(e) from e

return {"data": data}

data = hass.data.setdefault(DOMAIN, {})
config = entry.data
Expand All @@ -161,7 +170,11 @@ async def handle_api_call(call: ServiceCall) -> None:

if not hass.services.has_service(DOMAIN, SERVICE_API_CALL):
hass.services.async_register(
DOMAIN, SERVICE_API_CALL, handle_api_call, schema=SERVICE_API_CALL_SCHEMA
DOMAIN,
SERVICE_API_CALL,
handle_api_call,
schema=SERVICE_API_CALL_SCHEMA,
supports_response=SupportsResponse.OPTIONAL,
)

return True
Expand Down
5 changes: 1 addition & 4 deletions homeassistant/components/habitica/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@
SERVICE_API_CALL = "api_call"
ATTR_PATH = CONF_PATH
ATTR_ARGS = "args"

# event constants
EVENT_API_CALL_SUCCESS = f"{DOMAIN}_{SERVICE_API_CALL}_success"
ATTR_DATA = "data"
ATTR_CONFIG_ENTRY = "config_entry"

MANUFACTURER = "HabitRPG, Inc."
NAME = "Habitica"
7 changes: 2 additions & 5 deletions homeassistant/components/habitica/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CONF_URL
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
Expand Down Expand Up @@ -168,7 +168,6 @@ async def async_setup_entry(
) -> None:
"""Set up the habitica sensors."""

name = config_entry.data[CONF_NAME]
sensor_data = HabitipyData(hass.data[DOMAIN][config_entry.entry_id])
await sensor_data.update()

Expand All @@ -177,7 +176,7 @@ async def async_setup_entry(
for description in SENSOR_DESCRIPTIONS.values()
]
entities.extend(
HabitipyTaskSensor(name, task_type, sensor_data, config_entry)
HabitipyTaskSensor(config_entry.title, task_type, sensor_data, config_entry)
for task_type in TASKS_TYPES
)
async_add_entities(entities, True)
Expand Down Expand Up @@ -258,7 +257,6 @@ def __init__(
entry_type=DeviceEntryType.SERVICE,
manufacturer=MANUFACTURER,
model=NAME,
name=entry.data[CONF_NAME],
configuration_url=entry.data[CONF_URL],
identifiers={(DOMAIN, entry.unique_id)},
)
Expand Down Expand Up @@ -287,7 +285,6 @@ def __init__(self, name, task_name, updater, entry):
entry_type=DeviceEntryType.SERVICE,
manufacturer=MANUFACTURER,
model=NAME,
name=entry.data[CONF_NAME],
configuration_url=entry.data[CONF_URL],
identifiers={(DOMAIN, entry.unique_id)},
)
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/habitica/services.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Describes the format for Habitica service
api_call:
fields:
name:
config_entry:
required: true
example: "xxxNotAValidNickxxx"
selector:
text:
config_entry:
integration: habitica
path:
required: true
example: '["tasks", "user", "post"]'
Expand Down
11 changes: 8 additions & 3 deletions homeassistant/components/habitica/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,19 @@
}
}
},
"exceptions": {
"sevice_invalid_path": {
"message": "Failed to call service {service}. Path `{path}` is invalid for API on `{element}` element"
}
},
"services": {
"api_call": {
"name": "API name",
"description": "Calls Habitica API.",
"fields": {
"name": {
"name": "[%key:common::config_flow::data::name%]",
"description": "Habitica's username to call for."
"config_entry": {
"name": "Habitica user",
"description": "The Habitica user to call for"
},
"path": {
"name": "[%key:common::config_flow::data::path%]",
Expand Down
35 changes: 12 additions & 23 deletions tests/components/habitica/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,21 @@

from homeassistant.components.habitica.const import (
ATTR_ARGS,
ATTR_DATA,
ATTR_CONFIG_ENTRY,
ATTR_PATH,
DEFAULT_URL,
DOMAIN,
EVENT_API_CALL_SUCCESS,
SERVICE_API_CALL,
)
from homeassistant.components.habitica.sensor import TASKS_TYPES
from homeassistant.const import ATTR_NAME
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry, async_capture_events
from tests.common import MockConfigEntry

TEST_API_CALL_ARGS = {"text": "Use API from Home Assistant", "type": "todo"}
TEST_USER_NAME = "test_user"


@pytest.fixture
def capture_api_call_success(hass):
"""Capture api_call events."""
return async_capture_events(hass, EVENT_API_CALL_SUCCESS)


@pytest.fixture
def habitica_entry(hass):
"""Test entry for the following tests."""
Expand All @@ -55,7 +47,7 @@ def common_requests(aioclient_mock):
"api_user": "test-api-user",
"profile": {"name": TEST_USER_NAME},
"stats": {
"class": "test-class",
"class": "warrior",
"con": 1,
"exp": 2,
"gp": 3,
Expand Down Expand Up @@ -108,7 +100,7 @@ async def test_entry_setup_unload(


async def test_service_call(
hass: HomeAssistant, habitica_entry, common_requests, capture_api_call_success
hass: HomeAssistant, habitica_entry, common_requests
) -> None:
"""Test integration setup, service call and unload."""

Expand All @@ -117,22 +109,19 @@ async def test_service_call(

assert hass.services.has_service(DOMAIN, SERVICE_API_CALL)

assert len(capture_api_call_success) == 0

TEST_SERVICE_DATA = {
ATTR_NAME: "test_user",
ATTR_CONFIG_ENTRY: habitica_entry.entry_id,
ATTR_PATH: ["tasks", "user", "post"],
ATTR_ARGS: TEST_API_CALL_ARGS,
}
await hass.services.async_call(
DOMAIN, SERVICE_API_CALL, TEST_SERVICE_DATA, blocking=True
service_response = await hass.services.async_call(
DOMAIN,
SERVICE_API_CALL,
TEST_SERVICE_DATA,
blocking=True,
return_response=True,
)

assert len(capture_api_call_success) == 1
captured_data = capture_api_call_success[0].data
captured_data[ATTR_ARGS] = captured_data[ATTR_DATA]
del captured_data[ATTR_DATA]
assert captured_data == TEST_SERVICE_DATA
assert service_response == {"data": TEST_API_CALL_ARGS}

assert await hass.config_entries.async_unload(habitica_entry.entry_id)

Expand Down