core/tests/util/test_location.py

113 lines
3.4 KiB
Python
Raw Normal View History

2016-05-29 18:55:16 +00:00
"""Test Home Assistant location util methods."""
2021-07-28 04:05:16 +00:00
from unittest.mock import Mock, patch
2021-01-01 21:31:56 +00:00
import aiohttp
import pytest
2016-05-29 18:55:16 +00:00
from homeassistant.helpers.aiohttp_client import async_get_clientsession
2016-05-29 18:55:16 +00:00
import homeassistant.util.location as location_util
2020-04-25 22:52:50 +00:00
from tests.common import load_fixture
2016-05-29 18:55:16 +00:00
# Paris
COORDINATES_PARIS = (48.864716, 2.349014)
# New York
COORDINATES_NEW_YORK = (40.730610, -73.935242)
# Results for the assertion (vincenty algorithm):
# Distance [km] Distance [miles]
# [0] 5846.39 3632.78
# [1] 5851 3635
#
# [0]: http://boulter.com/gps/distance/
# [1]: https://www.wolframalpha.com/input/?i=from+paris+to+new+york
DISTANCE_KM = 5846.39
DISTANCE_MILES = 3632.78
@pytest.fixture
async def session(hass):
"""Return aioclient session."""
return async_get_clientsession(hass)
@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
async def raising_session(event_loop):
"""Return an aioclient session that only fails."""
return Mock(get=Mock(side_effect=aiohttp.ClientError))
def test_get_distance_to_same_place():
"""Test getting the distance."""
meters = location_util.distance(
2019-07-31 19:25:30 +00:00
COORDINATES_PARIS[0],
COORDINATES_PARIS[1],
COORDINATES_PARIS[0],
COORDINATES_PARIS[1],
)
assert meters == 0
def test_get_distance():
"""Test getting the distance."""
meters = location_util.distance(
2019-07-31 19:25:30 +00:00
COORDINATES_PARIS[0],
COORDINATES_PARIS[1],
COORDINATES_NEW_YORK[0],
COORDINATES_NEW_YORK[1],
)
2019-07-31 19:25:30 +00:00
assert meters / 1000 - DISTANCE_KM < 0.01
def test_get_kilometers():
"""Test getting the distance between given coordinates in km."""
2019-07-31 19:25:30 +00:00
kilometers = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK)
assert round(kilometers, 2) == DISTANCE_KM
def test_get_miles():
"""Test getting the distance between given coordinates in miles."""
2019-07-31 19:25:30 +00:00
miles = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
assert round(miles, 2) == DISTANCE_MILES
async def test_detect_location_info_whoami(aioclient_mock, session):
2022-03-07 10:11:25 +00:00
"""Test detect location info using services.home-assistant.io/whoami."""
aioclient_mock.get(location_util.WHOAMI_URL, text=load_fixture("whoami.json"))
2021-07-28 04:05:16 +00:00
with patch("homeassistant.util.location.HA_VERSION", "1.0"):
info = await location_util.async_detect_location_info(session, _test_real=True)
assert str(aioclient_mock.mock_calls[-1][1]) == location_util.WHOAMI_URL
assert info is not None
2019-07-31 19:25:30 +00:00
assert info.ip == "1.2.3.4"
assert info.country_code == "XX"
2021-07-28 04:05:16 +00:00
assert info.currency == "XXX"
assert info.region_code == "00"
assert info.city == "Gotham"
assert info.zip_code == "12345"
assert info.time_zone == "Earth/Gotham"
assert info.latitude == 12.34567
assert info.longitude == 12.34567
assert info.use_metric
2021-07-28 04:05:16 +00:00
async def test_dev_url(aioclient_mock, session):
"""Test usage of dev URL."""
aioclient_mock.get(location_util.WHOAMI_URL_DEV, text=load_fixture("whoami.json"))
with patch("homeassistant.util.location.HA_VERSION", "1.0.dev0"):
info = await location_util.async_detect_location_info(session, _test_real=True)
assert str(aioclient_mock.mock_calls[-1][1]) == location_util.WHOAMI_URL_DEV
assert info.currency == "XXX"
async def test_whoami_query_raises(raising_session):
"""Test whoami query when the request to API fails."""
info = await location_util._get_whoami(raising_session)
assert info is None