2018-05-01 17:35:23 +00:00
|
|
|
"""Fixtures for component testing."""
|
2018-09-11 16:08:03 +00:00
|
|
|
from unittest.mock import patch
|
|
|
|
|
2018-05-01 17:35:23 +00:00
|
|
|
import pytest
|
|
|
|
|
|
|
|
from homeassistant.setup import async_setup_component
|
2018-07-13 13:31:20 +00:00
|
|
|
from homeassistant.components import websocket_api
|
2018-05-01 17:35:23 +00:00
|
|
|
|
2018-07-09 16:24:46 +00:00
|
|
|
from tests.common import MockUser, CLIENT_ID
|
2018-05-10 08:38:11 +00:00
|
|
|
|
2018-05-01 17:35:23 +00:00
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def hass_ws_client(aiohttp_client):
|
|
|
|
"""Websocket client fixture connected to websocket server."""
|
2018-07-13 13:31:20 +00:00
|
|
|
async def create_client(hass, access_token=None):
|
2018-05-01 17:35:23 +00:00
|
|
|
"""Create a websocket client."""
|
|
|
|
wapi = hass.components.websocket_api
|
|
|
|
assert await async_setup_component(hass, 'websocket_api')
|
|
|
|
|
|
|
|
client = await aiohttp_client(hass.http.app)
|
2018-07-13 13:31:20 +00:00
|
|
|
|
2018-09-11 16:08:03 +00:00
|
|
|
patching = None
|
|
|
|
|
|
|
|
if access_token is not None:
|
|
|
|
patching = patch('homeassistant.auth.AuthManager.active',
|
|
|
|
return_value=True)
|
|
|
|
patching.start()
|
|
|
|
|
|
|
|
try:
|
|
|
|
websocket = await client.ws_connect(wapi.URL)
|
|
|
|
auth_resp = await websocket.receive_json()
|
|
|
|
|
|
|
|
if auth_resp['type'] == wapi.TYPE_AUTH_OK:
|
|
|
|
assert access_token is None, \
|
|
|
|
'Access token given but no auth required'
|
|
|
|
return websocket
|
|
|
|
|
|
|
|
assert access_token is not None, \
|
|
|
|
'Access token required for fixture'
|
2018-07-13 13:31:20 +00:00
|
|
|
|
2018-09-11 16:08:03 +00:00
|
|
|
await websocket.send_json({
|
|
|
|
'type': websocket_api.TYPE_AUTH,
|
|
|
|
'access_token': access_token
|
|
|
|
})
|
2018-07-13 13:31:20 +00:00
|
|
|
|
2018-09-11 16:08:03 +00:00
|
|
|
auth_ok = await websocket.receive_json()
|
|
|
|
assert auth_ok['type'] == wapi.TYPE_AUTH_OK
|
2018-07-13 13:31:20 +00:00
|
|
|
|
2018-09-11 16:08:03 +00:00
|
|
|
finally:
|
|
|
|
if patching is not None:
|
|
|
|
patching.stop()
|
2018-05-01 17:35:23 +00:00
|
|
|
|
2018-09-11 10:05:15 +00:00
|
|
|
# wrap in client
|
|
|
|
websocket.client = client
|
2018-05-01 17:35:23 +00:00
|
|
|
return websocket
|
|
|
|
|
|
|
|
return create_client
|
2018-05-10 08:38:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def hass_access_token(hass):
|
|
|
|
"""Return an access token to access Home Assistant."""
|
|
|
|
user = MockUser().add_to_hass(hass)
|
|
|
|
refresh_token = hass.loop.run_until_complete(
|
2018-07-09 16:24:46 +00:00
|
|
|
hass.auth.async_create_refresh_token(user, CLIENT_ID))
|
2018-05-10 08:38:11 +00:00
|
|
|
yield hass.auth.async_create_access_token(refresh_token)
|