Move HomeAssistantView to separate file. Convert http to async syntax. [skip ci] (#12982)

* Move HomeAssistantView to separate file. Convert http to async syntax.

* pylint

* websocket api

* update emulated_hue for async/await

* Lint
This commit is contained in:
Boyi C authored and Paulus Schoutsen committed 2018-03-08 17:51:49 -08:00
1 parent 2ee73ca911
commit 321eb2ec6f
17 files changed
+292 -344

No files matched your search

+3 -6
View File
@@ -1,5 +1,4 @@
"""Tests for the HTTP component."""
import asyncio
from ipaddress import ip_address
from aiohttp import web
@@ -18,18 +17,16 @@ def mock_real_ip(app):
nonlocal ip_to_mock
ip_to_mock = value
@asyncio.coroutine
@web.middleware
def mock_real_ip(request, handler):
async def mock_real_ip(request, handler):
"""Mock Real IP middleware."""
nonlocal ip_to_mock
request[KEY_REAL_IP] = ip_address(ip_to_mock)
return (yield from handler(request))
return (await handler(request))
@asyncio.coroutine
def real_ip_startup(app):
async def real_ip_startup(app):
"""Startup of real ip."""
app.middlewares.insert(0, mock_real_ip)
+25 -33
View File
@@ -1,6 +1,5 @@
"""The tests for the Home Assistant HTTP component."""
# pylint: disable=protected-access
import asyncio
from ipaddress import ip_network
from unittest.mock import patch
@@ -30,8 +29,7 @@ TRUSTED_ADDRESSES = ['100.64.0.1', '192.0.2.100', 'FD01:DB8::1',
UNTRUSTED_ADDRESSES = ['198.51.100.1', '2001:DB8:FA1::1', '127.0.0.1', '::1']
@asyncio.coroutine
def mock_handler(request):
async def mock_handler(request):
"""Return if request was authenticated."""
if not request[KEY_AUTHENTICATED]:
raise HTTPUnauthorized
@@ -47,84 +45,79 @@ def app():
return app
@asyncio.coroutine
def test_auth_middleware_loaded_by_default(hass):
async def test_auth_middleware_loaded_by_default(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_auth') as mock_setup:
yield from async_setup_component(hass, 'http', {
await async_setup_component(hass, 'http', {
'http': {}
})
assert len(mock_setup.mock_calls) == 1
@asyncio.coroutine
def test_access_without_password(app, test_client):
async def test_access_without_password(app, test_client):
"""Test access without password."""
setup_auth(app, [], None)
client = yield from test_client(app)
client = await test_client(app)
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 200
@asyncio.coroutine
def test_access_with_password_in_header(app, test_client):
async def test_access_with_password_in_header(app, test_client):
"""Test access with password in URL."""
setup_auth(app, [], API_PASSWORD)
client = yield from test_client(app)
client = await test_client(app)
req = yield from client.get(
req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
assert req.status == 200
req = yield from client.get(
req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: 'wrong-pass'})
assert req.status == 401
@asyncio.coroutine
def test_access_with_password_in_query(app, test_client):
async def test_access_with_password_in_query(app, test_client):
"""Test access without password."""
setup_auth(app, [], API_PASSWORD)
client = yield from test_client(app)
client = await test_client(app)
resp = yield from client.get('/', params={
resp = await client.get('/', params={
'api_password': API_PASSWORD
})
assert resp.status == 200
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 401
resp = yield from client.get('/', params={
resp = await client.get('/', params={
'api_password': 'wrong-password'
})
assert resp.status == 401
@asyncio.coroutine
def test_basic_auth_works(app, test_client):
async def test_basic_auth_works(app, test_client):
"""Test access with basic authentication."""
setup_auth(app, [], API_PASSWORD)
client = yield from test_client(app)
client = await test_client(app)
req = yield from client.get(
req = await client.get(
'/',
auth=BasicAuth('homeassistant', API_PASSWORD))
assert req.status == 200
req = yield from client.get(
req = await client.get(
'/',
auth=BasicAuth('wrong_username', API_PASSWORD))
assert req.status == 401
req = yield from client.get(
req = await client.get(
'/',
auth=BasicAuth('homeassistant', 'wrong password'))
assert req.status == 401
req = yield from client.get(
req = await client.get(
'/',
headers={
'authorization': 'NotBasic abcdefg'
@@ -132,8 +125,7 @@ def test_basic_auth_works(app, test_client):
assert req.status == 401
@asyncio.coroutine
def test_access_with_trusted_ip(test_client):
async def test_access_with_trusted_ip(test_client):
"""Test access with an untrusted ip address."""
app = web.Application()
app.router.add_get('/', mock_handler)
@@ -141,16 +133,16 @@ def test_access_with_trusted_ip(test_client):
setup_auth(app, TRUSTED_NETWORKS, 'some-pass')
set_mock_ip = mock_real_ip(app)
client = yield from test_client(app)
client = await test_client(app)
for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 401, \
"{} shouldn't be trusted".format(remote_addr)
for remote_addr in TRUSTED_ADDRESSES:
set_mock_ip(remote_addr)
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 200, \
"{} should be trusted".format(remote_addr)
+13 -19
View File
@@ -1,6 +1,5 @@
"""The tests for the Home Assistant HTTP component."""
# pylint: disable=protected-access
import asyncio
from unittest.mock import patch, mock_open
from aiohttp import web
@@ -16,8 +15,7 @@ from . import mock_real_ip
BANNED_IPS = ['200.201.202.203', '100.64.0.2']
@asyncio.coroutine
def test_access_from_banned_ip(hass, test_client):
async def test_access_from_banned_ip(hass, test_client):
"""Test accessing to server from banned IP. Both trusted and not."""
app = web.Application()
setup_bans(hass, app, 5)
@@ -26,19 +24,18 @@ def test_access_from_banned_ip(hass, test_client):
with patch('homeassistant.components.http.ban.load_ip_bans_config',
return_value=[IpBan(banned_ip) for banned_ip
in BANNED_IPS]):
client = yield from test_client(app)
client = await test_client(app)
for remote_addr in BANNED_IPS:
set_real_ip(remote_addr)
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 403
@asyncio.coroutine
def test_ban_middleware_not_loaded_by_config(hass):
async def test_ban_middleware_not_loaded_by_config(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_bans') as mock_setup:
yield from async_setup_component(hass, 'http', {
await async_setup_component(hass, 'http', {
'http': {
http.CONF_IP_BAN_ENABLED: False,
}
@@ -47,25 +44,22 @@ def test_ban_middleware_not_loaded_by_config(hass):
assert len(mock_setup.mock_calls) == 0
@asyncio.coroutine
def test_ban_middleware_loaded_by_default(hass):
async def test_ban_middleware_loaded_by_default(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_bans') as mock_setup:
yield from async_setup_component(hass, 'http', {
await async_setup_component(hass, 'http', {
'http': {}
})
assert len(mock_setup.mock_calls) == 1
@asyncio.coroutine
def test_ip_bans_file_creation(hass, test_client):
async def test_ip_bans_file_creation(hass, test_client):
"""Testing if banned IP file created."""
app = web.Application()
app['hass'] = hass
@asyncio.coroutine
def unauth_handler(request):
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
@@ -76,21 +70,21 @@ def test_ip_bans_file_creation(hass, test_client):
with patch('homeassistant.components.http.ban.load_ip_bans_config',
return_value=[IpBan(banned_ip) for banned_ip
in BANNED_IPS]):
client = yield from test_client(app)
client = await test_client(app)
m = mock_open()
with patch('homeassistant.components.http.ban.open', m, create=True):
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 401
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS)
assert m.call_count == 0
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 401
assert len(app[KEY_BANNED_IPS]) == len(BANNED_IPS) + 1
m.assert_called_once_with(hass.config.path(IP_BANS_FILE), 'a')
resp = yield from client.get('/')
resp = await client.get('/')
assert resp.status == 403
assert m.call_count == 1
+11 -17
View File
@@ -1,5 +1,4 @@
"""Test cors for the HTTP component."""
import asyncio
from unittest.mock import patch
from aiohttp import web
@@ -20,22 +19,20 @@ from homeassistant.components.http.cors import setup_cors
TRUSTED_ORIGIN = 'https://home-assistant.io'
@asyncio.coroutine
def test_cors_middleware_not_loaded_by_default(hass):
async def test_cors_middleware_not_loaded_by_default(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_cors') as mock_setup:
yield from async_setup_component(hass, 'http', {
await async_setup_component(hass, 'http', {
'http': {}
})
assert len(mock_setup.mock_calls) == 0
@asyncio.coroutine
def test_cors_middleware_loaded_from_config(hass):
async def test_cors_middleware_loaded_from_config(hass):
"""Test accessing to server from banned IP when feature is off."""
with patch('homeassistant.components.http.setup_cors') as mock_setup:
yield from async_setup_component(hass, 'http', {
await async_setup_component(hass, 'http', {
'http': {
'cors_allowed_origins': ['http://home-assistant.io']
}
@@ -44,8 +41,7 @@ def test_cors_middleware_loaded_from_config(hass):
assert len(mock_setup.mock_calls) == 1
@asyncio.coroutine
def mock_handler(request):
async def mock_handler(request):
"""Return if request was authenticated."""
return web.Response(status=200)
@@ -59,10 +55,9 @@ def client(loop, test_client):
return loop.run_until_complete(test_client(app))
@asyncio.coroutine
def test_cors_requests(client):
async def test_cors_requests(client):
"""Test cross origin requests."""
req = yield from client.get('/', headers={
req = await client.get('/', headers={
ORIGIN: TRUSTED_ORIGIN
})
assert req.status == 200
@@ -70,7 +65,7 @@ def test_cors_requests(client):
TRUSTED_ORIGIN
# With password in URL
req = yield from client.get('/', params={
req = await client.get('/', params={
'api_password': 'some-pass'
}, headers={
ORIGIN: TRUSTED_ORIGIN
@@ -80,7 +75,7 @@ def test_cors_requests(client):
TRUSTED_ORIGIN
# With password in headers
req = yield from client.get('/', headers={
req = await client.get('/', headers={
HTTP_HEADER_HA_AUTH: 'some-pass',
ORIGIN: TRUSTED_ORIGIN
})
@@ -89,10 +84,9 @@ def test_cors_requests(client):
TRUSTED_ORIGIN
@asyncio.coroutine
def test_cors_preflight_allowed(client):
async def test_cors_preflight_allowed(client):
"""Test cross origin resource sharing preflight (OPTIONS) request."""
req = yield from client.options('/', headers={
req = await client.options('/', headers={
ORIGIN: TRUSTED_ORIGIN,
ACCESS_CONTROL_REQUEST_METHOD: 'GET',
ACCESS_CONTROL_REQUEST_HEADERS: 'x-ha-access'
+13 -18
View File
@@ -1,5 +1,4 @@
"""Test data validator decorator."""
import asyncio
from unittest.mock import Mock
from aiohttp import web
@@ -9,8 +8,7 @@ from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
@asyncio.coroutine
def get_client(test_client, validator):
async def get_client(test_client, validator):
"""Generate a client that hits a view decorated with validator."""
app = web.Application()
app['hass'] = Mock(is_running=True)
@@ -20,58 +18,55 @@ def get_client(test_client, validator):
name = 'test'
requires_auth = False
@asyncio.coroutine
@validator
def post(self, request, data):
async def post(self, request, data):
"""Test method."""
return b''
TestView().register(app.router)
client = yield from test_client(app)
client = await test_client(app)
return client
@asyncio.coroutine
def test_validator(test_client):
async def test_validator(test_client):
"""Test the validator."""
client = yield from get_client(
client = await get_client(
test_client, RequestDataValidator(vol.Schema({
vol.Required('test'): str
})))
resp = yield from client.post('/', json={
resp = await client.post('/', json={
'test': 'bla'
})
assert resp.status == 200
resp = yield from client.post('/', json={
resp = await client.post('/', json={
'test': 100
})
assert resp.status == 400
resp = yield from client.post('/')
resp = await client.post('/')
assert resp.status == 400
@asyncio.coroutine
def test_validator_allow_empty(test_client):
async def test_validator_allow_empty(test_client):
"""Test the validator with empty data."""
client = yield from get_client(
client = await get_client(
test_client, RequestDataValidator(vol.Schema({
# Although we allow empty, our schema should still be able
# to validate an empty dict.
vol.Optional('test'): str
}), allow_empty=True))
resp = yield from client.post('/', json={
resp = await client.post('/', json={
'test': 'bla'
})
assert resp.status == 200
resp = yield from client.post('/', json={
resp = await client.post('/', json={
'test': 100
})
assert resp.status == 400
resp = yield from client.post('/')
resp = await client.post('/')
assert resp.status == 200
+16 -25
View File
@@ -1,6 +1,4 @@
"""The tests for the Home Assistant HTTP component."""
import asyncio
from homeassistant.setup import async_setup_component
import homeassistant.components.http as http
@@ -12,16 +10,14 @@ class TestView(http.HomeAssistantView):
name = 'test'
url = '/hello'
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Return a get request."""
return 'hello'
@asyncio.coroutine
def test_registering_view_while_running(hass, test_client, unused_port):
async def test_registering_view_while_running(hass, test_client, unused_port):
"""Test that we can register a view while the server is running."""
yield from async_setup_component(
await async_setup_component(
hass, http.DOMAIN, {
http.DOMAIN: {
http.CONF_SERVER_PORT: unused_port(),
@@ -29,15 +25,14 @@ def test_registering_view_while_running(hass, test_client, unused_port):
}
)
yield from hass.async_start()
await hass.async_start()
# This raises a RuntimeError if app is frozen
hass.http.register_view(TestView)
@asyncio.coroutine
def test_api_base_url_with_domain(hass):
async def test_api_base_url_with_domain(hass):
"""Test setting API URL."""
result = yield from async_setup_component(hass, 'http', {
result = await async_setup_component(hass, 'http', {
'http': {
'base_url': 'example.com'
}
@@ -46,10 +41,9 @@ def test_api_base_url_with_domain(hass):
assert hass.config.api.base_url == 'http://example.com'
@asyncio.coroutine
def test_api_base_url_with_ip(hass):
async def test_api_base_url_with_ip(hass):
"""Test setting api url."""
result = yield from async_setup_component(hass, 'http', {
result = await async_setup_component(hass, 'http', {
'http': {
'server_host': '1.1.1.1'
}
@@ -58,10 +52,9 @@ def test_api_base_url_with_ip(hass):
assert hass.config.api.base_url == 'http://1.1.1.1:8123'
@asyncio.coroutine
def test_api_base_url_with_ip_port(hass):
async def test_api_base_url_with_ip_port(hass):
"""Test setting api url."""
result = yield from async_setup_component(hass, 'http', {
result = await async_setup_component(hass, 'http', {
'http': {
'base_url': '1.1.1.1:8124'
}
@@ -70,10 +63,9 @@ def test_api_base_url_with_ip_port(hass):
assert hass.config.api.base_url == 'http://1.1.1.1:8124'
@asyncio.coroutine
def test_api_no_base_url(hass):
async def test_api_no_base_url(hass):
"""Test setting api url."""
result = yield from async_setup_component(hass, 'http', {
result = await async_setup_component(hass, 'http', {
'http': {
}
})
@@ -81,10 +73,9 @@ def test_api_no_base_url(hass):
assert hass.config.api.base_url == 'http://127.0.0.1:8123'
@asyncio.coroutine
def test_not_log_password(hass, unused_port, test_client, caplog):
async def test_not_log_password(hass, unused_port, test_client, caplog):
"""Test access with password doesn't get logged."""
result = yield from async_setup_component(hass, 'api', {
result = await async_setup_component(hass, 'api', {
'http': {
http.CONF_SERVER_PORT: unused_port(),
http.CONF_API_PASSWORD: 'some-pass'
@@ -92,9 +83,9 @@ def test_not_log_password(hass, unused_port, test_client, caplog):
})
assert result
client = yield from test_client(hass.http.app)
client = await test_client(hass.http.app)
resp = yield from client.get('/api/', params={
resp = await client.get('/api/', params={
'api_password': 'some-pass'
})
+9 -14
View File
@@ -1,6 +1,4 @@
"""Test real IP middleware."""
import asyncio
from aiohttp import web
from aiohttp.hdrs import X_FORWARDED_FOR
@@ -8,41 +6,38 @@ from homeassistant.components.http.real_ip import setup_real_ip
from homeassistant.components.http.const import KEY_REAL_IP
@asyncio.coroutine
def mock_handler(request):
async def mock_handler(request):
"""Handler that returns the real IP as text."""
return web.Response(text=str(request[KEY_REAL_IP]))
@asyncio.coroutine
def test_ignore_x_forwarded_for(test_client):
async def test_ignore_x_forwarded_for(test_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, False)
mock_api_client = yield from test_client(app)
mock_api_client = await test_client(app)
resp = yield from mock_api_client.get('/', headers={
resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255'
})
assert resp.status == 200
text = yield from resp.text()
text = await resp.text()
assert text != '255.255.255.255'
@asyncio.coroutine
def test_use_x_forwarded_for(test_client):
async def test_use_x_forwarded_for(test_client):
"""Test that we get the IP from the transport."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_real_ip(app, True)
mock_api_client = yield from test_client(app)
mock_api_client = await test_client(app)
resp = yield from mock_api_client.get('/', headers={
resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255'
})
assert resp.status == 200
text = yield from resp.text()
text = await resp.text()
assert text == '255.255.255.255'