core/tests/components/meraki/test_device_tracker.py

142 lines
4.5 KiB
Python
Raw Normal View History

"""The tests the for Meraki device tracker."""
from http import HTTPStatus
import json
import pytest
import homeassistant.components.device_tracker as device_tracker
from homeassistant.components.device_tracker import legacy
from homeassistant.components.meraki.device_tracker import (
CONF_SECRET,
CONF_VALIDATOR,
URL,
)
from homeassistant.const import CONF_PLATFORM
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
@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 meraki_client(event_loop, hass, hass_client):
"""Meraki mock client."""
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
assert loop.run_until_complete(
async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "meraki",
CONF_VALIDATOR: "validator",
CONF_SECRET: "secret",
}
},
)
)
return loop.run_until_complete(hass_client())
async def test_invalid_or_missing_data(
mock_device_tracker_conf: list[legacy.Device], meraki_client
) -> None:
"""Test validator with invalid or missing data."""
req = await meraki_client.get(URL)
text = await req.text()
assert req.status == HTTPStatus.OK
assert text == "validator"
req = await meraki_client.post(URL, data=b"invalid")
text = await req.json()
assert req.status == HTTPStatus.BAD_REQUEST
assert text["message"] == "Invalid JSON"
req = await meraki_client.post(URL, data=b"{}")
text = await req.json()
assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "No secret"
data = {"version": "1.0", "secret": "secret"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid version"
data = {"version": "2.0", "secret": "invalid"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid secret"
data = {"version": "2.0", "secret": "secret", "type": "InvalidType"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == HTTPStatus.UNPROCESSABLE_ENTITY
assert text["message"] == "Invalid device type"
data = {
"version": "2.0",
"secret": "secret",
"type": "BluetoothDevicesSeen",
"data": {"observations": []},
}
req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == HTTPStatus.OK
async def test_data_will_be_saved(
mock_device_tracker_conf: list[legacy.Device], hass: HomeAssistant, meraki_client
) -> None:
"""Test with valid data."""
data = {
"version": "2.0",
"secret": "secret",
"type": "DevicesSeen",
"data": {
"observations": [
{
"location": {
"lat": "51.5355157",
"lng": "21.0699035",
"unc": "46.3610585",
},
"seenTime": "2016-09-12T16:23:13Z",
"ssid": "ssid",
"os": "HA",
"ipv6": "2607:f0d0:1002:51::4/64",
"clientMac": "00:26:ab:b8:a9:a4",
"seenEpoch": "147369739",
"rssi": "20",
"manufacturer": "Seiko Epson",
},
{
"location": {
"lat": "51.5355357",
"lng": "21.0699635",
"unc": "46.3610585",
},
"seenTime": "2016-09-12T16:21:13Z",
"ssid": "ssid",
"os": "HA",
"ipv4": "192.168.0.1",
"clientMac": "00:26:ab:b8:a9:a5",
"seenEpoch": "147369750",
"rssi": "20",
"manufacturer": "Seiko Epson",
},
]
},
}
req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == HTTPStatus.OK
await hass.async_block_till_done()
state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4")
).state
assert state_name == "home"
state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a5")
).state
assert state_name == "home"