No longer rely on requests (#23685)
* No longer rely on requests * Lint * Missed a few parts * Fix types * Fix more types * Update __main__.py * Fix tests * Lint * Fix script
This commit is contained in:
1 parent
f019e2a204
commit
cc13713abd
10 files changed
+271
-197
No files matched your search
+4
-2
@@ -42,8 +42,10 @@ def check_real(func):
|
||||
|
||||
|
||||
# Guard a few functions that would make network connections
|
||||
location.detect_location_info = check_real(location.detect_location_info)
|
||||
location.elevation = check_real(location.elevation)
|
||||
location.async_detect_location_info = \
|
||||
check_real(location.async_detect_location_info)
|
||||
location.async_get_elevation = \
|
||||
check_real(location.async_get_elevation)
|
||||
util.get_local_ip = lambda: '127.0.0.1'
|
||||
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ _LOGGER = logging.getLogger(__name__)
|
||||
# prevent .HA_VERSION file from being written
|
||||
@patch(
|
||||
'homeassistant.bootstrap.conf_util.process_ha_config_upgrade', Mock())
|
||||
@patch('homeassistant.util.location.detect_location_info',
|
||||
Mock(return_value=None))
|
||||
@patch('homeassistant.util.location.async_detect_location_info',
|
||||
Mock(return_value=mock_coro(None)))
|
||||
@patch('os.path.isfile', Mock(return_value=True))
|
||||
@patch('os.access', Mock(return_value=True))
|
||||
@patch('homeassistant.bootstrap.async_enable_logging',
|
||||
|
||||
+34
-32
@@ -34,7 +34,7 @@ from homeassistant.components.config.customize import (
|
||||
import homeassistant.scripts.check_config as check_config
|
||||
|
||||
from tests.common import (
|
||||
get_test_config_dir, patch_yaml_files)
|
||||
get_test_config_dir, patch_yaml_files, mock_coro)
|
||||
|
||||
CONFIG_DIR = get_test_config_dir()
|
||||
YAML_PATH = os.path.join(CONFIG_DIR, config_util.YAML_CONFIG_FILE)
|
||||
@@ -79,9 +79,9 @@ def teardown():
|
||||
os.remove(CUSTOMIZE_PATH)
|
||||
|
||||
|
||||
def test_create_default_config():
|
||||
async def test_create_default_config(hass):
|
||||
"""Test creation of default config."""
|
||||
config_util.create_default_config(CONFIG_DIR, False)
|
||||
await config_util.async_create_default_config(hass, CONFIG_DIR, False)
|
||||
|
||||
assert os.path.isfile(YAML_PATH)
|
||||
assert os.path.isfile(SECRET_PATH)
|
||||
@@ -98,22 +98,22 @@ def test_find_config_file_yaml():
|
||||
assert YAML_PATH == config_util.find_config_file(CONFIG_DIR)
|
||||
|
||||
|
||||
@mock.patch('builtins.print')
|
||||
def test_ensure_config_exists_creates_config(mock_print):
|
||||
async def test_ensure_config_exists_creates_config(hass):
|
||||
"""Test that calling ensure_config_exists.
|
||||
|
||||
If not creates a new config file.
|
||||
"""
|
||||
config_util.ensure_config_exists(CONFIG_DIR, False)
|
||||
with mock.patch('builtins.print') as mock_print:
|
||||
await config_util.async_ensure_config_exists(hass, CONFIG_DIR, False)
|
||||
|
||||
assert os.path.isfile(YAML_PATH)
|
||||
assert mock_print.called
|
||||
|
||||
|
||||
def test_ensure_config_exists_uses_existing_config():
|
||||
async def test_ensure_config_exists_uses_existing_config(hass):
|
||||
"""Test that calling ensure_config_exists uses existing config."""
|
||||
create_file(YAML_PATH)
|
||||
config_util.ensure_config_exists(CONFIG_DIR, False)
|
||||
await config_util.async_ensure_config_exists(hass, CONFIG_DIR, False)
|
||||
|
||||
with open(YAML_PATH) as f:
|
||||
content = f.read()
|
||||
@@ -166,17 +166,17 @@ def test_load_yaml_config_preserves_key_order():
|
||||
list(config_util.load_yaml_config_file(YAML_PATH).items())
|
||||
|
||||
|
||||
@mock.patch('homeassistant.util.location.detect_location_info',
|
||||
return_value=location_util.LocationInfo(
|
||||
'0.0.0.0', 'US', 'United States', 'CA', 'California',
|
||||
'San Diego', '92122', 'America/Los_Angeles', 32.8594,
|
||||
-117.2073, True))
|
||||
@mock.patch('homeassistant.util.location.elevation', return_value=101)
|
||||
@mock.patch('builtins.print')
|
||||
def test_create_default_config_detect_location(mock_detect,
|
||||
mock_elev, mock_print):
|
||||
async def test_create_default_config_detect_location(hass):
|
||||
"""Test that detect location sets the correct config keys."""
|
||||
config_util.ensure_config_exists(CONFIG_DIR)
|
||||
with mock.patch('homeassistant.util.location.async_detect_location_info',
|
||||
return_value=mock_coro(location_util.LocationInfo(
|
||||
'0.0.0.0', 'US', 'United States', 'CA', 'California',
|
||||
'San Diego', '92122', 'America/Los_Angeles', 32.8594,
|
||||
-117.2073, True))), \
|
||||
mock.patch('homeassistant.util.location.async_get_elevation',
|
||||
return_value=mock_coro(101)), \
|
||||
mock.patch('builtins.print') as mock_print:
|
||||
await config_util.async_ensure_config_exists(hass, CONFIG_DIR)
|
||||
|
||||
config = config_util.load_yaml_config_file(YAML_PATH)
|
||||
|
||||
@@ -198,14 +198,14 @@ def test_create_default_config_detect_location(mock_detect,
|
||||
assert mock_print.called
|
||||
|
||||
|
||||
@mock.patch('builtins.print')
|
||||
def test_create_default_config_returns_none_if_write_error(mock_print):
|
||||
async def test_create_default_config_returns_none_if_write_error(hass):
|
||||
"""Test the writing of a default configuration.
|
||||
|
||||
Non existing folder returns None.
|
||||
"""
|
||||
assert config_util.create_default_config(
|
||||
os.path.join(CONFIG_DIR, 'non_existing_dir/'), False) is None
|
||||
with mock.patch('builtins.print') as mock_print:
|
||||
assert await config_util.async_create_default_config(
|
||||
hass, os.path.join(CONFIG_DIR, 'non_existing_dir/'), False) is None
|
||||
assert mock_print.called
|
||||
|
||||
|
||||
@@ -490,13 +490,14 @@ async def test_loading_configuration_from_packages(hass):
|
||||
})
|
||||
|
||||
|
||||
@asynctest.mock.patch('homeassistant.util.location.detect_location_info',
|
||||
autospec=True, return_value=location_util.LocationInfo(
|
||||
'0.0.0.0', 'US', 'United States', 'CA', 'California',
|
||||
'San Diego', '92122', 'America/Los_Angeles', 32.8594,
|
||||
-117.2073, True))
|
||||
@asynctest.mock.patch('homeassistant.util.location.elevation',
|
||||
autospec=True, return_value=101)
|
||||
@asynctest.mock.patch(
|
||||
'homeassistant.util.location.async_detect_location_info',
|
||||
autospec=True, return_value=mock_coro(location_util.LocationInfo(
|
||||
'0.0.0.0', 'US', 'United States', 'CA',
|
||||
'California', 'San Diego', '92122',
|
||||
'America/Los_Angeles', 32.8594, -117.2073, True)))
|
||||
@asynctest.mock.patch('homeassistant.util.location.async_get_elevation',
|
||||
autospec=True, return_value=mock_coro(101))
|
||||
async def test_discovering_configuration(mock_detect, mock_elevation, hass):
|
||||
"""Test auto discovery for missing core configs."""
|
||||
hass.config.latitude = None
|
||||
@@ -516,9 +517,10 @@ async def test_discovering_configuration(mock_detect, mock_elevation, hass):
|
||||
assert hass.config.time_zone.zone == 'America/Los_Angeles'
|
||||
|
||||
|
||||
@asynctest.mock.patch('homeassistant.util.location.detect_location_info',
|
||||
autospec=True, return_value=None)
|
||||
@asynctest.mock.patch('homeassistant.util.location.elevation', return_value=0)
|
||||
@asynctest.mock.patch('homeassistant.util.location.async_detect_location_info',
|
||||
autospec=True, return_value=mock_coro(None))
|
||||
@asynctest.mock.patch('homeassistant.util.location.async_get_elevation',
|
||||
return_value=mock_coro(0))
|
||||
async def test_discovering_configuration_auto_detect_fails(mock_detect,
|
||||
mock_elevation,
|
||||
hass):
|
||||
|
||||
+122
-104
@@ -1,13 +1,12 @@
|
||||
"""Test Home Assistant location util methods."""
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import patch, Mock
|
||||
|
||||
import requests
|
||||
import requests_mock
|
||||
import aiohttp
|
||||
import pytest
|
||||
|
||||
import homeassistant.util.location as location_util
|
||||
|
||||
from tests.common import load_fixture
|
||||
from tests.common import load_fixture, mock_coro
|
||||
|
||||
# Paris
|
||||
COORDINATES_PARIS = (48.864716, 2.349014)
|
||||
@@ -25,120 +24,139 @@ DISTANCE_KM = 5846.39
|
||||
DISTANCE_MILES = 3632.78
|
||||
|
||||
|
||||
class TestLocationUtil(TestCase):
|
||||
"""Test util location methods."""
|
||||
@pytest.fixture
|
||||
async def session(hass):
|
||||
"""Return aioclient session."""
|
||||
return hass.helpers.aiohttp_client.async_get_clientsession()
|
||||
|
||||
def test_get_distance_to_same_place(self):
|
||||
"""Test getting the distance."""
|
||||
meters = location_util.distance(
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1],
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1])
|
||||
|
||||
assert meters == 0
|
||||
@pytest.fixture
|
||||
async def raising_session(loop):
|
||||
"""Return an aioclient session that only fails."""
|
||||
return Mock(get=Mock(side_effect=aiohttp.ClientError))
|
||||
|
||||
def test_get_distance(self):
|
||||
"""Test getting the distance."""
|
||||
meters = location_util.distance(
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1],
|
||||
COORDINATES_NEW_YORK[0], COORDINATES_NEW_YORK[1])
|
||||
|
||||
assert meters/1000 - DISTANCE_KM < 0.01
|
||||
def test_get_distance_to_same_place():
|
||||
"""Test getting the distance."""
|
||||
meters = location_util.distance(
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1],
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1])
|
||||
|
||||
def test_get_kilometers(self):
|
||||
"""Test getting the distance between given coordinates in km."""
|
||||
kilometers = location_util.vincenty(
|
||||
COORDINATES_PARIS, COORDINATES_NEW_YORK)
|
||||
assert round(kilometers, 2) == DISTANCE_KM
|
||||
assert meters == 0
|
||||
|
||||
def test_get_miles(self):
|
||||
"""Test getting the distance between given coordinates in miles."""
|
||||
miles = location_util.vincenty(
|
||||
COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
|
||||
assert round(miles, 2) == DISTANCE_MILES
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_detect_location_info_ipapi(self, m):
|
||||
"""Test detect location info using ipapi.co."""
|
||||
m.get(
|
||||
location_util.IPAPI, text=load_fixture('ipapi.co.json'))
|
||||
def test_get_distance():
|
||||
"""Test getting the distance."""
|
||||
meters = location_util.distance(
|
||||
COORDINATES_PARIS[0], COORDINATES_PARIS[1],
|
||||
COORDINATES_NEW_YORK[0], COORDINATES_NEW_YORK[1])
|
||||
|
||||
info = location_util.detect_location_info(_test_real=True)
|
||||
assert meters/1000 - DISTANCE_KM < 0.01
|
||||
|
||||
assert info is not None
|
||||
assert info.ip == '1.2.3.4'
|
||||
assert info.country_code == 'CH'
|
||||
assert info.country_name == 'Switzerland'
|
||||
assert info.region_code == 'BE'
|
||||
assert info.region_name == 'Bern'
|
||||
assert info.city == 'Bern'
|
||||
assert info.zip_code == '3000'
|
||||
assert info.time_zone == 'Europe/Zurich'
|
||||
assert info.latitude == 46.9480278
|
||||
assert info.longitude == 7.4490812
|
||||
assert info.use_metric
|
||||
|
||||
@requests_mock.Mocker()
|
||||
@patch('homeassistant.util.location._get_ipapi', return_value=None)
|
||||
def test_detect_location_info_ip_api(self, mock_req, mock_ipapi):
|
||||
"""Test detect location info using ip-api.com."""
|
||||
mock_req.get(
|
||||
location_util.IP_API, text=load_fixture('ip-api.com.json'))
|
||||
def test_get_kilometers():
|
||||
"""Test getting the distance between given coordinates in km."""
|
||||
kilometers = location_util.vincenty(
|
||||
COORDINATES_PARIS, COORDINATES_NEW_YORK)
|
||||
assert round(kilometers, 2) == DISTANCE_KM
|
||||
|
||||
info = location_util.detect_location_info(_test_real=True)
|
||||
|
||||
assert info is not None
|
||||
assert info.ip == '1.2.3.4'
|
||||
assert info.country_code == 'US'
|
||||
assert info.country_name == 'United States'
|
||||
assert info.region_code == 'CA'
|
||||
assert info.region_name == 'California'
|
||||
assert info.city == 'San Diego'
|
||||
assert info.zip_code == '92122'
|
||||
assert info.time_zone == 'America/Los_Angeles'
|
||||
assert info.latitude == 32.8594
|
||||
assert info.longitude == -117.2073
|
||||
assert not info.use_metric
|
||||
def test_get_miles():
|
||||
"""Test getting the distance between given coordinates in miles."""
|
||||
miles = location_util.vincenty(
|
||||
COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
|
||||
assert round(miles, 2) == DISTANCE_MILES
|
||||
|
||||
@patch('homeassistant.util.location.elevation', return_value=0)
|
||||
@patch('homeassistant.util.location._get_ipapi', return_value=None)
|
||||
@patch('homeassistant.util.location._get_ip_api', return_value=None)
|
||||
def test_detect_location_info_both_queries_fail(
|
||||
self, mock_ipapi, mock_ip_api, mock_elevation):
|
||||
"""Ensure we return None if both queries fail."""
|
||||
info = location_util.detect_location_info(_test_real=True)
|
||||
assert info is None
|
||||
|
||||
@patch('homeassistant.util.location.requests.get',
|
||||
side_effect=requests.RequestException)
|
||||
def test_freegeoip_query_raises(self, mock_get):
|
||||
"""Test ipapi.co query when the request to API fails."""
|
||||
info = location_util._get_ipapi()
|
||||
assert info is None
|
||||
async def test_detect_location_info_ipapi(aioclient_mock, session):
|
||||
"""Test detect location info using ipapi.co."""
|
||||
aioclient_mock.get(
|
||||
location_util.IPAPI, text=load_fixture('ipapi.co.json'))
|
||||
|
||||
@patch('homeassistant.util.location.requests.get',
|
||||
side_effect=requests.RequestException)
|
||||
def test_ip_api_query_raises(self, mock_get):
|
||||
"""Test ip api query when the request to API fails."""
|
||||
info = location_util._get_ip_api()
|
||||
assert info is None
|
||||
info = await location_util.async_detect_location_info(
|
||||
session, _test_real=True)
|
||||
|
||||
@patch('homeassistant.util.location.requests.get',
|
||||
side_effect=requests.RequestException)
|
||||
def test_elevation_query_raises(self, mock_get):
|
||||
"""Test elevation when the request to API fails."""
|
||||
elevation = location_util.elevation(10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
assert info is not None
|
||||
assert info.ip == '1.2.3.4'
|
||||
assert info.country_code == 'CH'
|
||||
assert info.country_name == 'Switzerland'
|
||||
assert info.region_code == 'BE'
|
||||
assert info.region_name == 'Bern'
|
||||
assert info.city == 'Bern'
|
||||
assert info.zip_code == '3000'
|
||||
assert info.time_zone == 'Europe/Zurich'
|
||||
assert info.latitude == 46.9480278
|
||||
assert info.longitude == 7.4490812
|
||||
assert info.use_metric
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_elevation_query_fails(self, mock_req):
|
||||
"""Test elevation when the request to API fails."""
|
||||
mock_req.get(location_util.ELEVATION_URL, text='{}', status_code=401)
|
||||
elevation = location_util.elevation(10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_elevation_query_nonjson(self, mock_req):
|
||||
"""Test if elevation API returns a non JSON value."""
|
||||
mock_req.get(location_util.ELEVATION_URL, text='{ I am not JSON }')
|
||||
elevation = location_util.elevation(10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
async def test_detect_location_info_ip_api(aioclient_mock, session):
|
||||
"""Test detect location info using ip-api.com."""
|
||||
aioclient_mock.get(
|
||||
location_util.IP_API, text=load_fixture('ip-api.com.json'))
|
||||
|
||||
with patch('homeassistant.util.location._get_ipapi',
|
||||
return_value=mock_coro(None)):
|
||||
info = await location_util.async_detect_location_info(
|
||||
session, _test_real=True)
|
||||
|
||||
assert info is not None
|
||||
assert info.ip == '1.2.3.4'
|
||||
assert info.country_code == 'US'
|
||||
assert info.country_name == 'United States'
|
||||
assert info.region_code == 'CA'
|
||||
assert info.region_name == 'California'
|
||||
assert info.city == 'San Diego'
|
||||
assert info.zip_code == '92122'
|
||||
assert info.time_zone == 'America/Los_Angeles'
|
||||
assert info.latitude == 32.8594
|
||||
assert info.longitude == -117.2073
|
||||
assert not info.use_metric
|
||||
|
||||
|
||||
async def test_detect_location_info_both_queries_fail(session):
|
||||
"""Ensure we return None if both queries fail."""
|
||||
with patch('homeassistant.util.location.async_get_elevation',
|
||||
return_value=mock_coro(0)), \
|
||||
patch('homeassistant.util.location._get_ipapi',
|
||||
return_value=mock_coro(None)), \
|
||||
patch('homeassistant.util.location._get_ip_api',
|
||||
return_value=mock_coro(None)):
|
||||
info = await location_util.async_detect_location_info(
|
||||
session, _test_real=True)
|
||||
assert info is None
|
||||
|
||||
|
||||
async def test_freegeoip_query_raises(raising_session):
|
||||
"""Test ipapi.co query when the request to API fails."""
|
||||
info = await location_util._get_ipapi(raising_session)
|
||||
assert info is None
|
||||
|
||||
|
||||
async def test_ip_api_query_raises(raising_session):
|
||||
"""Test ip api query when the request to API fails."""
|
||||
info = await location_util._get_ip_api(raising_session)
|
||||
assert info is None
|
||||
|
||||
|
||||
async def test_elevation_query_raises(raising_session):
|
||||
"""Test elevation when the request to API fails."""
|
||||
elevation = await location_util.async_get_elevation(
|
||||
raising_session, 10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
|
||||
|
||||
async def test_elevation_query_fails(aioclient_mock, session):
|
||||
"""Test elevation when the request to API fails."""
|
||||
aioclient_mock.get(location_util.ELEVATION_URL, text='{}', status=401)
|
||||
elevation = await location_util.async_get_elevation(
|
||||
session, 10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
|
||||
|
||||
async def test_elevation_query_nonjson(aioclient_mock, session):
|
||||
"""Test if elevation API returns a non JSON value."""
|
||||
aioclient_mock.get(location_util.ELEVATION_URL, text='{ I am not JSON }')
|
||||
elevation = await location_util.async_get_elevation(
|
||||
session, 10, 10, _test_real=True)
|
||||
assert elevation == 0
|
||||
Reference in new issue
Block a user