Fix aiohttp deprecation warnings (#13240)

* Fix aiohttp deprecation warnings

* Fix Ring deprecation warning

* Lint
This commit is contained in:
Paulus Schoutsen 2018-03-15 13:49:49 -07:00 committed by Pascal Vizeli
parent a86bf81768
commit 89a19c89a7
45 changed files with 221 additions and 225 deletions

View file

@ -37,8 +37,8 @@ CONFIG_SCHEMA = vol.Schema({
def setup(hass, config): def setup(hass, config):
"""Set up the Ring component.""" """Set up the Ring component."""
conf = config[DOMAIN] conf = config[DOMAIN]
username = conf.get(CONF_USERNAME) username = conf[CONF_USERNAME]
password = conf.get(CONF_PASSWORD) password = conf[CONF_PASSWORD]
try: try:
from ring_doorbell import Ring from ring_doorbell import Ring

View file

@ -149,34 +149,27 @@ def _async_get_connector(hass, verify_ssl=True):
This method must be run in the event loop. This method must be run in the event loop.
""" """
is_new = False key = DATA_CONNECTOR if verify_ssl else DATA_CONNECTOR_NOTVERIFY
if key in hass.data:
return hass.data[key]
if verify_ssl: if verify_ssl:
if DATA_CONNECTOR not in hass.data: ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ssl_context.load_verify_locations(cafile=certifi.where(),
ssl_context.load_verify_locations(cafile=certifi.where(), capath=None)
capath=None)
connector = aiohttp.TCPConnector(loop=hass.loop,
ssl_context=ssl_context)
hass.data[DATA_CONNECTOR] = connector
is_new = True
else:
connector = hass.data[DATA_CONNECTOR]
else: else:
if DATA_CONNECTOR_NOTVERIFY not in hass.data: ssl_context = False
connector = aiohttp.TCPConnector(loop=hass.loop, verify_ssl=False)
hass.data[DATA_CONNECTOR_NOTVERIFY] = connector
is_new = True
else:
connector = hass.data[DATA_CONNECTOR_NOTVERIFY]
if is_new: connector = aiohttp.TCPConnector(loop=hass.loop, ssl=ssl_context)
@callback hass.data[key] = connector
def _async_close_connector(event):
"""Close connector pool."""
connector.close()
hass.bus.async_listen_once( @callback
EVENT_HOMEASSISTANT_CLOSE, _async_close_connector) def _async_close_connector(event):
"""Close connector pool."""
connector.close()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_CLOSE, _async_close_connector)
return connector return connector

View file

@ -21,7 +21,7 @@ NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3"
@pytest.fixture @pytest.fixture
def alexa_client(loop, hass, test_client): def alexa_client(loop, hass, aiohttp_client):
"""Initialize a Home Assistant server for testing this module.""" """Initialize a Home Assistant server for testing this module."""
@callback @callback
def mock_service(call): def mock_service(call):
@ -49,7 +49,7 @@ def alexa_client(loop, hass, test_client):
}, },
} }
})) }))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
def _flash_briefing_req(client, briefing_id): def _flash_briefing_req(client, briefing_id):

View file

@ -23,7 +23,7 @@ NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3"
@pytest.fixture @pytest.fixture
def alexa_client(loop, hass, test_client): def alexa_client(loop, hass, aiohttp_client):
"""Initialize a Home Assistant server for testing this module.""" """Initialize a Home Assistant server for testing this module."""
@callback @callback
def mock_service(call): def mock_service(call):
@ -95,7 +95,7 @@ def alexa_client(loop, hass, test_client):
}, },
} }
})) }))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
def _intent_req(client, data=None): def _intent_req(client, data=None):

View file

@ -1199,10 +1199,10 @@ def test_unsupported_domain(hass):
@asyncio.coroutine @asyncio.coroutine
def do_http_discovery(config, hass, test_client): def do_http_discovery(config, hass, aiohttp_client):
"""Submit a request to the Smart Home HTTP API.""" """Submit a request to the Smart Home HTTP API."""
yield from async_setup_component(hass, alexa.DOMAIN, config) yield from async_setup_component(hass, alexa.DOMAIN, config)
http_client = yield from test_client(hass.http.app) http_client = yield from aiohttp_client(hass.http.app)
request = get_new_request('Alexa.Discovery', 'Discover') request = get_new_request('Alexa.Discovery', 'Discover')
response = yield from http_client.post( response = yield from http_client.post(
@ -1213,7 +1213,7 @@ def do_http_discovery(config, hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_http_api(hass, test_client): def test_http_api(hass, aiohttp_client):
"""With `smart_home:` HTTP API is exposed.""" """With `smart_home:` HTTP API is exposed."""
config = { config = {
'alexa': { 'alexa': {
@ -1221,7 +1221,7 @@ def test_http_api(hass, test_client):
} }
} }
response = yield from do_http_discovery(config, hass, test_client) response = yield from do_http_discovery(config, hass, aiohttp_client)
response_data = yield from response.json() response_data = yield from response.json()
# Here we're testing just the HTTP view glue -- details of discovery are # Here we're testing just the HTTP view glue -- details of discovery are
@ -1230,12 +1230,12 @@ def test_http_api(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_http_api_disabled(hass, test_client): def test_http_api_disabled(hass, aiohttp_client):
"""Without `smart_home:`, the HTTP API is disabled.""" """Without `smart_home:`, the HTTP API is disabled."""
config = { config = {
'alexa': {} 'alexa': {}
} }
response = yield from do_http_discovery(config, hass, test_client) response = yield from do_http_discovery(config, hass, aiohttp_client)
assert response.status == 404 assert response.status == 404

View file

@ -6,7 +6,7 @@ from homeassistant.setup import async_setup_component
@asyncio.coroutine @asyncio.coroutine
def test_fetching_url(aioclient_mock, hass, test_client): def test_fetching_url(aioclient_mock, hass, aiohttp_client):
"""Test that it fetches the given url.""" """Test that it fetches the given url."""
aioclient_mock.get('http://example.com', text='hello world') aioclient_mock.get('http://example.com', text='hello world')
@ -19,7 +19,7 @@ def test_fetching_url(aioclient_mock, hass, test_client):
'password': 'pass' 'password': 'pass'
}}) }})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/camera_proxy/camera.config_test') resp = yield from client.get('/api/camera_proxy/camera.config_test')
@ -33,7 +33,7 @@ def test_fetching_url(aioclient_mock, hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_limit_refetch(aioclient_mock, hass, test_client): def test_limit_refetch(aioclient_mock, hass, aiohttp_client):
"""Test that it fetches the given url.""" """Test that it fetches the given url."""
aioclient_mock.get('http://example.com/5a', text='hello world') aioclient_mock.get('http://example.com/5a', text='hello world')
aioclient_mock.get('http://example.com/10a', text='hello world') aioclient_mock.get('http://example.com/10a', text='hello world')
@ -49,7 +49,7 @@ def test_limit_refetch(aioclient_mock, hass, test_client):
'limit_refetch_to_url_change': True, 'limit_refetch_to_url_change': True,
}}) }})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/camera_proxy/camera.config_test') resp = yield from client.get('/api/camera_proxy/camera.config_test')
@ -94,7 +94,7 @@ def test_limit_refetch(aioclient_mock, hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_camera_content_type(aioclient_mock, hass, test_client): def test_camera_content_type(aioclient_mock, hass, aiohttp_client):
"""Test generic camera with custom content_type.""" """Test generic camera with custom content_type."""
svg_image = '<some image>' svg_image = '<some image>'
urlsvg = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg' urlsvg = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg'
@ -113,7 +113,7 @@ def test_camera_content_type(aioclient_mock, hass, test_client):
yield from async_setup_component(hass, 'camera', { yield from async_setup_component(hass, 'camera', {
'camera': [cam_config_svg, cam_config_normal]}) 'camera': [cam_config_svg, cam_config_normal]})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp_1 = yield from client.get('/api/camera_proxy/camera.config_test_svg') resp_1 = yield from client.get('/api/camera_proxy/camera.config_test_svg')
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1

View file

@ -12,7 +12,7 @@ from tests.common import mock_registry
@asyncio.coroutine @asyncio.coroutine
def test_loading_file(hass, test_client): def test_loading_file(hass, aiohttp_client):
"""Test that it loads image from disk.""" """Test that it loads image from disk."""
mock_registry(hass) mock_registry(hass)
@ -25,7 +25,7 @@ def test_loading_file(hass, test_client):
'file_path': 'mock.file', 'file_path': 'mock.file',
}}) }})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
m_open = MockOpen(read_data=b'hello') m_open = MockOpen(read_data=b'hello')
with mock.patch( with mock.patch(
@ -57,7 +57,7 @@ def test_file_not_readable(hass, caplog):
@asyncio.coroutine @asyncio.coroutine
def test_camera_content_type(hass, test_client): def test_camera_content_type(hass, aiohttp_client):
"""Test local_file camera content_type.""" """Test local_file camera content_type."""
cam_config_jpg = { cam_config_jpg = {
'name': 'test_jpg', 'name': 'test_jpg',
@ -84,7 +84,7 @@ def test_camera_content_type(hass, test_client):
'camera': [cam_config_jpg, cam_config_png, 'camera': [cam_config_jpg, cam_config_png,
cam_config_svg, cam_config_noext]}) cam_config_svg, cam_config_noext]})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
image = 'hello' image = 'hello'
m_open = MockOpen(read_data=image.encode()) m_open = MockOpen(read_data=image.encode())

View file

@ -8,7 +8,7 @@ from tests.common import (
@asyncio.coroutine @asyncio.coroutine
def test_run_camera_setup(hass, test_client): def test_run_camera_setup(hass, aiohttp_client):
"""Test that it fetches the given payload.""" """Test that it fetches the given payload."""
topic = 'test/camera' topic = 'test/camera'
yield from async_mock_mqtt_component(hass) yield from async_mock_mqtt_component(hass)
@ -24,7 +24,7 @@ def test_run_camera_setup(hass, test_client):
async_fire_mqtt_message(hass, topic, 'beer') async_fire_mqtt_message(hass, topic, 'beer')
yield from hass.async_block_till_done() yield from hass.async_block_till_done()
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get(url) resp = yield from client.get(url)
assert resp.status == 200 assert resp.status == 200
body = yield from resp.text() body = yield from resp.text()

View file

@ -12,7 +12,7 @@ from tests.common import mock_coro
@pytest.fixture @pytest.fixture
def cloud_client(hass, test_client): def cloud_client(hass, aiohttp_client):
"""Fixture that can fetch from the cloud client.""" """Fixture that can fetch from the cloud client."""
with patch('homeassistant.components.cloud.Cloud.async_start', with patch('homeassistant.components.cloud.Cloud.async_start',
return_value=mock_coro()): return_value=mock_coro()):
@ -28,7 +28,7 @@ def cloud_client(hass, test_client):
hass.data['cloud']._decode_claims = \ hass.data['cloud']._decode_claims = \
lambda token: jwt.get_unverified_claims(token) lambda token: jwt.get_unverified_claims(token)
with patch('homeassistant.components.cloud.Cloud.write_user_info'): with patch('homeassistant.components.cloud.Cloud.write_user_info'):
yield hass.loop.run_until_complete(test_client(hass.http.app)) yield hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture

View file

@ -17,11 +17,11 @@ from tests.common import MockConfigEntry, MockModule, mock_coro_func
@pytest.fixture @pytest.fixture
def client(hass, test_client): def client(hass, aiohttp_client):
"""Fixture that can interact with the config manager API.""" """Fixture that can interact with the config manager API."""
hass.loop.run_until_complete(async_setup_component(hass, 'http', {})) hass.loop.run_until_complete(async_setup_component(hass, 'http', {}))
hass.loop.run_until_complete(config_entries.async_setup(hass)) hass.loop.run_until_complete(config_entries.async_setup(hass))
yield hass.loop.run_until_complete(test_client(hass.http.app)) yield hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -8,14 +8,14 @@ from tests.common import mock_coro
@asyncio.coroutine @asyncio.coroutine
def test_validate_config_ok(hass, test_client): def test_validate_config_ok(hass, aiohttp_client):
"""Test checking config.""" """Test checking config."""
with patch.object(config, 'SECTIONS', ['core']): with patch.object(config, 'SECTIONS', ['core']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
yield from asyncio.sleep(0.1, loop=hass.loop) yield from asyncio.sleep(0.1, loop=hass.loop)
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
with patch( with patch(
'homeassistant.components.config.core.async_check_ha_config_file', 'homeassistant.components.config.core.async_check_ha_config_file',

View file

@ -9,12 +9,12 @@ from homeassistant.config import DATA_CUSTOMIZE
@asyncio.coroutine @asyncio.coroutine
def test_get_entity(hass, test_client): def test_get_entity(hass, aiohttp_client):
"""Test getting entity.""" """Test getting entity."""
with patch.object(config, 'SECTIONS', ['customize']): with patch.object(config, 'SECTIONS', ['customize']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
def mock_read(path): def mock_read(path):
"""Mock reading data.""" """Mock reading data."""
@ -38,12 +38,12 @@ def test_get_entity(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_entity(hass, test_client): def test_update_entity(hass, aiohttp_client):
"""Test updating entity.""" """Test updating entity."""
with patch.object(config, 'SECTIONS', ['customize']): with patch.object(config, 'SECTIONS', ['customize']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
orig_data = { orig_data = {
'hello.beer': { 'hello.beer': {
@ -89,12 +89,12 @@ def test_update_entity(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_entity_invalid_key(hass, test_client): def test_update_entity_invalid_key(hass, aiohttp_client):
"""Test updating entity.""" """Test updating entity."""
with patch.object(config, 'SECTIONS', ['customize']): with patch.object(config, 'SECTIONS', ['customize']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/customize/config/not_entity', data=json.dumps({ '/api/config/customize/config/not_entity', data=json.dumps({
@ -105,12 +105,12 @@ def test_update_entity_invalid_key(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_entity_invalid_json(hass, test_client): def test_update_entity_invalid_json(hass, aiohttp_client):
"""Test updating entity.""" """Test updating entity."""
with patch.object(config, 'SECTIONS', ['customize']): with patch.object(config, 'SECTIONS', ['customize']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/customize/config/hello.beer', data='not json') '/api/config/customize/config/hello.beer', data='not json')

View file

@ -8,11 +8,11 @@ from tests.common import mock_registry, MockEntity, MockEntityPlatform
@pytest.fixture @pytest.fixture
def client(hass, test_client): def client(hass, aiohttp_client):
"""Fixture that can interact with the config manager API.""" """Fixture that can interact with the config manager API."""
hass.loop.run_until_complete(async_setup_component(hass, 'http', {})) hass.loop.run_until_complete(async_setup_component(hass, 'http', {}))
hass.loop.run_until_complete(entity_registry.async_setup(hass)) hass.loop.run_until_complete(entity_registry.async_setup(hass))
yield hass.loop.run_until_complete(test_client(hass.http.app)) yield hass.loop.run_until_complete(aiohttp_client(hass.http.app))
async def test_get_entity(hass, client): async def test_get_entity(hass, client):

View file

@ -11,12 +11,12 @@ VIEW_NAME = 'api:config:group:config'
@asyncio.coroutine @asyncio.coroutine
def test_get_device_config(hass, test_client): def test_get_device_config(hass, aiohttp_client):
"""Test getting device config.""" """Test getting device config."""
with patch.object(config, 'SECTIONS', ['group']): with patch.object(config, 'SECTIONS', ['group']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
def mock_read(path): def mock_read(path):
"""Mock reading data.""" """Mock reading data."""
@ -40,12 +40,12 @@ def test_get_device_config(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_device_config(hass, test_client): def test_update_device_config(hass, aiohttp_client):
"""Test updating device config.""" """Test updating device config."""
with patch.object(config, 'SECTIONS', ['group']): with patch.object(config, 'SECTIONS', ['group']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
orig_data = { orig_data = {
'hello.beer': { 'hello.beer': {
@ -89,12 +89,12 @@ def test_update_device_config(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_device_config_invalid_key(hass, test_client): def test_update_device_config_invalid_key(hass, aiohttp_client):
"""Test updating device config.""" """Test updating device config."""
with patch.object(config, 'SECTIONS', ['group']): with patch.object(config, 'SECTIONS', ['group']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/group/config/not a slug', data=json.dumps({ '/api/config/group/config/not a slug', data=json.dumps({
@ -105,12 +105,12 @@ def test_update_device_config_invalid_key(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_device_config_invalid_data(hass, test_client): def test_update_device_config_invalid_data(hass, aiohttp_client):
"""Test updating device config.""" """Test updating device config."""
with patch.object(config, 'SECTIONS', ['group']): with patch.object(config, 'SECTIONS', ['group']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/group/config/hello_beer', data=json.dumps({ '/api/config/group/config/hello_beer', data=json.dumps({
@ -121,12 +121,12 @@ def test_update_device_config_invalid_data(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_update_device_config_invalid_json(hass, test_client): def test_update_device_config_invalid_json(hass, aiohttp_client):
"""Test updating device config.""" """Test updating device config."""
with patch.object(config, 'SECTIONS', ['group']): with patch.object(config, 'SECTIONS', ['group']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/group/config/hello_beer', data='not json') '/api/config/group/config/hello_beer', data='not json')

View file

@ -34,13 +34,13 @@ def test_setup_check_env_works(hass, loop):
@asyncio.coroutine @asyncio.coroutine
def test_get_suites(hass, test_client): def test_get_suites(hass, aiohttp_client):
"""Test getting suites.""" """Test getting suites."""
with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \ with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
patch.object(config, 'SECTIONS', ['hassbian']): patch.object(config, 'SECTIONS', ['hassbian']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/config/hassbian/suites') resp = yield from client.get('/api/config/hassbian/suites')
assert resp.status == 200 assert resp.status == 200
result = yield from resp.json() result = yield from resp.json()
@ -53,13 +53,13 @@ def test_get_suites(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_install_suite(hass, test_client): def test_install_suite(hass, aiohttp_client):
"""Test getting suites.""" """Test getting suites."""
with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \ with patch.dict(os.environ, {'FORCE_HASSBIAN': '1'}), \
patch.object(config, 'SECTIONS', ['hassbian']): patch.object(config, 'SECTIONS', ['hassbian']):
yield from async_setup_component(hass, 'config', {}) yield from async_setup_component(hass, 'config', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/config/hassbian/suites/openzwave/install') '/api/config/hassbian/suites/openzwave/install')
assert resp.status == 200 assert resp.status == 200

View file

@ -17,7 +17,7 @@ def test_config_setup(hass, loop):
@asyncio.coroutine @asyncio.coroutine
def test_load_on_demand_already_loaded(hass, test_client): def test_load_on_demand_already_loaded(hass, aiohttp_client):
"""Test getting suites.""" """Test getting suites."""
mock_component(hass, 'zwave') mock_component(hass, 'zwave')
@ -34,7 +34,7 @@ def test_load_on_demand_already_loaded(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_load_on_demand_on_load(hass, test_client): def test_load_on_demand_on_load(hass, aiohttp_client):
"""Test getting suites.""" """Test getting suites."""
with patch.object(config, 'SECTIONS', []), \ with patch.object(config, 'SECTIONS', []), \
patch.object(config, 'ON_DEMAND', ['zwave']): patch.object(config, 'ON_DEMAND', ['zwave']):

View file

@ -16,12 +16,12 @@ VIEW_NAME = 'api:config:zwave:device_config'
@pytest.fixture @pytest.fixture
def client(loop, hass, test_client): def client(loop, hass, aiohttp_client):
"""Client to communicate with Z-Wave config views.""" """Client to communicate with Z-Wave config views."""
with patch.object(config, 'SECTIONS', ['zwave']): with patch.object(config, 'SECTIONS', ['zwave']):
loop.run_until_complete(async_setup_component(hass, 'config', {})) loop.run_until_complete(async_setup_component(hass, 'config', {}))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -107,7 +107,7 @@ BEACON_EXIT_CAR = {
@pytest.fixture @pytest.fixture
def geofency_client(loop, hass, test_client): def geofency_client(loop, hass, aiohttp_client):
"""Geofency mock client.""" """Geofency mock client."""
assert loop.run_until_complete(async_setup_component( assert loop.run_until_complete(async_setup_component(
hass, device_tracker.DOMAIN, { hass, device_tracker.DOMAIN, {
@ -117,7 +117,7 @@ def geofency_client(loop, hass, test_client):
}})) }}))
with patch('homeassistant.components.device_tracker.update_config'): with patch('homeassistant.components.device_tracker.update_config'):
yield loop.run_until_complete(test_client(hass.http.app)) yield loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)

View file

@ -19,7 +19,7 @@ def _url(data=None):
@pytest.fixture @pytest.fixture
def locative_client(loop, hass, test_client): def locative_client(loop, hass, aiohttp_client):
"""Locative mock client.""" """Locative mock client."""
assert loop.run_until_complete(async_setup_component( assert loop.run_until_complete(async_setup_component(
hass, device_tracker.DOMAIN, { hass, device_tracker.DOMAIN, {
@ -29,7 +29,7 @@ def locative_client(loop, hass, test_client):
})) }))
with patch('homeassistant.components.device_tracker.update_config'): with patch('homeassistant.components.device_tracker.update_config'):
yield loop.run_until_complete(test_client(hass.http.app)) yield loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -13,7 +13,7 @@ from homeassistant.components.device_tracker.meraki import URL
@pytest.fixture @pytest.fixture
def meraki_client(loop, hass, test_client): def meraki_client(loop, hass, aiohttp_client):
"""Meraki mock client.""" """Meraki mock client."""
assert loop.run_until_complete(async_setup_component( assert loop.run_until_complete(async_setup_component(
hass, device_tracker.DOMAIN, { hass, device_tracker.DOMAIN, {
@ -25,7 +25,7 @@ def meraki_client(loop, hass, test_client):
} }
})) }))
yield loop.run_until_complete(test_client(hass.http.app)) yield loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -10,7 +10,7 @@ from tests.common import mock_coro, mock_component
@pytest.fixture @pytest.fixture
def mock_client(hass, test_client): def mock_client(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
mock_component(hass, 'group') mock_component(hass, 'group')
mock_component(hass, 'zone') mock_component(hass, 'zone')
@ -22,7 +22,7 @@ def mock_client(hass, test_client):
'platform': 'owntracks_http' 'platform': 'owntracks_http'
} }
})) }))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture

View file

@ -118,7 +118,7 @@ def hass_hue(loop, hass):
@pytest.fixture @pytest.fixture
def hue_client(loop, hass_hue, test_client): def hue_client(loop, hass_hue, aiohttp_client):
"""Create web client for emulated hue api.""" """Create web client for emulated hue api."""
web_app = hass_hue.http.app web_app = hass_hue.http.app
config = Config(None, { config = Config(None, {
@ -135,7 +135,7 @@ def hue_client(loop, hass_hue, test_client):
HueOneLightStateView(config).register(web_app.router) HueOneLightStateView(config).register(web_app.router)
HueOneLightChangeView(config).register(web_app.router) HueOneLightChangeView(config).register(web_app.router)
return loop.run_until_complete(test_client(web_app)) return loop.run_until_complete(aiohttp_client(web_app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -27,7 +27,7 @@ AUTH_HEADER = {AUTHORIZATION: 'Bearer {}'.format(ACCESS_TOKEN)}
@pytest.fixture @pytest.fixture
def assistant_client(loop, hass, test_client): def assistant_client(loop, hass, aiohttp_client):
"""Create web client for the Google Assistant API.""" """Create web client for the Google Assistant API."""
loop.run_until_complete( loop.run_until_complete(
setup.async_setup_component(hass, 'google_assistant', { setup.async_setup_component(hass, 'google_assistant', {
@ -44,7 +44,7 @@ def assistant_client(loop, hass, test_client):
} }
})) }))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture

View file

@ -26,7 +26,7 @@ def hassio_env():
@pytest.fixture @pytest.fixture
def hassio_client(hassio_env, hass, test_client): def hassio_client(hassio_env, hass, aiohttp_client):
"""Create mock hassio http client.""" """Create mock hassio http client."""
with patch('homeassistant.components.hassio.HassIO.update_hass_api', with patch('homeassistant.components.hassio.HassIO.update_hass_api',
Mock(return_value=mock_coro({"result": "ok"}))), \ Mock(return_value=mock_coro({"result": "ok"}))), \
@ -38,7 +38,7 @@ def hassio_client(hassio_env, hass, test_client):
'api_password': API_PASSWORD 'api_password': API_PASSWORD
} }
})) }))
yield hass.loop.run_until_complete(test_client(hass.http.app)) yield hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture

View file

@ -55,19 +55,19 @@ async def test_auth_middleware_loaded_by_default(hass):
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_access_without_password(app, test_client): async def test_access_without_password(app, aiohttp_client):
"""Test access without password.""" """Test access without password."""
setup_auth(app, [], None) setup_auth(app, [], None)
client = await test_client(app) client = await aiohttp_client(app)
resp = await client.get('/') resp = await client.get('/')
assert resp.status == 200 assert resp.status == 200
async def test_access_with_password_in_header(app, test_client): async def test_access_with_password_in_header(app, aiohttp_client):
"""Test access with password in URL.""" """Test access with password in URL."""
setup_auth(app, [], API_PASSWORD) setup_auth(app, [], API_PASSWORD)
client = await test_client(app) client = await aiohttp_client(app)
req = await client.get( req = await client.get(
'/', headers={HTTP_HEADER_HA_AUTH: API_PASSWORD}) '/', headers={HTTP_HEADER_HA_AUTH: API_PASSWORD})
@ -78,10 +78,10 @@ async def test_access_with_password_in_header(app, test_client):
assert req.status == 401 assert req.status == 401
async def test_access_with_password_in_query(app, test_client): async def test_access_with_password_in_query(app, aiohttp_client):
"""Test access without password.""" """Test access without password."""
setup_auth(app, [], API_PASSWORD) setup_auth(app, [], API_PASSWORD)
client = await test_client(app) client = await aiohttp_client(app)
resp = await client.get('/', params={ resp = await client.get('/', params={
'api_password': API_PASSWORD 'api_password': API_PASSWORD
@ -97,10 +97,10 @@ async def test_access_with_password_in_query(app, test_client):
assert resp.status == 401 assert resp.status == 401
async def test_basic_auth_works(app, test_client): async def test_basic_auth_works(app, aiohttp_client):
"""Test access with basic authentication.""" """Test access with basic authentication."""
setup_auth(app, [], API_PASSWORD) setup_auth(app, [], API_PASSWORD)
client = await test_client(app) client = await aiohttp_client(app)
req = await client.get( req = await client.get(
'/', '/',
@ -125,7 +125,7 @@ async def test_basic_auth_works(app, test_client):
assert req.status == 401 assert req.status == 401
async def test_access_with_trusted_ip(test_client): async def test_access_with_trusted_ip(aiohttp_client):
"""Test access with an untrusted ip address.""" """Test access with an untrusted ip address."""
app = web.Application() app = web.Application()
app.router.add_get('/', mock_handler) app.router.add_get('/', mock_handler)
@ -133,7 +133,7 @@ async def test_access_with_trusted_ip(test_client):
setup_auth(app, TRUSTED_NETWORKS, 'some-pass') setup_auth(app, TRUSTED_NETWORKS, 'some-pass')
set_mock_ip = mock_real_ip(app) set_mock_ip = mock_real_ip(app)
client = await test_client(app) client = await aiohttp_client(app)
for remote_addr in UNTRUSTED_ADDRESSES: for remote_addr in UNTRUSTED_ADDRESSES:
set_mock_ip(remote_addr) set_mock_ip(remote_addr)

View file

@ -15,7 +15,7 @@ from . import mock_real_ip
BANNED_IPS = ['200.201.202.203', '100.64.0.2'] BANNED_IPS = ['200.201.202.203', '100.64.0.2']
async def test_access_from_banned_ip(hass, test_client): async def test_access_from_banned_ip(hass, aiohttp_client):
"""Test accessing to server from banned IP. Both trusted and not.""" """Test accessing to server from banned IP. Both trusted and not."""
app = web.Application() app = web.Application()
setup_bans(hass, app, 5) setup_bans(hass, app, 5)
@ -24,7 +24,7 @@ async def test_access_from_banned_ip(hass, test_client):
with patch('homeassistant.components.http.ban.load_ip_bans_config', with patch('homeassistant.components.http.ban.load_ip_bans_config',
return_value=[IpBan(banned_ip) for banned_ip return_value=[IpBan(banned_ip) for banned_ip
in BANNED_IPS]): in BANNED_IPS]):
client = await test_client(app) client = await aiohttp_client(app)
for remote_addr in BANNED_IPS: for remote_addr in BANNED_IPS:
set_real_ip(remote_addr) set_real_ip(remote_addr)
@ -54,7 +54,7 @@ async def test_ban_middleware_loaded_by_default(hass):
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_ip_bans_file_creation(hass, test_client): async def test_ip_bans_file_creation(hass, aiohttp_client):
"""Testing if banned IP file created.""" """Testing if banned IP file created."""
app = web.Application() app = web.Application()
app['hass'] = hass app['hass'] = hass
@ -70,7 +70,7 @@ async def test_ip_bans_file_creation(hass, test_client):
with patch('homeassistant.components.http.ban.load_ip_bans_config', with patch('homeassistant.components.http.ban.load_ip_bans_config',
return_value=[IpBan(banned_ip) for banned_ip return_value=[IpBan(banned_ip) for banned_ip
in BANNED_IPS]): in BANNED_IPS]):
client = await test_client(app) client = await aiohttp_client(app)
m = mock_open() m = mock_open()

View file

@ -47,12 +47,12 @@ async def mock_handler(request):
@pytest.fixture @pytest.fixture
def client(loop, test_client): def client(loop, aiohttp_client):
"""Fixture to setup a web.Application.""" """Fixture to setup a web.Application."""
app = web.Application() app = web.Application()
app.router.add_get('/', mock_handler) app.router.add_get('/', mock_handler)
setup_cors(app, [TRUSTED_ORIGIN]) setup_cors(app, [TRUSTED_ORIGIN])
return loop.run_until_complete(test_client(app)) return loop.run_until_complete(aiohttp_client(app))
async def test_cors_requests(client): async def test_cors_requests(client):

View file

@ -8,7 +8,7 @@ from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.data_validator import RequestDataValidator
async def get_client(test_client, validator): async def get_client(aiohttp_client, validator):
"""Generate a client that hits a view decorated with validator.""" """Generate a client that hits a view decorated with validator."""
app = web.Application() app = web.Application()
app['hass'] = Mock(is_running=True) app['hass'] = Mock(is_running=True)
@ -24,14 +24,14 @@ async def get_client(test_client, validator):
return b'' return b''
TestView().register(app.router) TestView().register(app.router)
client = await test_client(app) client = await aiohttp_client(app)
return client return client
async def test_validator(test_client): async def test_validator(aiohttp_client):
"""Test the validator.""" """Test the validator."""
client = await get_client( client = await get_client(
test_client, RequestDataValidator(vol.Schema({ aiohttp_client, RequestDataValidator(vol.Schema({
vol.Required('test'): str vol.Required('test'): str
}))) })))
@ -49,10 +49,10 @@ async def test_validator(test_client):
assert resp.status == 400 assert resp.status == 400
async def test_validator_allow_empty(test_client): async def test_validator_allow_empty(aiohttp_client):
"""Test the validator with empty data.""" """Test the validator with empty data."""
client = await get_client( client = await get_client(
test_client, RequestDataValidator(vol.Schema({ aiohttp_client, RequestDataValidator(vol.Schema({
# Although we allow empty, our schema should still be able # Although we allow empty, our schema should still be able
# to validate an empty dict. # to validate an empty dict.
vol.Optional('test'): str vol.Optional('test'): str

View file

@ -15,12 +15,13 @@ class TestView(http.HomeAssistantView):
return 'hello' return 'hello'
async def test_registering_view_while_running(hass, test_client, unused_port): async def test_registering_view_while_running(hass, aiohttp_client,
aiohttp_unused_port):
"""Test that we can register a view while the server is running.""" """Test that we can register a view while the server is running."""
await async_setup_component( await async_setup_component(
hass, http.DOMAIN, { hass, http.DOMAIN, {
http.DOMAIN: { http.DOMAIN: {
http.CONF_SERVER_PORT: unused_port(), http.CONF_SERVER_PORT: aiohttp_unused_port(),
} }
} }
) )
@ -73,17 +74,16 @@ async def test_api_no_base_url(hass):
assert hass.config.api.base_url == 'http://127.0.0.1:8123' assert hass.config.api.base_url == 'http://127.0.0.1:8123'
async def test_not_log_password(hass, unused_port, test_client, caplog): async def test_not_log_password(hass, aiohttp_client, caplog):
"""Test access with password doesn't get logged.""" """Test access with password doesn't get logged."""
result = await async_setup_component(hass, 'api', { result = await async_setup_component(hass, 'api', {
'http': { 'http': {
http.CONF_SERVER_PORT: unused_port(),
http.CONF_API_PASSWORD: 'some-pass' http.CONF_API_PASSWORD: 'some-pass'
} }
}) })
assert result assert result
client = await test_client(hass.http.app) client = await aiohttp_client(hass.http.app)
resp = await client.get('/api/', params={ resp = await client.get('/api/', params={
'api_password': 'some-pass' 'api_password': 'some-pass'

View file

@ -11,13 +11,13 @@ async def mock_handler(request):
return web.Response(text=str(request[KEY_REAL_IP])) return web.Response(text=str(request[KEY_REAL_IP]))
async def test_ignore_x_forwarded_for(test_client): async def test_ignore_x_forwarded_for(aiohttp_client):
"""Test that we get the IP from the transport.""" """Test that we get the IP from the transport."""
app = web.Application() app = web.Application()
app.router.add_get('/', mock_handler) app.router.add_get('/', mock_handler)
setup_real_ip(app, False) setup_real_ip(app, False)
mock_api_client = await test_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get('/', headers={ resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255' X_FORWARDED_FOR: '255.255.255.255'
@ -27,13 +27,13 @@ async def test_ignore_x_forwarded_for(test_client):
assert text != '255.255.255.255' assert text != '255.255.255.255'
async def test_use_x_forwarded_for(test_client): async def test_use_x_forwarded_for(aiohttp_client):
"""Test that we get the IP from the transport.""" """Test that we get the IP from the transport."""
app = web.Application() app = web.Application()
app.router.add_get('/', mock_handler) app.router.add_get('/', mock_handler)
setup_real_ip(app, True) setup_real_ip(app, True)
mock_api_client = await test_client(app) mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get('/', headers={ resp = await mock_api_client.get('/', headers={
X_FORWARDED_FOR: '255.255.255.255' X_FORWARDED_FOR: '255.255.255.255'

View file

@ -9,7 +9,7 @@ import homeassistant.components.mailbox as mailbox
@pytest.fixture @pytest.fixture
def mock_http_client(hass, test_client): def mock_http_client(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
config = { config = {
mailbox.DOMAIN: { mailbox.DOMAIN: {
@ -18,7 +18,7 @@ def mock_http_client(hass, test_client):
} }
hass.loop.run_until_complete( hass.loop.run_until_complete(
async_setup_component(hass, mailbox.DOMAIN, config)) async_setup_component(hass, mailbox.DOMAIN, config))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -59,7 +59,7 @@ class TestMQTTComponent(unittest.TestCase):
"""Helper for recording calls.""" """Helper for recording calls."""
self.calls.append(args) self.calls.append(args)
def test_client_stops_on_home_assistant_start(self): def aiohttp_client_stops_on_home_assistant_start(self):
"""Test if client stops on HA stop.""" """Test if client stops on HA stop."""
self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP) self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP)
self.hass.block_till_done() self.hass.block_till_done()
@ -156,7 +156,7 @@ class TestMQTTCallbacks(unittest.TestCase):
"""Helper for recording calls.""" """Helper for recording calls."""
self.calls.append(args) self.calls.append(args)
def test_client_starts_on_home_assistant_mqtt_setup(self): def aiohttp_client_starts_on_home_assistant_mqtt_setup(self):
"""Test if client is connected after mqtt init on bootstrap.""" """Test if client is connected after mqtt init on bootstrap."""
self.assertEqual(self.hass.data['mqtt']._mqttc.connect.call_count, 1) self.assertEqual(self.hass.data['mqtt']._mqttc.connect.call_count, 1)

View file

@ -49,7 +49,7 @@ REGISTER_URL = '/api/notify.html5'
PUBLISH_URL = '/api/notify.html5/callback' PUBLISH_URL = '/api/notify.html5/callback'
async def mock_client(hass, test_client, registrations=None): async def mock_client(hass, aiohttp_client, registrations=None):
"""Create a test client for HTML5 views.""" """Create a test client for HTML5 views."""
if registrations is None: if registrations is None:
registrations = {} registrations = {}
@ -62,7 +62,7 @@ async def mock_client(hass, test_client, registrations=None):
} }
}) })
return await test_client(hass.http.app) return await aiohttp_client(hass.http.app)
class TestHtml5Notify(object): class TestHtml5Notify(object):
@ -151,9 +151,9 @@ class TestHtml5Notify(object):
assert mock_wp.mock_calls[4][2]['gcm_key'] is None assert mock_wp.mock_calls[4][2]['gcm_key'] is None
async def test_registering_new_device_view(hass, test_client): async def test_registering_new_device_view(hass, aiohttp_client):
"""Test that the HTML view works.""" """Test that the HTML view works."""
client = await mock_client(hass, test_client) client = await mock_client(hass, aiohttp_client)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
@ -165,9 +165,9 @@ async def test_registering_new_device_view(hass, test_client):
} }
async def test_registering_new_device_expiration_view(hass, test_client): async def test_registering_new_device_expiration_view(hass, aiohttp_client):
"""Test that the HTML view works.""" """Test that the HTML view works."""
client = await mock_client(hass, test_client) client = await mock_client(hass, aiohttp_client)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
@ -178,10 +178,10 @@ async def test_registering_new_device_expiration_view(hass, test_client):
} }
async def test_registering_new_device_fails_view(hass, test_client): async def test_registering_new_device_fails_view(hass, aiohttp_client):
"""Test subs. are not altered when registering a new device fails.""" """Test subs. are not altered when registering a new device fails."""
registrations = {} registrations = {}
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json', with patch('homeassistant.components.notify.html5.save_json',
side_effect=HomeAssistantError()): side_effect=HomeAssistantError()):
@ -191,10 +191,10 @@ async def test_registering_new_device_fails_view(hass, test_client):
assert registrations == {} assert registrations == {}
async def test_registering_existing_device_view(hass, test_client): async def test_registering_existing_device_view(hass, aiohttp_client):
"""Test subscription is updated when registering existing device.""" """Test subscription is updated when registering existing device."""
registrations = {} registrations = {}
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
@ -209,10 +209,10 @@ async def test_registering_existing_device_view(hass, test_client):
} }
async def test_registering_existing_device_fails_view(hass, test_client): async def test_registering_existing_device_fails_view(hass, aiohttp_client):
"""Test sub. is not updated when registering existing device fails.""" """Test sub. is not updated when registering existing device fails."""
registrations = {} registrations = {}
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
@ -225,9 +225,9 @@ async def test_registering_existing_device_fails_view(hass, test_client):
} }
async def test_registering_new_device_validation(hass, test_client): async def test_registering_new_device_validation(hass, aiohttp_client):
"""Test various errors when registering a new device.""" """Test various errors when registering a new device."""
client = await mock_client(hass, test_client) client = await mock_client(hass, aiohttp_client)
resp = await client.post(REGISTER_URL, data=json.dumps({ resp = await client.post(REGISTER_URL, data=json.dumps({
'browser': 'invalid browser', 'browser': 'invalid browser',
@ -249,13 +249,13 @@ async def test_registering_new_device_validation(hass, test_client):
assert resp.status == 400 assert resp.status == 400
async def test_unregistering_device_view(hass, test_client): async def test_unregistering_device_view(hass, aiohttp_client):
"""Test that the HTML unregister view works.""" """Test that the HTML unregister view works."""
registrations = { registrations = {
'some device': SUBSCRIPTION_1, 'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2, 'other device': SUBSCRIPTION_2,
} }
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.delete(REGISTER_URL, data=json.dumps({ resp = await client.delete(REGISTER_URL, data=json.dumps({
@ -269,11 +269,11 @@ async def test_unregistering_device_view(hass, test_client):
} }
async def test_unregister_device_view_handle_unknown_subscription(hass, async def test_unregister_device_view_handle_unknown_subscription(
test_client): hass, aiohttp_client):
"""Test that the HTML unregister view handles unknown subscriptions.""" """Test that the HTML unregister view handles unknown subscriptions."""
registrations = {} registrations = {}
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save: with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.delete(REGISTER_URL, data=json.dumps({ resp = await client.delete(REGISTER_URL, data=json.dumps({
@ -285,13 +285,14 @@ async def test_unregister_device_view_handle_unknown_subscription(hass,
assert len(mock_save.mock_calls) == 0 assert len(mock_save.mock_calls) == 0
async def test_unregistering_device_view_handles_save_error(hass, test_client): async def test_unregistering_device_view_handles_save_error(
hass, aiohttp_client):
"""Test that the HTML unregister view handles save errors.""" """Test that the HTML unregister view handles save errors."""
registrations = { registrations = {
'some device': SUBSCRIPTION_1, 'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2, 'other device': SUBSCRIPTION_2,
} }
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('homeassistant.components.notify.html5.save_json', with patch('homeassistant.components.notify.html5.save_json',
side_effect=HomeAssistantError()): side_effect=HomeAssistantError()):
@ -306,9 +307,9 @@ async def test_unregistering_device_view_handles_save_error(hass, test_client):
} }
async def test_callback_view_no_jwt(hass, test_client): async def test_callback_view_no_jwt(hass, aiohttp_client):
"""Test that the notification callback view works without JWT.""" """Test that the notification callback view works without JWT."""
client = await mock_client(hass, test_client) client = await mock_client(hass, aiohttp_client)
resp = await client.post(PUBLISH_URL, data=json.dumps({ resp = await client.post(PUBLISH_URL, data=json.dumps({
'type': 'push', 'type': 'push',
'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72' 'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
@ -317,12 +318,12 @@ async def test_callback_view_no_jwt(hass, test_client):
assert resp.status == 401, resp.response assert resp.status == 401, resp.response
async def test_callback_view_with_jwt(hass, test_client): async def test_callback_view_with_jwt(hass, aiohttp_client):
"""Test that the notification callback view works with JWT.""" """Test that the notification callback view works with JWT."""
registrations = { registrations = {
'device': SUBSCRIPTION_1 'device': SUBSCRIPTION_1
} }
client = await mock_client(hass, test_client, registrations) client = await mock_client(hass, aiohttp_client, registrations)
with patch('pywebpush.WebPusher') as mock_wp: with patch('pywebpush.WebPusher') as mock_wp:
await hass.services.async_call('notify', 'notify', { await hass.services.async_call('notify', 'notify', {

View file

@ -52,7 +52,7 @@ class TestMHZ19Sensor(unittest.TestCase):
@patch('pmsensor.co2sensor.read_mh_z19_with_temperature', @patch('pmsensor.co2sensor.read_mh_z19_with_temperature',
side_effect=OSError('test error')) side_effect=OSError('test error'))
def test_client_update_oserror(self, mock_function): def aiohttp_client_update_oserror(self, mock_function):
"""Test MHZClient when library throws OSError.""" """Test MHZClient when library throws OSError."""
from pmsensor import co2sensor from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial') client = mhz19.MHZClient(co2sensor, 'test.serial')
@ -61,7 +61,7 @@ class TestMHZ19Sensor(unittest.TestCase):
@patch('pmsensor.co2sensor.read_mh_z19_with_temperature', @patch('pmsensor.co2sensor.read_mh_z19_with_temperature',
return_value=(5001, 24)) return_value=(5001, 24))
def test_client_update_ppm_overflow(self, mock_function): def aiohttp_client_update_ppm_overflow(self, mock_function):
"""Test MHZClient when ppm is too high.""" """Test MHZClient when ppm is too high."""
from pmsensor import co2sensor from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial') client = mhz19.MHZClient(co2sensor, 'test.serial')
@ -70,7 +70,7 @@ class TestMHZ19Sensor(unittest.TestCase):
@patch('pmsensor.co2sensor.read_mh_z19_with_temperature', @patch('pmsensor.co2sensor.read_mh_z19_with_temperature',
return_value=(1000, 24)) return_value=(1000, 24))
def test_client_update_good_read(self, mock_function): def aiohttp_client_update_good_read(self, mock_function):
"""Test MHZClient when ppm is too high.""" """Test MHZClient when ppm is too high."""
from pmsensor import co2sensor from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial') client = mhz19.MHZClient(co2sensor, 'test.serial')

View file

@ -11,10 +11,10 @@ from homeassistant.setup import async_setup_component
@pytest.fixture @pytest.fixture
def mock_api_client(hass, test_client): def mock_api_client(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
hass.loop.run_until_complete(async_setup_component(hass, 'api', {})) hass.loop.run_until_complete(async_setup_component(hass, 'api', {}))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -93,7 +93,7 @@ def test_register_before_setup(hass):
@asyncio.coroutine @asyncio.coroutine
def test_http_processing_intent(hass, test_client): def test_http_processing_intent(hass, aiohttp_client):
"""Test processing intent via HTTP API.""" """Test processing intent via HTTP API."""
class TestIntentHandler(intent.IntentHandler): class TestIntentHandler(intent.IntentHandler):
intent_type = 'OrderBeer' intent_type = 'OrderBeer'
@ -122,7 +122,7 @@ def test_http_processing_intent(hass, test_client):
}) })
assert result assert result
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post('/api/conversation/process', json={ resp = yield from client.post('/api/conversation/process', json={
'text': 'I would like the Grolsch beer' 'text': 'I would like the Grolsch beer'
}) })
@ -224,7 +224,7 @@ def test_toggle_intent(hass, sentence):
@asyncio.coroutine @asyncio.coroutine
def test_http_api(hass, test_client): def test_http_api(hass, aiohttp_client):
"""Test the HTTP conversation API.""" """Test the HTTP conversation API."""
result = yield from component.async_setup(hass, {}) result = yield from component.async_setup(hass, {})
assert result assert result
@ -232,7 +232,7 @@ def test_http_api(hass, test_client):
result = yield from async_setup_component(hass, 'conversation', {}) result = yield from async_setup_component(hass, 'conversation', {})
assert result assert result
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
hass.states.async_set('light.kitchen', 'off') hass.states.async_set('light.kitchen', 'off')
calls = async_mock_service(hass, 'homeassistant', 'turn_on') calls = async_mock_service(hass, 'homeassistant', 'turn_on')
@ -249,7 +249,7 @@ def test_http_api(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_http_api_wrong_data(hass, test_client): def test_http_api_wrong_data(hass, aiohttp_client):
"""Test the HTTP conversation API.""" """Test the HTTP conversation API."""
result = yield from component.async_setup(hass, {}) result = yield from component.async_setup(hass, {})
assert result assert result
@ -257,7 +257,7 @@ def test_http_api_wrong_data(hass, test_client):
result = yield from async_setup_component(hass, 'conversation', {}) result = yield from async_setup_component(hass, 'conversation', {})
assert result assert result
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post('/api/conversation/process', json={ resp = yield from client.post('/api/conversation/process', json={
'text': 123 'text': 123

View file

@ -12,14 +12,14 @@ from homeassistant.components.frontend import (
@pytest.fixture @pytest.fixture
def mock_http_client(hass, test_client): def mock_http_client(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
hass.loop.run_until_complete(async_setup_component(hass, 'frontend', {})) hass.loop.run_until_complete(async_setup_component(hass, 'frontend', {}))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture
def mock_http_client_with_themes(hass, test_client): def mock_http_client_with_themes(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
hass.loop.run_until_complete(async_setup_component(hass, 'frontend', { hass.loop.run_until_complete(async_setup_component(hass, 'frontend', {
DOMAIN: { DOMAIN: {
@ -29,11 +29,11 @@ def mock_http_client_with_themes(hass, test_client):
} }
} }
}})) }}))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@pytest.fixture @pytest.fixture
def mock_http_client_with_urls(hass, test_client): def mock_http_client_with_urls(hass, aiohttp_client):
"""Start the Hass HTTP component.""" """Start the Hass HTTP component."""
hass.loop.run_until_complete(async_setup_component(hass, 'frontend', { hass.loop.run_until_complete(async_setup_component(hass, 'frontend', {
DOMAIN: { DOMAIN: {
@ -42,7 +42,7 @@ def mock_http_client_with_urls(hass, test_client):
CONF_EXTRA_HTML_URL_ES5: CONF_EXTRA_HTML_URL_ES5:
["https://domain.com/my_extra_url_es5.html"] ["https://domain.com/my_extra_url_es5.html"]
}})) }}))
return hass.loop.run_until_complete(test_client(hass.http.app)) return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -7,14 +7,14 @@ import homeassistant.components.prometheus as prometheus
@pytest.fixture @pytest.fixture
def prometheus_client(loop, hass, test_client): def prometheus_client(loop, hass, aiohttp_client):
"""Initialize a test_client with Prometheus component.""" """Initialize a aiohttp_client with Prometheus component."""
assert loop.run_until_complete(async_setup_component( assert loop.run_until_complete(async_setup_component(
hass, hass,
prometheus.DOMAIN, prometheus.DOMAIN,
{}, {},
)) ))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -1,4 +1,5 @@
"""The tests for the Ring component.""" """The tests for the Ring component."""
from copy import deepcopy
import os import os
import unittest import unittest
import requests_mock import requests_mock
@ -51,7 +52,7 @@ class TestRing(unittest.TestCase):
"""Test the setup when no login is configured.""" """Test the setup when no login is configured."""
mock.post('https://api.ring.com/clients_api/session', mock.post('https://api.ring.com/clients_api/session',
text=load_fixture('ring_session.json')) text=load_fixture('ring_session.json'))
conf = self.config.copy() conf = deepcopy(VALID_CONFIG)
del conf['ring']['username'] del conf['ring']['username']
assert not setup.setup_component(self.hass, ring.DOMAIN, conf) assert not setup.setup_component(self.hass, ring.DOMAIN, conf)
@ -60,6 +61,6 @@ class TestRing(unittest.TestCase):
"""Test the setup when no password is configured.""" """Test the setup when no password is configured."""
mock.post('https://api.ring.com/clients_api/session', mock.post('https://api.ring.com/clients_api/session',
text=load_fixture('ring_session.json')) text=load_fixture('ring_session.json'))
conf = self.config.copy() conf = deepcopy(VALID_CONFIG)
del conf['ring']['password'] del conf['ring']['password']
assert not setup.setup_component(self.hass, ring.DOMAIN, conf) assert not setup.setup_component(self.hass, ring.DOMAIN, conf)

View file

@ -8,7 +8,7 @@ from homeassistant.setup import async_setup_component
@pytest.fixture @pytest.fixture
def mock_http_client(loop, hass, test_client): def mock_http_client(loop, hass, aiohttp_client):
"""Setup test fixture.""" """Setup test fixture."""
config = { config = {
'rss_feed_template': { 'rss_feed_template': {
@ -21,7 +21,7 @@ def mock_http_client(loop, hass, test_client):
loop.run_until_complete(async_setup_component(hass, loop.run_until_complete(async_setup_component(hass,
'rss_feed_template', 'rss_feed_template',
config)) config))
return loop.run_until_complete(test_client(hass.http.app)) return loop.run_until_complete(aiohttp_client(hass.http.app))
@asyncio.coroutine @asyncio.coroutine

View file

@ -54,7 +54,7 @@ def test_recent_items_intent(hass):
@asyncio.coroutine @asyncio.coroutine
def test_api_get_all(hass, test_client): def test_api_get_all(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
@ -65,7 +65,7 @@ def test_api_get_all(hass, test_client):
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'wine'}} hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'wine'}}
) )
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/shopping_list') resp = yield from client.get('/api/shopping_list')
assert resp.status == 200 assert resp.status == 200
@ -78,7 +78,7 @@ def test_api_get_all(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_api_update(hass, test_client): def test_api_update(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
@ -92,7 +92,7 @@ def test_api_update(hass, test_client):
beer_id = hass.data['shopping_list'].items[0]['id'] beer_id = hass.data['shopping_list'].items[0]['id']
wine_id = hass.data['shopping_list'].items[1]['id'] wine_id = hass.data['shopping_list'].items[1]['id']
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/shopping_list/item/{}'.format(beer_id), json={ '/api/shopping_list/item/{}'.format(beer_id), json={
'name': 'soda' 'name': 'soda'
@ -133,7 +133,7 @@ def test_api_update(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_api_update_fails(hass, test_client): def test_api_update_fails(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
@ -141,7 +141,7 @@ def test_api_update_fails(hass, test_client):
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}} hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}}
) )
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post( resp = yield from client.post(
'/api/shopping_list/non_existing', json={ '/api/shopping_list/non_existing', json={
'name': 'soda' 'name': 'soda'
@ -159,7 +159,7 @@ def test_api_update_fails(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_api_clear_completed(hass, test_client): def test_api_clear_completed(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
@ -173,7 +173,7 @@ def test_api_clear_completed(hass, test_client):
beer_id = hass.data['shopping_list'].items[0]['id'] beer_id = hass.data['shopping_list'].items[0]['id']
wine_id = hass.data['shopping_list'].items[1]['id'] wine_id = hass.data['shopping_list'].items[1]['id']
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
# Mark beer as completed # Mark beer as completed
resp = yield from client.post( resp = yield from client.post(
@ -196,11 +196,11 @@ def test_api_clear_completed(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_api_create(hass, test_client): def test_api_create(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post('/api/shopping_list/item', json={ resp = yield from client.post('/api/shopping_list/item', json={
'name': 'soda' 'name': 'soda'
}) })
@ -217,11 +217,11 @@ def test_api_create(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_api_create_fail(hass, test_client): def test_api_create_fail(hass, aiohttp_client):
"""Test the API.""" """Test the API."""
yield from async_setup_component(hass, 'shopping_list', {}) yield from async_setup_component(hass, 'shopping_list', {})
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.post('/api/shopping_list/item', json={ resp = yield from client.post('/api/shopping_list/item', json={
'name': 1234 'name': 1234
}) })

View file

@ -14,16 +14,16 @@ _LOGGER = logging.getLogger('test_logger')
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@asyncio.coroutine @asyncio.coroutine
def setup_test_case(hass, test_client): def setup_test_case(hass, aiohttp_client):
"""Setup system_log component before test case.""" """Setup system_log component before test case."""
config = {'system_log': {'max_entries': 2}} config = {'system_log': {'max_entries': 2}}
yield from async_setup_component(hass, system_log.DOMAIN, config) yield from async_setup_component(hass, system_log.DOMAIN, config)
@asyncio.coroutine @asyncio.coroutine
def get_error_log(hass, test_client, expected_count): def get_error_log(hass, aiohttp_client, expected_count):
"""Fetch all entries from system_log via the API.""" """Fetch all entries from system_log via the API."""
client = yield from test_client(hass.http.app) client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/error/all') resp = yield from client.get('/api/error/all')
assert resp.status == 200 assert resp.status == 200
@ -53,41 +53,41 @@ def get_frame(name):
@asyncio.coroutine @asyncio.coroutine
def test_normal_logs(hass, test_client): def test_normal_logs(hass, aiohttp_client):
"""Test that debug and info are not logged.""" """Test that debug and info are not logged."""
_LOGGER.debug('debug') _LOGGER.debug('debug')
_LOGGER.info('info') _LOGGER.info('info')
# Assert done by get_error_log # Assert done by get_error_log
yield from get_error_log(hass, test_client, 0) yield from get_error_log(hass, aiohttp_client, 0)
@asyncio.coroutine @asyncio.coroutine
def test_exception(hass, test_client): def test_exception(hass, aiohttp_client):
"""Test that exceptions are logged and retrieved correctly.""" """Test that exceptions are logged and retrieved correctly."""
_generate_and_log_exception('exception message', 'log message') _generate_and_log_exception('exception message', 'log message')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert_log(log, 'exception message', 'log message', 'ERROR') assert_log(log, 'exception message', 'log message', 'ERROR')
@asyncio.coroutine @asyncio.coroutine
def test_warning(hass, test_client): def test_warning(hass, aiohttp_client):
"""Test that warning are logged and retrieved correctly.""" """Test that warning are logged and retrieved correctly."""
_LOGGER.warning('warning message') _LOGGER.warning('warning message')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert_log(log, '', 'warning message', 'WARNING') assert_log(log, '', 'warning message', 'WARNING')
@asyncio.coroutine @asyncio.coroutine
def test_error(hass, test_client): def test_error(hass, aiohttp_client):
"""Test that errors are logged and retrieved correctly.""" """Test that errors are logged and retrieved correctly."""
_LOGGER.error('error message') _LOGGER.error('error message')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert_log(log, '', 'error message', 'ERROR') assert_log(log, '', 'error message', 'ERROR')
@asyncio.coroutine @asyncio.coroutine
def test_error_posted_as_event(hass, test_client): def test_error_posted_as_event(hass, aiohttp_client):
"""Test that error are posted as events.""" """Test that error are posted as events."""
events = [] events = []
@ -106,26 +106,26 @@ def test_error_posted_as_event(hass, test_client):
@asyncio.coroutine @asyncio.coroutine
def test_critical(hass, test_client): def test_critical(hass, aiohttp_client):
"""Test that critical are logged and retrieved correctly.""" """Test that critical are logged and retrieved correctly."""
_LOGGER.critical('critical message') _LOGGER.critical('critical message')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert_log(log, '', 'critical message', 'CRITICAL') assert_log(log, '', 'critical message', 'CRITICAL')
@asyncio.coroutine @asyncio.coroutine
def test_remove_older_logs(hass, test_client): def test_remove_older_logs(hass, aiohttp_client):
"""Test that older logs are rotated out.""" """Test that older logs are rotated out."""
_LOGGER.error('error message 1') _LOGGER.error('error message 1')
_LOGGER.error('error message 2') _LOGGER.error('error message 2')
_LOGGER.error('error message 3') _LOGGER.error('error message 3')
log = yield from get_error_log(hass, test_client, 2) log = yield from get_error_log(hass, aiohttp_client, 2)
assert_log(log[0], '', 'error message 3', 'ERROR') assert_log(log[0], '', 'error message 3', 'ERROR')
assert_log(log[1], '', 'error message 2', 'ERROR') assert_log(log[1], '', 'error message 2', 'ERROR')
@asyncio.coroutine @asyncio.coroutine
def test_clear_logs(hass, test_client): def test_clear_logs(hass, aiohttp_client):
"""Test that the log can be cleared via a service call.""" """Test that the log can be cleared via a service call."""
_LOGGER.error('error message') _LOGGER.error('error message')
@ -135,7 +135,7 @@ def test_clear_logs(hass, test_client):
yield from hass.async_block_till_done() yield from hass.async_block_till_done()
# Assert done by get_error_log # Assert done by get_error_log
yield from get_error_log(hass, test_client, 0) yield from get_error_log(hass, aiohttp_client, 0)
@asyncio.coroutine @asyncio.coroutine
@ -182,12 +182,12 @@ def test_write_choose_level(hass):
@asyncio.coroutine @asyncio.coroutine
def test_unknown_path(hass, test_client): def test_unknown_path(hass, aiohttp_client):
"""Test error logged from unknown path.""" """Test error logged from unknown path."""
_LOGGER.findCaller = MagicMock( _LOGGER.findCaller = MagicMock(
return_value=('unknown_path', 0, None, None)) return_value=('unknown_path', 0, None, None))
_LOGGER.error('error message') _LOGGER.error('error message')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert log['source'] == 'unknown_path' assert log['source'] == 'unknown_path'
@ -207,30 +207,30 @@ def log_error_from_test_path(path):
@asyncio.coroutine @asyncio.coroutine
def test_homeassistant_path(hass, test_client): def test_homeassistant_path(hass, aiohttp_client):
"""Test error logged from homeassistant path.""" """Test error logged from homeassistant path."""
with patch('homeassistant.components.system_log.HOMEASSISTANT_PATH', with patch('homeassistant.components.system_log.HOMEASSISTANT_PATH',
new=['venv_path/homeassistant']): new=['venv_path/homeassistant']):
log_error_from_test_path( log_error_from_test_path(
'venv_path/homeassistant/component/component.py') 'venv_path/homeassistant/component/component.py')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert log['source'] == 'component/component.py' assert log['source'] == 'component/component.py'
@asyncio.coroutine @asyncio.coroutine
def test_config_path(hass, test_client): def test_config_path(hass, aiohttp_client):
"""Test error logged from config path.""" """Test error logged from config path."""
with patch.object(hass.config, 'config_dir', new='config'): with patch.object(hass.config, 'config_dir', new='config'):
log_error_from_test_path('config/custom_component/test.py') log_error_from_test_path('config/custom_component/test.py')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert log['source'] == 'custom_component/test.py' assert log['source'] == 'custom_component/test.py'
@asyncio.coroutine @asyncio.coroutine
def test_netdisco_path(hass, test_client): def test_netdisco_path(hass, aiohttp_client):
"""Test error logged from netdisco path.""" """Test error logged from netdisco path."""
with patch.dict('sys.modules', with patch.dict('sys.modules',
netdisco=MagicMock(__path__=['venv_path/netdisco'])): netdisco=MagicMock(__path__=['venv_path/netdisco'])):
log_error_from_test_path('venv_path/netdisco/disco_component.py') log_error_from_test_path('venv_path/netdisco/disco_component.py')
log = (yield from get_error_log(hass, test_client, 1))[0] log = (yield from get_error_log(hass, aiohttp_client, 1))[0]
assert log['source'] == 'disco_component.py' assert log['source'] == 'disco_component.py'

View file

@ -16,12 +16,12 @@ API_PASSWORD = 'test1234'
@pytest.fixture @pytest.fixture
def websocket_client(loop, hass, test_client): def websocket_client(loop, hass, aiohttp_client):
"""Websocket client fixture connected to websocket server.""" """Websocket client fixture connected to websocket server."""
assert loop.run_until_complete( assert loop.run_until_complete(
async_setup_component(hass, 'websocket_api')) async_setup_component(hass, 'websocket_api'))
client = loop.run_until_complete(test_client(hass.http.app)) client = loop.run_until_complete(aiohttp_client(hass.http.app))
ws = loop.run_until_complete(client.ws_connect(wapi.URL)) ws = loop.run_until_complete(client.ws_connect(wapi.URL))
auth_ok = loop.run_until_complete(ws.receive_json()) auth_ok = loop.run_until_complete(ws.receive_json())
assert auth_ok['type'] == wapi.TYPE_AUTH_OK assert auth_ok['type'] == wapi.TYPE_AUTH_OK
@ -33,7 +33,7 @@ def websocket_client(loop, hass, test_client):
@pytest.fixture @pytest.fixture
def no_auth_websocket_client(hass, loop, test_client): def no_auth_websocket_client(hass, loop, aiohttp_client):
"""Websocket connection that requires authentication.""" """Websocket connection that requires authentication."""
assert loop.run_until_complete( assert loop.run_until_complete(
async_setup_component(hass, 'websocket_api', { async_setup_component(hass, 'websocket_api', {
@ -42,7 +42,7 @@ def no_auth_websocket_client(hass, loop, test_client):
} }
})) }))
client = loop.run_until_complete(test_client(hass.http.app)) client = loop.run_until_complete(aiohttp_client(hass.http.app))
ws = loop.run_until_complete(client.ws_connect(wapi.URL)) ws = loop.run_until_complete(client.ws_connect(wapi.URL))
auth_ok = loop.run_until_complete(ws.receive_json()) auth_ok = loop.run_until_complete(ws.receive_json())

View file

@ -14,7 +14,7 @@ from tests.common import get_test_home_assistant
@pytest.fixture @pytest.fixture
def camera_client(hass, test_client): def camera_client(hass, aiohttp_client):
"""Fixture to fetch camera streams.""" """Fixture to fetch camera streams."""
assert hass.loop.run_until_complete(async_setup_component(hass, 'camera', { assert hass.loop.run_until_complete(async_setup_component(hass, 'camera', {
'camera': { 'camera': {
@ -23,7 +23,7 @@ def camera_client(hass, test_client):
'mjpeg_url': 'http://example.com/mjpeg_stream', 'mjpeg_url': 'http://example.com/mjpeg_stream',
}})) }}))
yield hass.loop.run_until_complete(test_client(hass.http.app)) yield hass.loop.run_until_complete(aiohttp_client(hass.http.app))
class TestHelpersAiohttpClient(unittest.TestCase): class TestHelpersAiohttpClient(unittest.TestCase):

View file

@ -82,7 +82,8 @@ class AiohttpClientMocker:
def create_session(self, loop): def create_session(self, loop):
"""Create a ClientSession that is bound to this mocker.""" """Create a ClientSession that is bound to this mocker."""
session = ClientSession(loop=loop) session = ClientSession(loop=loop)
session._request = self.match_request # Setting directly on `session` will raise deprecation warning
object.__setattr__(session, '_request', self.match_request)
return session return session
async def match_request(self, method, url, *, data=None, auth=None, async def match_request(self, method, url, *, data=None, auth=None,