core/tests/components/alexa/test_intent.py

539 lines
19 KiB
Python
Raw Normal View History

2016-03-09 09:25:50 +00:00
"""The tests for the Alexa component."""
2023-01-22 16:26:24 +00:00
from http import HTTPStatus
2015-12-13 06:29:02 +00:00
import json
import pytest
2015-12-13 06:29:02 +00:00
from homeassistant.components import alexa
from homeassistant.components.alexa import intent
from homeassistant.const import CONTENT_TYPE_JSON
from homeassistant.core import callback
from homeassistant.setup import async_setup_component
2015-12-13 06:29:02 +00:00
SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000"
APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe"
2022-01-31 18:23:26 +00:00
APPLICATION_ID_SESSION_OPEN = (
"amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebf"
)
REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000"
AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC"
BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST"
# pylint: disable=invalid-name
calls = []
2015-12-13 06:29:02 +00:00
NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3"
2015-12-13 06:29:02 +00:00
@pytest.fixture
Upgrade pytest-aiohttp (#82475) * Upgrade pytest-aiohttp * Make sure executors, tasks and timers are closed Some test will trigger warnings on garbage collect, these warnings spills over into next test. Some test trigger tasks that raise errors on shutdown, these spill over into next test. This is to mimic older pytest-aiohttp and it's behaviour on test cleanup. Discussions on similar changes for pytest-aiohttp are here: https://github.com/pytest-dev/pytest-asyncio/pull/309 * Replace loop with event_loop * Make sure time is frozen for tests * Make sure the ConditionType is not async /home-assistant/homeassistant/helpers/template.py:2082: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited def wrapper(*args, **kwargs): Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. * Increase litejet press tests with a factor 10 The times are simulated anyway, and we can't stop the normal event from occuring. * Use async handlers for aiohttp tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template /Users/joakim/src/hass/home-assistant/venv/lib/python3.9/site-packages/aiohttp/web_urldispatcher.py:189: DeprecationWarning: Bare functions are deprecated, use async ones warnings.warn( * Switch to freezegun in modbus tests The tests allowed clock to tick in between steps * Make sure skybell object are fully mocked Old tests would trigger attempts to post to could services: ``` DEBUG:aioskybell:HTTP post https://cloud.myskybell.com/api/v3/login/ Request with headers: {'content-type': 'application/json', 'accept': '*/*', 'x-skybell-app-id': 'd2b542c7-a7e4-4e1e-b77d-2b76911c7c46', 'x-skybell-client-id': '1f36a3c0-6dee-4997-a6db-4e1c67338e57'} ``` * Fix sorting that broke after rebase
2022-11-29 21:36:36 +00:00
def alexa_client(event_loop, hass, hass_client):
2016-03-09 09:25:50 +00:00
"""Initialize a Home Assistant server for testing this module."""
Upgrade pytest-aiohttp (#82475) * Upgrade pytest-aiohttp * Make sure executors, tasks and timers are closed Some test will trigger warnings on garbage collect, these warnings spills over into next test. Some test trigger tasks that raise errors on shutdown, these spill over into next test. This is to mimic older pytest-aiohttp and it's behaviour on test cleanup. Discussions on similar changes for pytest-aiohttp are here: https://github.com/pytest-dev/pytest-asyncio/pull/309 * Replace loop with event_loop * Make sure time is frozen for tests * Make sure the ConditionType is not async /home-assistant/homeassistant/helpers/template.py:2082: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited def wrapper(*args, **kwargs): Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. * Increase litejet press tests with a factor 10 The times are simulated anyway, and we can't stop the normal event from occuring. * Use async handlers for aiohttp tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_still_image_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_get_stream_from_camera tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template tests/components/motioneye/test_camera.py::test_camera_option_stream_url_template /Users/joakim/src/hass/home-assistant/venv/lib/python3.9/site-packages/aiohttp/web_urldispatcher.py:189: DeprecationWarning: Bare functions are deprecated, use async ones warnings.warn( * Switch to freezegun in modbus tests The tests allowed clock to tick in between steps * Make sure skybell object are fully mocked Old tests would trigger attempts to post to could services: ``` DEBUG:aioskybell:HTTP post https://cloud.myskybell.com/api/v3/login/ Request with headers: {'content-type': 'application/json', 'accept': '*/*', 'x-skybell-app-id': 'd2b542c7-a7e4-4e1e-b77d-2b76911c7c46', 'x-skybell-client-id': '1f36a3c0-6dee-4997-a6db-4e1c67338e57'} ``` * Fix sorting that broke after rebase
2022-11-29 21:36:36 +00:00
loop = event_loop
2019-07-31 19:25:30 +00:00
@callback
def mock_service(call):
calls.append(call)
hass.services.async_register("test", "alexa", mock_service)
2019-07-31 19:25:30 +00:00
assert loop.run_until_complete(
async_setup_component(
hass,
alexa.DOMAIN,
{
# Key is here to verify we allow other keys in config too
"homeassistant": {},
"alexa": {},
2019-07-31 19:25:30 +00:00
},
)
)
assert loop.run_until_complete(
async_setup_component(
hass,
"intent_script",
{
"intent_script": {
"WhereAreWeIntent": {
"speech": {
"type": "plain",
"text": """
{%- if is_state("device_tracker.paulus", "home")
and is_state("device_tracker.anne_therese",
"home") -%}
2015-12-13 06:29:02 +00:00
You are both home, you silly
{%- else -%}
Anne Therese is at {{
states("device_tracker.anne_therese")
}} and Paulus is at {{
states("device_tracker.paulus")
}}
2015-12-13 06:29:02 +00:00
{% endif %}
""",
2019-07-31 19:25:30 +00:00
}
},
"GetZodiacHoroscopeIntent": {
"speech": {
"type": "plain",
"text": "You told us your sign is {{ ZodiacSign }}.",
}
2017-07-30 04:52:26 +00:00
},
2019-07-31 19:25:30 +00:00
"AMAZON.PlaybackAction<object@MusicCreativeWork>": {
"speech": {
"type": "plain",
"text": "Playing {{ object_byArtist_name }}.",
}
},
2019-07-31 19:25:30 +00:00
"CallServiceIntent": {
"speech": {
"type": "plain",
"text": "Service called for {{ ZodiacSign }}",
},
2019-07-31 19:25:30 +00:00
"card": {
"type": "simple",
"title": "Card title for {{ ZodiacSign }}",
"content": "Card content: {{ ZodiacSign }}",
},
"action": {
"service": "test.alexa",
"data_template": {"hello": "{{ ZodiacSign }}"},
"entity_id": "switch.test",
},
},
APPLICATION_ID: {
"speech": {
"type": "plain",
"text": "LaunchRequest has been received.",
}
},
2022-01-31 18:23:26 +00:00
APPLICATION_ID_SESSION_OPEN: {
"speech": {
"type": "plain",
"text": "LaunchRequest has been received.",
},
"reprompt": {
"type": "plain",
"text": "LaunchRequest has been received.",
},
},
2019-07-31 19:25:30 +00:00
}
},
)
)
return loop.run_until_complete(hass_client())
2016-05-14 07:58:36 +00:00
2015-12-13 06:29:02 +00:00
def _intent_req(client, data=None):
2019-07-31 19:25:30 +00:00
return client.post(
intent.INTENTS_API_ENDPOINT,
data=json.dumps(data or {}),
headers={"content-type": CONTENT_TYPE_JSON},
2019-07-31 19:25:30 +00:00
)
2015-12-13 06:29:02 +00:00
async def test_intent_launch_request(alexa_client):
"""Test the launch of a request."""
data = {
"version": "1.0",
"session": {
"new": True,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "LaunchRequest",
"requestId": REQUEST_ID,
2019-07-31 19:25:30 +00:00
"timestamp": "2015-05-13T12:34:56Z",
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "LaunchRequest has been received."
2022-01-31 18:23:26 +00:00
assert data.get("response", {}).get("shouldEndSession")
async def test_intent_launch_request_with_session_open(alexa_client):
"""Test the launch of a request."""
data = {
"version": "1.0",
"session": {
"new": True,
"sessionId": SESSION_ID,
"application": {"applicationId": APPLICATION_ID_SESSION_OPEN},
"attributes": {},
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "LaunchRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "LaunchRequest has been received."
text = (
data.get("response", {}).get("reprompt", {}).get("outputSpeech", {}).get("text")
)
assert text == "LaunchRequest has been received."
assert not data.get("response", {}).get("shouldEndSession")
async def test_intent_launch_request_not_configured(alexa_client):
"""Test the launch of a request."""
data = {
"version": "1.0",
"session": {
"new": True,
"sessionId": SESSION_ID,
"application": {
"applicationId": (
"amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000"
),
},
"attributes": {},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "LaunchRequest",
"requestId": REQUEST_ID,
2019-07-31 19:25:30 +00:00
"timestamp": "2015-05-13T12:34:56Z",
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "This intent is not yet configured within Home Assistant."
async def test_intent_request_with_slots(alexa_client):
"""Test a request with slots."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
2015-12-13 06:29:02 +00:00
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
"intent": {
"name": "GetZodiacHoroscopeIntent",
2019-07-31 19:25:30 +00:00
"slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}},
},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "You told us your sign is virgo."
async def test_intent_request_with_slots_and_synonym_resolution(alexa_client):
"""Test a request with slots and a name synonym."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
"intent": {
"name": "GetZodiacHoroscopeIntent",
"slots": {
"ZodiacSign": {
"name": "ZodiacSign",
"value": "V zodiac",
"resolutions": {
"resolutionsPerAuthority": [
{
"authority": AUTHORITY_ID,
2019-07-31 19:25:30 +00:00
"status": {"code": "ER_SUCCESS_MATCH"},
"values": [{"value": {"name": "Virgo"}}],
},
{
"authority": BUILTIN_AUTH_ID,
2019-07-31 19:25:30 +00:00
"status": {"code": "ER_SUCCESS_NO_MATCH"},
"values": [{"value": {"name": "Test"}}],
},
]
2019-07-31 19:25:30 +00:00
},
}
2019-07-31 19:25:30 +00:00
},
},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "You told us your sign is Virgo."
async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client):
"""Test a request with slots and multiple name synonyms."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
"intent": {
"name": "GetZodiacHoroscopeIntent",
"slots": {
"ZodiacSign": {
"name": "ZodiacSign",
"value": "V zodiac",
"resolutions": {
"resolutionsPerAuthority": [
{
"authority": AUTHORITY_ID,
2019-07-31 19:25:30 +00:00
"status": {"code": "ER_SUCCESS_MATCH"},
"values": [{"value": {"name": "Virgo"}}],
},
{
"authority": BUILTIN_AUTH_ID,
2019-07-31 19:25:30 +00:00
"status": {"code": "ER_SUCCESS_MATCH"},
"values": [{"value": {"name": "Test"}}],
},
]
2019-07-31 19:25:30 +00:00
},
}
2019-07-31 19:25:30 +00:00
},
},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "You told us your sign is V zodiac."
async def test_intent_request_with_slots_but_no_value(alexa_client):
"""Test a request with slots but no value."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
2015-12-22 10:08:46 +00:00
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
"intent": {
"name": "GetZodiacHoroscopeIntent",
2019-07-31 19:25:30 +00:00
"slots": {"ZodiacSign": {"name": "ZodiacSign"}},
},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "You told us your sign is ."
async def test_intent_request_without_slots(hass, alexa_client):
"""Test a request without slots."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
2015-12-13 06:29:02 +00:00
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
2019-07-31 19:25:30 +00:00
"intent": {"name": "WhereAreWeIntent"},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
json = await req.json()
2019-07-31 19:25:30 +00:00
text = json.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "Anne Therese is at unknown and Paulus is at unknown"
hass.states.async_set("device_tracker.paulus", "home")
hass.states.async_set("device_tracker.anne_therese", "home")
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
json = await req.json()
2019-07-31 19:25:30 +00:00
text = json.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "You are both home, you silly"
async def test_intent_request_calling_service(alexa_client):
"""Test a request for calling a service."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "IntentRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
"intent": {
"name": "CallServiceIntent",
2019-07-31 19:25:30 +00:00
"slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}},
},
},
}
call_count = len(calls)
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
assert call_count + 1 == len(calls)
call = calls[-1]
assert call.domain == "test"
assert call.service == "alexa"
assert call.data.get("entity_id") == ["switch.test"]
assert call.data.get("hello") == "virgo"
data = await req.json()
2019-07-31 19:25:30 +00:00
assert data["response"]["card"]["title"] == "Card title for virgo"
assert data["response"]["card"]["content"] == "Card content: virgo"
assert data["response"]["outputSpeech"]["type"] == "PlainText"
assert data["response"]["outputSpeech"]["text"] == "Service called for virgo"
2017-07-30 04:52:26 +00:00
async def test_intent_session_ended_request(alexa_client):
"""Test the request for ending the session."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
2019-07-31 19:25:30 +00:00
"application": {"applicationId": APPLICATION_ID},
"attributes": {
"supportedHoroscopePeriods": {
"daily": True,
"weekly": False,
2019-07-31 19:25:30 +00:00
"monthly": False,
2015-12-13 06:29:02 +00:00
}
},
2019-07-31 19:25:30 +00:00
"user": {"userId": "amzn1.account.AM3B00000000000000000000000"},
},
"request": {
"type": "SessionEndedRequest",
"requestId": REQUEST_ID,
"timestamp": "2015-05-13T12:34:56Z",
2019-07-31 19:25:30 +00:00
"reason": "USER_INITIATED",
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
assert (
data["response"]["outputSpeech"]["text"]
== "This intent is not yet configured within Home Assistant."
)
async def test_intent_from_built_in_intent_library(alexa_client):
"""Test intents from the Built-in Intent Library."""
data = {
2019-07-31 19:25:30 +00:00
"request": {
"intent": {
"name": "AMAZON.PlaybackAction<object@MusicCreativeWork>",
"slots": {
"object.byArtist.name": {
"name": "object.byArtist.name",
"value": "the shins",
},
2019-07-31 19:25:30 +00:00
"object.composer.name": {"name": "object.composer.name"},
"object.contentSource": {"name": "object.contentSource"},
"object.era": {"name": "object.era"},
"object.genre": {"name": "object.genre"},
"object.name": {"name": "object.name"},
"object.owner.name": {"name": "object.owner.name"},
"object.select": {"name": "object.select"},
"object.sort": {"name": "object.sort"},
"object.type": {"name": "object.type", "value": "music"},
},
},
2019-07-31 19:25:30 +00:00
"timestamp": "2016-12-14T23:23:37Z",
"type": "IntentRequest",
"requestId": REQUEST_ID,
},
"session": {
"sessionId": SESSION_ID,
"application": {"applicationId": APPLICATION_ID},
},
}
req = await _intent_req(alexa_client, data)
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
text = data.get("response", {}).get("outputSpeech", {}).get("text")
assert text == "Playing the shins."