core/tests/components/alexa/test_flash_briefings.py

144 lines
4.6 KiB
Python
Raw Normal View History

"""The tests for the Alexa component."""
2023-01-22 16:26:24 +00:00
import datetime
from http import HTTPStatus
import pytest
from homeassistant.components import alexa
from homeassistant.components.alexa import const
from homeassistant.core import callback
from homeassistant.setup import async_setup_component
SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000"
APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe"
REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000"
calls = []
NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3"
@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):
"""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": {
"flash_briefings": {
"password": "pass/abc",
2019-07-31 19:25:30 +00:00
"weather": [
{
"title": "Weekly forecast",
"text": "This week it will be sunny.",
},
{
"title": "Current conditions",
"text": "Currently it is 80 degrees fahrenheit.",
},
],
"news_audio": {
"title": "NPR",
"audio": NPR_NEWS_MP3_URL,
"display_url": "https://npr.org",
"uid": "uuid",
},
}
},
},
2019-07-31 19:25:30 +00:00
)
)
return loop.run_until_complete(hass_client())
def _flash_briefing_req(client, briefing_id, password="pass%2Fabc"):
if password is None:
return client.get(f"/api/alexa/flash_briefings/{briefing_id}")
return client.get(f"/api/alexa/flash_briefings/{briefing_id}?password={password}")
async def test_flash_briefing_invalid_id(alexa_client) -> None:
"""Test an invalid Flash Briefing ID."""
req = await _flash_briefing_req(alexa_client, 10000)
assert req.status == HTTPStatus.NOT_FOUND
text = await req.text()
2019-07-31 19:25:30 +00:00
assert text == ""
async def test_flash_briefing_no_password(alexa_client) -> None:
"""Test for no Flash Briefing password."""
req = await _flash_briefing_req(alexa_client, "weather", password=None)
assert req.status == HTTPStatus.UNAUTHORIZED
text = await req.text()
assert text == ""
async def test_flash_briefing_invalid_password(alexa_client) -> None:
"""Test an invalid Flash Briefing password."""
req = await _flash_briefing_req(alexa_client, "weather", password="wrongpass")
assert req.status == HTTPStatus.UNAUTHORIZED
text = await req.text()
assert text == ""
async def test_flash_briefing_request_for_password(alexa_client) -> None:
"""Test for "password" Flash Briefing."""
req = await _flash_briefing_req(alexa_client, "password")
assert req.status == HTTPStatus.NOT_FOUND
text = await req.text()
assert text == ""
async def test_flash_briefing_date_from_str(alexa_client) -> None:
"""Test the response has a valid date parsed from string."""
req = await _flash_briefing_req(alexa_client, "weather")
assert req.status == HTTPStatus.OK
data = await req.json()
2019-07-31 19:25:30 +00:00
assert isinstance(
datetime.datetime.strptime(
data[0].get(const.ATTR_UPDATE_DATE), const.DATE_FORMAT
),
datetime.datetime,
)
async def test_flash_briefing_valid(alexa_client) -> None:
"""Test the response is valid."""
2019-07-31 19:25:30 +00:00
data = [
{
"titleText": "NPR",
"redirectionURL": "https://npr.org",
"streamUrl": NPR_NEWS_MP3_URL,
"mainText": "",
"uid": "uuid",
"updateDate": "2016-10-10T19:51:42.0Z",
}
]
req = await _flash_briefing_req(alexa_client, "news_audio")
assert req.status == HTTPStatus.OK
json = await req.json()
2019-07-31 19:25:30 +00:00
assert isinstance(
datetime.datetime.strptime(
json[0].get(const.ATTR_UPDATE_DATE), const.DATE_FORMAT
),
datetime.datetime,
)
json[0].pop(const.ATTR_UPDATE_DATE)
data[0].pop(const.ATTR_UPDATE_DATE)
assert json == data