Files
core/tests/components/api/test_init.py
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

978 lines
30 KiB
Python
Raw Normal View History

2016-05-24 23:19:37 -07:00
"""The tests for the Home Assistant API component."""
import asyncio
from http import HTTPStatus
2014-11-23 09:51:16 -08:00
import json
from typing import Any
from unittest.mock import ANY, patch
2014-11-23 09:51:16 -08:00
from aiohttp import ServerDisconnectedError, web
from aiohttp.test_utils import TestClient
2017-05-19 07:37:39 -07:00
import pytest
from syrupy.assertion import SnapshotAssertion
2018-11-30 21:28:35 +01:00
import voluptuous as vol
2014-11-23 09:51:16 -08:00
from homeassistant import const, core as ha
from homeassistant.auth.models import Credentials
from homeassistant.bootstrap import DATA_LOGGING
from homeassistant.components.group import DOMAIN as DOMAIN_GROUP
from homeassistant.components.logger import DOMAIN as DOMAIN_LOGGER
from homeassistant.components.system_health import DOMAIN as DOMAIN_SYSTEM_HEALTH
from homeassistant.core import HomeAssistant
from homeassistant.loader import Integration
2017-05-19 07:37:39 -07:00
from homeassistant.setup import async_setup_component
from homeassistant.util.yaml.loader import JSON_TYPE
2014-11-23 22:18:51 -08:00
from tests.common import CLIENT_ID, MockUser, async_mock_service
from tests.typing import ClientSessionGenerator
2018-07-29 01:53:37 +01:00
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
@pytest.fixture
2025-04-02 14:05:07 +02:00
async def mock_api_client(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Start the Home Assistant HTTP component and return admin API client."""
2025-04-02 14:05:07 +02:00
await async_setup_component(hass, "api", {})
return await hass_client()
2017-05-19 07:37:39 -07:00
async def test_api_list_state_entities(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the debug interface allows us to list state entities."""
hass.states.async_set("test.entity", "hello")
resp = await mock_api_client.get(const.URL_API_STATES)
assert resp.status == HTTPStatus.OK
json = await resp.json()
2017-05-19 07:37:39 -07:00
remote_data = [ha.State.from_dict(item).as_dict() for item in json]
local_data = [state.as_dict() for state in hass.states.async_all()]
assert remote_data == local_data
2017-05-19 07:37:39 -07:00
async def test_api_get_state(hass: HomeAssistant, mock_api_client: TestClient) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the debug interface allows us to get a state."""
hass.states.async_set("hello.world", "nice", {"attr": 1})
resp = await mock_api_client.get("/api/states/hello.world")
assert resp.status == HTTPStatus.OK
json = await resp.json()
2017-05-19 07:37:39 -07:00
data = ha.State.from_dict(json)
state = hass.states.get("hello.world")
assert data.state == state.state
assert data.last_changed == state.last_changed
assert data.attributes == state.attributes
async def test_api_get_non_existing_state(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the debug interface allows us to get a state."""
resp = await mock_api_client.get("/api/states/does_not_exist")
assert resp.status == HTTPStatus.NOT_FOUND
2017-05-19 07:37:39 -07:00
async def test_api_state_change(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if we can change the state of an entity that exists."""
hass.states.async_set("test.test", "not_to_be_set")
await mock_api_client.post(
"/api/states/test.test", json={"state": "debug_state_change2"}
2017-05-19 07:37:39 -07:00
)
assert hass.states.get("test.test").state == "debug_state_change2"
2014-11-23 12:57:29 -08:00
async def test_api_state_change_of_non_existing_entity(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if changing a state of a non existing entity is possible."""
new_state = "debug_state_change"
2014-11-23 12:57:29 -08:00
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={"state": new_state}
2017-05-19 07:37:39 -07:00
)
2014-11-23 12:57:29 -08:00
assert resp.status == HTTPStatus.CREATED
2014-11-23 12:57:29 -08:00
2017-05-19 07:37:39 -07:00
assert hass.states.get("test_entity.that_does_not_exist").state == new_state
2016-05-14 00:58:36 -07:00
2014-11-23 12:57:29 -08:00
async def test_api_state_change_with_bad_entity_id(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/bad.entity.id", json={"state": "new_state"}
)
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_api_state_change_with_bad_state(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/test.test", json={"state": "x" * 256}
)
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_api_state_change_with_bad_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={}
2017-05-19 07:37:39 -07:00
)
assert resp.status == HTTPStatus.BAD_REQUEST
2014-11-23 12:57:29 -08:00
async def test_api_state_change_with_invalid_json(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if send invalid json data."""
resp = await mock_api_client.post("/api/states/test.test", data="{,}")
assert resp.status == HTTPStatus.BAD_REQUEST
assert await resp.json() == {"message": "Invalid JSON specified."}
async def test_api_state_change_with_string_body(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if we send a string instead of a JSON object."""
resp = await mock_api_client.post(
"/api/states/bad.entity.id", json='"{"state": "new_state"}"'
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert await resp.json() == {"message": "State data should be a JSON object."}
async def test_api_state_change_to_zero_value(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if changing a state to a zero value is possible."""
resp = await mock_api_client.post(
"/api/states/test_entity.with_zero_state", json={"state": 0}
)
assert resp.status == HTTPStatus.CREATED
resp = await mock_api_client.post(
"/api/states/test_entity.with_zero_state", json={"state": 0.0}
)
assert resp.status == HTTPStatus.OK
async def test_api_state_change_push(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if we can push a change the state of an entity."""
hass.states.async_set("test.test", "not_to_be_set")
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
events = []
2016-02-14 23:01:49 -08:00
2017-05-19 07:37:39 -07:00
@ha.callback
def event_listener(event):
"""Track events."""
events.append(event)
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
hass.bus.async_listen(const.EVENT_STATE_CHANGED, event_listener)
2014-11-23 09:51:16 -08:00
await mock_api_client.post("/api/states/test.test", json={"state": "not_to_be_set"})
await hass.async_block_till_done()
2017-05-19 07:37:39 -07:00
assert len(events) == 0
2014-11-23 09:51:16 -08:00
await mock_api_client.post(
"/api/states/test.test", json={"state": "not_to_be_set", "force_update": True}
2017-05-19 07:37:39 -07:00
)
await hass.async_block_till_done()
2017-05-19 07:37:39 -07:00
assert len(events) == 1
2014-11-23 09:51:16 -08:00
async def test_api_fire_event_with_no_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the API allows us to fire an event."""
test_value = []
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
@ha.callback
def listener(event):
"""Record that our event got called."""
2017-05-19 07:37:39 -07:00
test_value.append(1)
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
hass.bus.async_listen_once("test.event_no_data", listener)
2014-11-23 09:51:16 -08:00
await mock_api_client.post("/api/events/test.event_no_data")
await hass.async_block_till_done()
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
assert len(test_value) == 1
2014-11-23 09:51:16 -08:00
async def test_api_fire_event_with_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the API allows us to fire an event."""
test_value = []
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
@ha.callback
def listener(event):
"""Record that our event got called.
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
Also test if our data came through.
"""
if "test" in event.data:
2014-11-23 09:51:16 -08:00
test_value.append(1)
2017-05-19 07:37:39 -07:00
hass.bus.async_listen_once("test_event_with_data", listener)
2014-11-23 09:51:16 -08:00
await mock_api_client.post("/api/events/test_event_with_data", json={"test": 1})
2014-11-23 09:51:16 -08:00
await hass.async_block_till_done()
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
assert len(test_value) == 1
2014-11-23 09:51:16 -08:00
async def test_api_fire_event_with_invalid_json(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the API allows us to fire an event."""
test_value = []
2016-03-09 10:25:50 +01:00
2017-05-19 07:37:39 -07:00
@ha.callback
def listener(event):
"""Record that our event got called."""
2017-05-19 07:37:39 -07:00
test_value.append(1)
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
hass.bus.async_listen_once("test_event_bad_data", listener)
2014-11-23 09:51:16 -08:00
resp = await mock_api_client.post(
"/api/events/test_event_bad_data", data=json.dumps("not an object")
2017-05-19 07:37:39 -07:00
)
2014-11-23 09:51:16 -08:00
await hass.async_block_till_done()
2014-11-23 09:51:16 -08:00
assert resp.status == HTTPStatus.BAD_REQUEST
2017-05-19 07:37:39 -07:00
assert len(test_value) == 0
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
# Try now with valid but unusable JSON
resp = await mock_api_client.post(
"/api/events/test_event_bad_data", data=json.dumps([1, 2, 3])
2017-05-19 07:37:39 -07:00
)
2014-11-23 09:51:16 -08:00
await hass.async_block_till_done()
2017-05-19 07:37:39 -07:00
assert resp.status == HTTPStatus.BAD_REQUEST
2017-05-19 07:37:39 -07:00
assert len(test_value) == 0
async def test_api_get_config(hass: HomeAssistant, mock_api_client: TestClient) -> None:
2017-05-19 07:37:39 -07:00
"""Test the return of the configuration."""
resp = await mock_api_client.get(const.URL_API_CONFIG)
result = await resp.json()
ignore_order_keys = (
"components",
"allowlist_external_dirs",
"whitelist_external_dirs",
"allowlist_external_urls",
)
config = hass.config.as_dict()
2017-05-19 07:37:39 -07:00
for key in ignore_order_keys:
if key in result:
result[key] = set(result[key])
config[key] = set(config[key])
assert result == config
2017-05-19 07:37:39 -07:00
async def test_api_get_components(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test the return of the components."""
resp = await mock_api_client.get(const.URL_API_COMPONENTS)
result = await resp.json()
2017-05-19 07:37:39 -07:00
assert set(result) == hass.config.components
async def test_api_get_event_listeners(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if we can get the list of events being listened for."""
resp = await mock_api_client.get(const.URL_API_EVENTS)
data = await resp.json()
2017-05-19 07:37:39 -07:00
local = hass.bus.async_listeners()
for event in data:
assert local.pop(event["event"]) == event["listener_count"]
assert len(local) == 0
async def test_api_get_services(
hass: HomeAssistant,
mock_api_client: TestClient,
snapshot: SnapshotAssertion,
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if we can get a dict describing current services."""
# Set up an integration that has services
assert await async_setup_component(hass, DOMAIN_GROUP, {DOMAIN_GROUP: {}})
# Set up an integration that has no services
assert await async_setup_component(hass, DOMAIN_SYSTEM_HEALTH, {})
resp = await mock_api_client.get(const.URL_API_SERVICES)
data = await resp.json()
2017-05-19 07:37:39 -07:00
assert data == snapshot
2017-05-19 07:37:39 -07:00
# Set up an integration with legacy translations in services.yaml
def _load_services_file(integration: Integration) -> JSON_TYPE:
return {
"set_default_level": {
"description": "Translated description",
"fields": {
"level": {
"description": "Field description",
"example": "Field example",
"name": "Field name",
"selector": {
"select": {
"options": [
"debug",
"info",
"warning",
"error",
"fatal",
"critical",
],
"translation_key": "level",
}
},
}
},
"name": "Translated name",
},
"set_level": None,
}
await async_setup_component(hass, DOMAIN_LOGGER, {DOMAIN_LOGGER: {}})
await hass.async_block_till_done()
with (
patch(
"homeassistant.helpers.service._load_services_file",
side_effect=_load_services_file,
),
):
resp = await mock_api_client.get(const.URL_API_SERVICES)
data2 = await resp.json()
assert data2 == [*data, {"domain": DOMAIN_LOGGER, "services": ANY}]
assert data2[-1] == snapshot
2017-05-19 07:37:39 -07:00
async def test_api_call_service_no_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the API allows us to call a service."""
test_value = []
@ha.callback
def listener(service_call):
"""Record that our service got called."""
2017-05-19 07:37:39 -07:00
test_value.append(1)
hass.services.async_register("test_domain", "test_service", listener)
await mock_api_client.post("/api/services/test_domain/test_service")
await hass.async_block_till_done()
2017-05-19 07:37:39 -07:00
assert len(test_value) == 1
async def test_api_call_service_with_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test if the API allows us to call a service."""
@ha.callback
def listener(service_call):
"""Record that our service got called.
2017-05-19 07:37:39 -07:00
Also test if our data came through.
"""
2021-03-11 23:18:09 -08:00
hass.states.async_set(
"test.data",
"on",
{"data": service_call.data["test"]},
context=service_call.context,
)
2014-11-23 09:51:16 -08:00
2017-05-19 07:37:39 -07:00
hass.services.async_register("test_domain", "test_service", listener)
2014-11-23 09:51:16 -08:00
2021-03-11 23:18:09 -08:00
resp = await mock_api_client.post(
"/api/services/test_domain/test_service", json={"test": 1}
2017-05-19 07:37:39 -07:00
)
2021-03-11 23:18:09 -08:00
data = await resp.json()
assert len(data) == 1
state = data[0]
assert state["entity_id"] == "test.data"
assert state["state"] == "on"
assert state["attributes"] == {"data": 1}
2014-11-23 09:51:16 -08:00
SERVICE_DICT = {"changed_states": [], "service_response": {"foo": "bar"}}
RESP_REQUIRED = {
"message": (
"Service call requires responses but caller did not ask for "
"responses. Add ?return_response to query parameters."
)
}
RESP_UNSUPPORTED = {
"message": "Service does not support responses. Remove return_response from request."
}
@pytest.mark.parametrize(
(
"supports_response",
"requested_response",
"expected_number_of_service_calls",
"expected_status",
"expected_response",
),
[
(ha.SupportsResponse.ONLY, True, 1, HTTPStatus.OK, SERVICE_DICT),
(ha.SupportsResponse.ONLY, False, 0, HTTPStatus.BAD_REQUEST, RESP_REQUIRED),
(ha.SupportsResponse.OPTIONAL, True, 1, HTTPStatus.OK, SERVICE_DICT),
(ha.SupportsResponse.OPTIONAL, False, 1, HTTPStatus.OK, []),
(ha.SupportsResponse.NONE, True, 0, HTTPStatus.BAD_REQUEST, RESP_UNSUPPORTED),
(ha.SupportsResponse.NONE, False, 1, HTTPStatus.OK, []),
],
)
async def test_api_call_service_returns_response_requested_response(
hass: HomeAssistant,
mock_api_client: TestClient,
supports_response: ha.SupportsResponse,
requested_response: bool,
expected_number_of_service_calls: int,
expected_status: int,
expected_response: Any,
) -> None:
"""Test if the API allows us to call a service."""
test_value = []
@ha.callback
def listener(service_call):
"""Record that our service got called."""
test_value.append(1)
return {"foo": "bar"}
hass.services.async_register(
"test_domain", "test_service", listener, supports_response=supports_response
)
resp = await mock_api_client.post(
"/api/services/test_domain/test_service"
+ ("?return_response" if requested_response else "")
)
assert resp.status == expected_status
await hass.async_block_till_done()
assert len(test_value) == expected_number_of_service_calls
assert await resp.json() == expected_response
async def test_api_call_service_client_closed(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test that services keep running if client is closed."""
test_value = []
fut = hass.loop.create_future()
service_call_started = asyncio.Event()
async def listener(service_call):
"""Wait and return after mock_api_client.post finishes."""
service_call_started.set()
value = await fut
test_value.append(value)
hass.services.async_register("test_domain", "test_service", listener)
api_task = hass.async_create_task(
mock_api_client.post("/api/services/test_domain/test_service")
)
await service_call_started.wait()
assert len(test_value) == 0
await mock_api_client.close()
assert len(test_value) == 0
assert api_task.done()
with pytest.raises(ServerDisconnectedError):
await api_task
fut.set_result(1)
await hass.async_block_till_done()
assert len(test_value) == 1
assert test_value[0] == 1
async def test_api_template(hass: HomeAssistant, mock_api_client: TestClient) -> None:
2017-05-19 07:37:39 -07:00
"""Test the template API."""
hass.states.async_set("sensor.temperature", 10)
resp = await mock_api_client.post(
2017-05-19 07:37:39 -07:00
const.URL_API_TEMPLATE,
json={"template": "{{ states.sensor.temperature.state }}"},
)
body = await resp.text()
2017-05-19 07:37:39 -07:00
assert body == "10"
2017-02-09 10:21:57 -08:00
hass.states.async_set("sensor.temperature", 20)
resp = await mock_api_client.post(
const.URL_API_TEMPLATE,
json={"template": "{{ states.sensor.temperature.state }}"},
)
body = await resp.text()
assert body == "20"
hass.states.async_remove("sensor.temperature")
resp = await mock_api_client.post(
const.URL_API_TEMPLATE,
json={"template": "{{ states.sensor.temperature.state }}"},
)
body = await resp.text()
assert body == ""
async def test_api_template_cached(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test the template API uses the cache."""
hass.states.async_set("sensor.temperature", 30)
resp = await mock_api_client.post(
const.URL_API_TEMPLATE,
json={"template": "{{ states.sensor.temperature.state }}"},
)
body = await resp.text()
assert body == "30"
hass.states.async_set("sensor.temperature", 40)
resp = await mock_api_client.post(
const.URL_API_TEMPLATE,
json={"template": "{{ states.sensor.temperature.state }}"},
)
body = await resp.text()
assert body == "40"
2015-11-28 14:08:01 -08:00
async def test_api_template_error(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test the template API."""
hass.states.async_set("sensor.temperature", 10)
2015-11-28 14:08:01 -08:00
resp = await mock_api_client.post(
2017-05-19 07:37:39 -07:00
const.URL_API_TEMPLATE, json={"template": "{{ states.sensor.temperature.state"}
)
2014-11-23 09:51:16 -08:00
assert resp.status == HTTPStatus.BAD_REQUEST
2014-11-23 09:51:16 -08:00
async def test_api_template_with_invalid_json(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if send invalid json data."""
resp = await mock_api_client.post(const.URL_API_TEMPLATE, data="{,}")
assert resp.status == HTTPStatus.BAD_REQUEST
assert await resp.json() == {"message": "Invalid JSON specified."}
async def test_api_template_error_with_string_body(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test that the API returns an appropriate error when a string is sent in the body."""
hass.states.async_set("sensor.temperature", 10)
resp = await mock_api_client.post(
const.URL_API_TEMPLATE,
json='"{"template": "{{ states.sensor.temperature.state"}"',
)
assert resp.status == HTTPStatus.BAD_REQUEST
assert await resp.json() == {"message": "Template data should be a JSON object."}
async def test_stream(hass: HomeAssistant, mock_api_client: TestClient) -> None:
2017-05-19 07:37:39 -07:00
"""Test the stream."""
listen_count = _listen_count(hass)
2014-11-23 09:51:16 -08:00
async with mock_api_client.get(const.URL_API_STREAM) as resp:
assert resp.status == HTTPStatus.OK
assert listen_count + 1 == _listen_count(hass)
2014-11-23 09:51:16 -08:00
hass.bus.async_fire("test_event")
2014-11-23 09:51:16 -08:00
data = await _stream_next_event(resp.content)
2014-11-23 09:51:16 -08:00
assert data["event_type"] == "test_event"
2014-11-23 09:51:16 -08:00
async def test_stream_with_restricted(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2017-05-19 07:37:39 -07:00
"""Test the stream with restrictions."""
listen_count = _listen_count(hass)
2014-11-23 09:51:16 -08:00
async with mock_api_client.get(
f"{const.URL_API_STREAM}?restrict=test_event1,test_event3"
) as resp:
assert resp.status == HTTPStatus.OK
assert listen_count + 1 == _listen_count(hass)
2014-11-23 09:51:16 -08:00
hass.bus.async_fire("test_event1")
data = await _stream_next_event(resp.content)
assert data["event_type"] == "test_event1"
2014-11-23 09:51:16 -08:00
hass.bus.async_fire("test_event2")
hass.bus.async_fire("test_event3")
data = await _stream_next_event(resp.content)
assert data["event_type"] == "test_event3"
2014-11-23 09:51:16 -08:00
async def _stream_next_event(stream):
2017-05-19 07:37:39 -07:00
"""Read the stream for next event while ignoring ping."""
while True:
last_new_line = False
data = b""
2014-11-23 09:51:16 -08:00
while True:
dat = await stream.read(1)
2017-05-19 07:37:39 -07:00
if dat == b"\n" and last_new_line:
break
2017-05-19 07:37:39 -07:00
data += dat
last_new_line = dat == b"\n"
2015-12-14 23:20:43 -08:00
2017-05-19 07:37:39 -07:00
conv = data.decode("utf-8").strip()[6:]
2016-05-15 23:54:14 -07:00
2017-05-19 07:37:39 -07:00
if conv != "ping":
break
return json.loads(conv)
def _listen_count(hass: HomeAssistant) -> int:
2017-05-19 07:37:39 -07:00
"""Return number of event listeners."""
return sum(hass.bus.async_listeners().values())
async def test_api_error_log(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
hass_access_token: str,
hass_admin_user: MockUser,
) -> None:
"""Test if we can fetch the error log."""
hass.data[DATA_LOGGING] = "/some/path"
2019-03-10 19:55:36 -07:00
await async_setup_component(hass, "api", {})
client = await hass_client_no_auth()
resp = await client.get(const.URL_API_ERROR_LOG)
2018-11-25 18:04:48 +01:00
# Verify auth required
assert resp.status == HTTPStatus.UNAUTHORIZED
with patch(
"aiohttp.web.FileResponse", return_value=web.Response(text="Hello")
) as mock_file:
resp = await client.get(
const.URL_API_ERROR_LOG,
headers={"Authorization": f"Bearer {hass_access_token}"},
)
assert len(mock_file.mock_calls) == 1
assert mock_file.mock_calls[0][1][0] == hass.data[DATA_LOGGING]
assert resp.status == HTTPStatus.OK
assert await resp.text() == "Hello"
2018-07-29 01:53:37 +01:00
2018-11-25 18:04:48 +01:00
# Verify we require admin user
hass_admin_user.groups = []
resp = await client.get(
const.URL_API_ERROR_LOG,
headers={"Authorization": f"Bearer {hass_access_token}"},
2018-11-25 18:04:48 +01:00
)
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
2018-07-29 01:53:37 +01:00
async def test_api_fire_event_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
2018-07-29 01:53:37 +01:00
"""Test if the API sets right context if we fire an event."""
test_value = []
@ha.callback
def listener(event):
"""Record that our event got called."""
2018-07-29 01:53:37 +01:00
test_value.append(event)
hass.bus.async_listen("test.event", listener)
await mock_api_client.post(
"/api/events/test.event",
headers={"authorization": f"Bearer {hass_access_token}"},
2018-07-29 01:53:37 +01:00
)
await hass.async_block_till_done()
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
2018-08-14 21:14:12 +02:00
2018-07-29 01:53:37 +01:00
assert len(test_value) == 1
2018-08-14 21:14:12 +02:00
assert test_value[0].context.user_id == refresh_token.user.id
2018-07-29 01:53:37 +01:00
async def test_api_call_service_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
2018-07-29 01:53:37 +01:00
"""Test if the API sets right context if we call a service."""
calls = async_mock_service(hass, "test_domain", "test_service")
await mock_api_client.post(
"/api/services/test_domain/test_service",
headers={"authorization": f"Bearer {hass_access_token}"},
2018-07-29 01:53:37 +01:00
)
await hass.async_block_till_done()
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
2018-08-14 21:14:12 +02:00
2018-07-29 01:53:37 +01:00
assert len(calls) == 1
2018-08-14 21:14:12 +02:00
assert calls[0].context.user_id == refresh_token.user.id
2018-07-29 01:53:37 +01:00
async def test_api_set_state_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
2018-07-29 01:53:37 +01:00
"""Test if the API sets right context if we set state."""
await mock_api_client.post(
"/api/states/light.kitchen",
json={"state": "on"},
headers={"authorization": f"Bearer {hass_access_token}"},
2018-07-29 01:53:37 +01:00
)
refresh_token = hass.auth.async_validate_access_token(hass_access_token)
2018-08-14 21:14:12 +02:00
2018-07-29 01:53:37 +01:00
state = hass.states.get("light.kitchen")
2018-08-14 21:14:12 +02:00
assert state.context.user_id == refresh_token.user.id
2018-11-25 18:04:48 +01:00
async def test_event_stream_requires_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test user needs to be admin to access event stream."""
hass_admin_user.groups = []
resp = await mock_api_client.get("/api/stream")
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
async def test_states(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test fetching all states as admin."""
hass.states.async_set("test.entity", "hello")
hass.states.async_set("test.entity2", "hello")
resp = await mock_api_client.get(const.URL_API_STATES)
assert resp.status == HTTPStatus.OK
json = await resp.json()
assert len(json) == 2
assert json[0]["entity_id"] == "test.entity"
assert json[1]["entity_id"] == "test.entity2"
async def test_states_view_filters(
hass: HomeAssistant,
hass_read_only_user: MockUser,
hass_client: ClientSessionGenerator,
) -> None:
2018-11-25 18:04:48 +01:00
"""Test filtering only visible states."""
assert not hass_read_only_user.is_admin
hass_read_only_user.mock_policy({"entities": {"entity_ids": {"test.entity": True}}})
await async_setup_component(hass, "api", {})
read_only_user_credential = Credentials(
id="mock-read-only-credential-id",
auth_provider_type="homeassistant",
auth_provider_id=None,
data={"username": "readonly"},
is_new=False,
)
await hass.auth.async_link_user(hass_read_only_user, read_only_user_credential)
refresh_token = await hass.auth.async_create_refresh_token(
hass_read_only_user, CLIENT_ID, credential=read_only_user_credential
)
token = hass.auth.async_create_access_token(refresh_token)
mock_api_client = await hass_client(token)
2018-11-25 18:04:48 +01:00
hass.states.async_set("test.entity", "hello")
hass.states.async_set("test.not_visible_entity", "invisible")
resp = await mock_api_client.get(const.URL_API_STATES)
assert resp.status == HTTPStatus.OK
2018-11-25 18:04:48 +01:00
json = await resp.json()
assert len(json) == 1
assert json[0]["entity_id"] == "test.entity"
async def test_get_entity_state_read_perm(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test getting a state requires read permission."""
hass_admin_user.mock_policy({})
hass_admin_user.groups = []
assert hass_admin_user.is_admin is False
2018-11-25 18:04:48 +01:00
resp = await mock_api_client.get("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
async def test_post_entity_state_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test updating state requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.post("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
async def test_delete_entity_state_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test deleting entity requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.delete("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
async def test_post_event_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test sending event requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.post("/api/events/state_changed")
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-25 18:04:48 +01:00
async def test_rendering_template_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
2018-11-25 18:04:48 +01:00
"""Test rendering a template requires admin."""
hass_admin_user.groups = []
2018-11-27 10:41:44 +01:00
resp = await mock_api_client.post(const.URL_API_TEMPLATE)
assert resp.status == HTTPStatus.UNAUTHORIZED
2018-11-27 10:41:44 +01:00
async def test_api_call_service_not_found(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2020-01-31 17:33:00 +01:00
"""Test if the API fails 400 if unknown service."""
resp = await mock_api_client.post("/api/services/test_domain/test_service")
assert resp.status == HTTPStatus.BAD_REQUEST
2018-11-30 21:28:35 +01:00
async def test_api_call_service_bad_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
2020-01-31 17:33:00 +01:00
"""Test if the API fails 400 if unknown service."""
2018-11-30 21:28:35 +01:00
test_value = []
@ha.callback
def listener(service_call):
"""Record that our service got called."""
test_value.append(1)
hass.services.async_register(
"test_domain", "test_service", listener, schema=vol.Schema({"hello": str})
)
resp = await mock_api_client.post(
"/api/services/test_domain/test_service", json={"hello": 5}
2018-11-30 21:28:35 +01:00
)
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_api_status(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test getting the api status."""
resp = await mock_api_client.get("/api/")
assert resp.status == HTTPStatus.OK
json = await resp.json()
assert json["message"] == "API running."
async def test_api_core_state(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test getting core status."""
resp = await mock_api_client.get("/api/core/state")
assert resp.status == HTTPStatus.OK
json = await resp.json()
assert json == {
"state": "RUNNING",
"recorder_state": {"migration_in_progress": False, "migration_is_live": False},
}
@pytest.mark.parametrize(
("migration_in_progress", "migration_is_live"),
[
(False, False),
(False, True),
(True, False),
(True, True),
],
)
async def test_api_core_state_recorder_migrating(
hass: HomeAssistant,
mock_api_client: TestClient,
migration_in_progress: bool,
migration_is_live: bool,
) -> None:
"""Test getting core status."""
with (
patch(
"homeassistant.helpers.recorder.async_migration_in_progress",
return_value=migration_in_progress,
),
patch(
"homeassistant.helpers.recorder.async_migration_is_live",
return_value=migration_is_live,
),
):
resp = await mock_api_client.get("/api/core/state")
assert resp.status == HTTPStatus.OK
json = await resp.json()
expected_recorder_state = {
"migration_in_progress": migration_in_progress,
"migration_is_live": migration_is_live,
}
assert json == {"state": "RUNNING", "recorder_state": expected_recorder_state}