async HTTP component (#3914)
* Migrate WSGI to asyncio * Rename wsgi -> http * Python 3.4 compat * Move linting to Python 3.4 * lint * Lint * Fix Python 3.4 mock_open + binary data * Surpress logging aiohttp.access * Spelling * Sending files is a coroutine * More callback annotations and naming fixes * Fix ios
This commit is contained in:
1 parent
9aa88819a5
commit
519d9f2fd0
45 files changed
+1422
-1009
No files matched your search
+1
-29
@@ -1,29 +1 @@
|
||||
"""Setup some common test helper things."""
|
||||
import functools
|
||||
import logging
|
||||
|
||||
from homeassistant import util
|
||||
from homeassistant.util import location
|
||||
|
||||
logging.basicConfig()
|
||||
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
|
||||
|
||||
|
||||
def test_real(func):
|
||||
"""Force a function to require a keyword _test_real to be passed in."""
|
||||
@functools.wraps(func)
|
||||
def guard_func(*args, **kwargs):
|
||||
real = kwargs.pop('_test_real', None)
|
||||
|
||||
if not real:
|
||||
raise Exception('Forgot to mock or pass "_test_real=True" to %s',
|
||||
func.__name__)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return guard_func
|
||||
|
||||
# Guard a few functions that would make network connections
|
||||
location.detect_location_info = test_real(location.detect_location_info)
|
||||
location.elevation = test_real(location.elevation)
|
||||
util.get_local_ip = lambda: '127.0.0.1'
|
||||
"""Tests for Home Assistant."""
|
||||
+42
-14
@@ -38,23 +38,11 @@ def get_test_home_assistant(num_threads=None):
|
||||
orig_num_threads = ha.MIN_WORKER_THREAD
|
||||
ha.MIN_WORKER_THREAD = num_threads
|
||||
|
||||
hass = ha.HomeAssistant(loop)
|
||||
hass = loop.run_until_complete(async_test_home_assistant(loop))
|
||||
|
||||
if num_threads:
|
||||
ha.MIN_WORKER_THREAD = orig_num_threads
|
||||
|
||||
hass.config.location_name = 'test home'
|
||||
hass.config.config_dir = get_test_config_dir()
|
||||
hass.config.latitude = 32.87336
|
||||
hass.config.longitude = -117.22743
|
||||
hass.config.elevation = 0
|
||||
hass.config.time_zone = date_util.get_time_zone('US/Pacific')
|
||||
hass.config.units = METRIC_SYSTEM
|
||||
hass.config.skip_pip = True
|
||||
|
||||
if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
|
||||
loader.prepare(hass)
|
||||
|
||||
# FIXME should not be a daemon. Means hass.stop() not called in teardown
|
||||
stop_event = threading.Event()
|
||||
|
||||
@@ -98,6 +86,35 @@ def get_test_home_assistant(num_threads=None):
|
||||
return hass
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_test_home_assistant(loop):
|
||||
"""Return a Home Assistant object pointing at test config dir."""
|
||||
loop._thread_ident = threading.get_ident()
|
||||
|
||||
def get_hass():
|
||||
"""Temp while we migrate core HASS over to be async constructors."""
|
||||
hass = ha.HomeAssistant(loop)
|
||||
|
||||
hass.config.location_name = 'test home'
|
||||
hass.config.config_dir = get_test_config_dir()
|
||||
hass.config.latitude = 32.87336
|
||||
hass.config.longitude = -117.22743
|
||||
hass.config.elevation = 0
|
||||
hass.config.time_zone = date_util.get_time_zone('US/Pacific')
|
||||
hass.config.units = METRIC_SYSTEM
|
||||
hass.config.skip_pip = True
|
||||
|
||||
if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
|
||||
loader.prepare(hass)
|
||||
|
||||
hass.state = ha.CoreState.running
|
||||
return hass
|
||||
|
||||
hass = yield from loop.run_in_executor(None, get_hass)
|
||||
|
||||
return hass
|
||||
|
||||
|
||||
def get_test_instance_port():
|
||||
"""Return unused port for running test instance.
|
||||
|
||||
@@ -181,8 +198,19 @@ def mock_state_change_event(hass, new_state, old_state=None):
|
||||
|
||||
def mock_http_component(hass):
|
||||
"""Mock the HTTP component."""
|
||||
hass.wsgi = mock.MagicMock()
|
||||
hass.http = mock.MagicMock()
|
||||
hass.config.components.append('http')
|
||||
hass.http.views = {}
|
||||
|
||||
def mock_register_view(view):
|
||||
"""Store registered view."""
|
||||
if isinstance(view, type):
|
||||
# Instantiate the view, if needed
|
||||
view = view(hass)
|
||||
|
||||
hass.http.views[view.name] = view
|
||||
|
||||
hass.http.register_view = mock_register_view
|
||||
|
||||
|
||||
def mock_mqtt_component(hass):
|
||||
|
||||
@@ -1,36 +1,18 @@
|
||||
"""The tests for generic camera component."""
|
||||
import unittest
|
||||
import asyncio
|
||||
from unittest import mock
|
||||
|
||||
import requests_mock
|
||||
from werkzeug.test import EnvironBuilder
|
||||
|
||||
from homeassistant.bootstrap import setup_component
|
||||
from homeassistant.components.http import request_class
|
||||
|
||||
from tests.common import get_test_home_assistant
|
||||
|
||||
|
||||
class TestGenericCamera(unittest.TestCase):
|
||||
"""Test the generic camera platform."""
|
||||
@asyncio.coroutine
|
||||
def test_fetching_url(aioclient_mock, hass, test_client):
|
||||
"""Test that it fetches the given url."""
|
||||
aioclient_mock.get('http://example.com', text='hello world')
|
||||
|
||||
def setUp(self):
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = get_test_home_assistant()
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
self.hass.config.components.append('http')
|
||||
|
||||
def tearDown(self):
|
||||
"""Stop everything that was started."""
|
||||
self.hass.stop()
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_fetching_url(self, m):
|
||||
"""Test that it fetches the given url."""
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
m.get('http://example.com', text='hello world')
|
||||
|
||||
assert setup_component(self.hass, 'camera', {
|
||||
def setup_platform():
|
||||
"""Setup the platform."""
|
||||
assert setup_component(hass, 'camera', {
|
||||
'camera': {
|
||||
'name': 'config_test',
|
||||
'platform': 'generic',
|
||||
@@ -39,32 +21,32 @@ class TestGenericCamera(unittest.TestCase):
|
||||
'password': 'pass'
|
||||
}})
|
||||
|
||||
image_view = self.hass.wsgi.mock_calls[0][1][0]
|
||||
yield from hass.loop.run_in_executor(None, setup_platform)
|
||||
|
||||
builder = EnvironBuilder(method='GET')
|
||||
Request = request_class()
|
||||
request = Request(builder.get_environ())
|
||||
request.authenticated = True
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
client = yield from test_client(hass.http.app)
|
||||
|
||||
assert m.call_count == 1
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == 'hello world'
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
|
||||
image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 2
|
||||
assert aioclient_mock.call_count == 1
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello world'
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_limit_refetch(self, m):
|
||||
"""Test that it fetches the given url."""
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
from requests.exceptions import Timeout
|
||||
m.get('http://example.com/5a', text='hello world')
|
||||
m.get('http://example.com/10a', text='hello world')
|
||||
m.get('http://example.com/15a', text='hello planet')
|
||||
m.get('http://example.com/20a', status_code=404)
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 2
|
||||
|
||||
assert setup_component(self.hass, 'camera', {
|
||||
|
||||
@asyncio.coroutine
|
||||
def test_limit_refetch(aioclient_mock, hass, test_client):
|
||||
"""Test that it fetches the given url."""
|
||||
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/15a', text='hello planet')
|
||||
aioclient_mock.get('http://example.com/20a', status=404)
|
||||
|
||||
def setup_platform():
|
||||
"""Setup the platform."""
|
||||
assert setup_component(hass, 'camera', {
|
||||
'camera': {
|
||||
'name': 'config_test',
|
||||
'platform': 'generic',
|
||||
@@ -73,43 +55,47 @@ class TestGenericCamera(unittest.TestCase):
|
||||
'limit_refetch_to_url_change': True,
|
||||
}})
|
||||
|
||||
image_view = self.hass.wsgi.mock_calls[0][1][0]
|
||||
yield from hass.loop.run_in_executor(None, setup_platform)
|
||||
|
||||
builder = EnvironBuilder(method='GET')
|
||||
Request = request_class()
|
||||
request = Request(builder.get_environ())
|
||||
request.authenticated = True
|
||||
client = yield from test_client(hass.http.app)
|
||||
|
||||
self.hass.states.set('sensor.temp', '5')
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
|
||||
with mock.patch('requests.get', side_effect=Timeout()):
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 0
|
||||
assert resp.status_code == 500, resp.response
|
||||
hass.states.async_set('sensor.temp', '5')
|
||||
|
||||
self.hass.states.set('sensor.temp', '10')
|
||||
with mock.patch('async_timeout.timeout',
|
||||
side_effect=asyncio.TimeoutError()):
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 0
|
||||
assert resp.status == 500
|
||||
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 1
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == 'hello world'
|
||||
hass.states.async_set('sensor.temp', '10')
|
||||
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 1
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == 'hello world'
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 1
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello world'
|
||||
|
||||
self.hass.states.set('sensor.temp', '15')
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 1
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello world'
|
||||
|
||||
# Url change = fetch new image
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 2
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == 'hello planet'
|
||||
hass.states.async_set('sensor.temp', '15')
|
||||
|
||||
# Cause a template render error
|
||||
self.hass.states.remove('sensor.temp')
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
assert m.call_count == 2
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == 'hello planet'
|
||||
# Url change = fetch new image
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 2
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello planet'
|
||||
|
||||
# Cause a template render error
|
||||
hass.states.async_remove('sensor.temp')
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
assert aioclient_mock.call_count == 2
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello planet'
|
||||
@@ -1,70 +1,60 @@
|
||||
"""The tests for local file camera component."""
|
||||
import unittest
|
||||
import asyncio
|
||||
from unittest import mock
|
||||
|
||||
from werkzeug.test import EnvironBuilder
|
||||
# Using third party package because of a bug reading binary data in Python 3.4
|
||||
# https://bugs.python.org/issue23004
|
||||
from mock_open import MockOpen
|
||||
|
||||
from homeassistant.bootstrap import setup_component
|
||||
from homeassistant.components.http import request_class
|
||||
|
||||
from tests.common import get_test_home_assistant, assert_setup_component
|
||||
from tests.common import assert_setup_component, mock_http_component
|
||||
|
||||
|
||||
class TestLocalCamera(unittest.TestCase):
|
||||
"""Test the local file camera component."""
|
||||
@asyncio.coroutine
|
||||
def test_loading_file(hass, test_client):
|
||||
"""Test that it loads image from disk."""
|
||||
@mock.patch('os.path.isfile', mock.Mock(return_value=True))
|
||||
@mock.patch('os.access', mock.Mock(return_value=True))
|
||||
def setup_platform():
|
||||
"""Setup platform inside callback."""
|
||||
assert setup_component(hass, 'camera', {
|
||||
'camera': {
|
||||
'name': 'config_test',
|
||||
'platform': 'local_file',
|
||||
'file_path': 'mock.file',
|
||||
}})
|
||||
|
||||
def setUp(self):
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = get_test_home_assistant()
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
self.hass.config.components.append('http')
|
||||
yield from hass.loop.run_in_executor(None, setup_platform)
|
||||
|
||||
def tearDown(self):
|
||||
"""Stop everything that was started."""
|
||||
self.hass.stop()
|
||||
client = yield from test_client(hass.http.app)
|
||||
|
||||
def test_loading_file(self):
|
||||
"""Test that it loads image from disk."""
|
||||
test_string = 'hello'
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
m_open = MockOpen(read_data=b'hello')
|
||||
with mock.patch(
|
||||
'homeassistant.components.camera.local_file.open',
|
||||
m_open, create=True
|
||||
):
|
||||
resp = yield from client.get('/api/camera_proxy/camera.config_test')
|
||||
|
||||
with mock.patch('os.path.isfile', mock.Mock(return_value=True)), \
|
||||
mock.patch('os.access', mock.Mock(return_value=True)):
|
||||
assert setup_component(self.hass, 'camera', {
|
||||
'camera': {
|
||||
'name': 'config_test',
|
||||
'platform': 'local_file',
|
||||
'file_path': 'mock.file',
|
||||
}})
|
||||
assert resp.status == 200
|
||||
body = yield from resp.text()
|
||||
assert body == 'hello'
|
||||
|
||||
image_view = self.hass.wsgi.mock_calls[0][1][0]
|
||||
|
||||
m_open = mock.mock_open(read_data=test_string)
|
||||
with mock.patch(
|
||||
'homeassistant.components.camera.local_file.open',
|
||||
m_open, create=True
|
||||
):
|
||||
builder = EnvironBuilder(method='GET')
|
||||
Request = request_class() # pylint: disable=invalid-name
|
||||
request = Request(builder.get_environ())
|
||||
request.authenticated = True
|
||||
resp = image_view.get(request, 'camera.config_test')
|
||||
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.response[0].decode('utf-8') == test_string
|
||||
|
||||
def test_file_not_readable(self):
|
||||
"""Test local file will not setup when file is not readable."""
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
@asyncio.coroutine
|
||||
def test_file_not_readable(hass):
|
||||
"""Test local file will not setup when file is not readable."""
|
||||
mock_http_component(hass)
|
||||
|
||||
def run_test():
|
||||
with mock.patch('os.path.isfile', mock.Mock(return_value=True)), \
|
||||
mock.patch('os.access', return_value=False), \
|
||||
assert_setup_component(0):
|
||||
assert setup_component(self.hass, 'camera', {
|
||||
assert_setup_component(0, 'camera'):
|
||||
assert setup_component(hass, 'camera', {
|
||||
'camera': {
|
||||
'name': 'config_test',
|
||||
'platform': 'local_file',
|
||||
'file_path': 'mock.file',
|
||||
}})
|
||||
|
||||
assert [] == self.hass.states.all()
|
||||
yield from hass.loop.run_in_executor(None, run_test)
|
||||
@@ -18,7 +18,7 @@ class TestUVCSetup(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = get_test_home_assistant()
|
||||
self.hass.wsgi = mock.MagicMock()
|
||||
self.hass.http = mock.MagicMock()
|
||||
self.hass.config.components = ['http']
|
||||
|
||||
def tearDown(self):
|
||||
|
||||
@@ -18,42 +18,19 @@ HTTP_BASE_URL = 'http://127.0.0.1:{}'.format(SERVER_PORT)
|
||||
API_PASSWORD = "test1234"
|
||||
HA_HEADERS = {HTTP_HEADER_HA_AUTH: API_PASSWORD}
|
||||
|
||||
hass = None
|
||||
|
||||
entity_id = 'media_player.walkman'
|
||||
|
||||
|
||||
def setUpModule(): # pylint: disable=invalid-name
|
||||
"""Initalize a Home Assistant server."""
|
||||
global hass
|
||||
|
||||
hass = get_test_home_assistant()
|
||||
setup_component(hass, http.DOMAIN, {
|
||||
http.DOMAIN: {
|
||||
http.CONF_SERVER_PORT: SERVER_PORT,
|
||||
http.CONF_API_PASSWORD: API_PASSWORD,
|
||||
},
|
||||
})
|
||||
|
||||
hass.start()
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def tearDownModule(): # pylint: disable=invalid-name
|
||||
"""Stop the Home Assistant server."""
|
||||
hass.stop()
|
||||
|
||||
|
||||
class TestDemoMediaPlayer(unittest.TestCase):
|
||||
"""Test the media_player module."""
|
||||
|
||||
def setUp(self): # pylint: disable=invalid-name
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = hass
|
||||
try:
|
||||
self.hass.config.components.remove(mp.DOMAIN)
|
||||
except ValueError:
|
||||
pass
|
||||
self.hass = get_test_home_assistant()
|
||||
|
||||
def tearDown(self):
|
||||
"""Shut down test instance."""
|
||||
self.hass.stop()
|
||||
|
||||
def test_source_select(self):
|
||||
"""Test the input source service."""
|
||||
@@ -226,21 +203,6 @@ class TestDemoMediaPlayer(unittest.TestCase):
|
||||
assert 0 == (mp.SUPPORT_PREVIOUS_TRACK &
|
||||
state.attributes.get('supported_media_commands'))
|
||||
|
||||
@requests_mock.Mocker(real_http=True)
|
||||
def test_media_image_proxy(self, m):
|
||||
"""Test the media server image proxy server ."""
|
||||
fake_picture_data = 'test.test'
|
||||
m.get('https://graph.facebook.com/v2.5/107771475912710/'
|
||||
'picture?type=large', text=fake_picture_data)
|
||||
assert setup_component(
|
||||
self.hass, mp.DOMAIN,
|
||||
{'media_player': {'platform': 'demo'}})
|
||||
assert self.hass.states.is_state(entity_id, 'playing')
|
||||
state = self.hass.states.get(entity_id)
|
||||
req = requests.get(HTTP_BASE_URL +
|
||||
state.attributes.get('entity_picture'))
|
||||
assert req.text == fake_picture_data
|
||||
|
||||
@patch('homeassistant.components.media_player.demo.DemoYoutubePlayer.'
|
||||
'media_seek')
|
||||
def test_play_media(self, mock_seek):
|
||||
@@ -275,3 +237,42 @@ class TestDemoMediaPlayer(unittest.TestCase):
|
||||
mp.media_seek(self.hass, 100, ent_id)
|
||||
self.hass.block_till_done()
|
||||
assert mock_seek.called
|
||||
|
||||
|
||||
class TestMediaPlayerWeb(unittest.TestCase):
|
||||
"""Test the media player web views sensor."""
|
||||
|
||||
def setUp(self):
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = get_test_home_assistant()
|
||||
|
||||
setup_component(self.hass, http.DOMAIN, {
|
||||
http.DOMAIN: {
|
||||
http.CONF_SERVER_PORT: SERVER_PORT,
|
||||
http.CONF_API_PASSWORD: API_PASSWORD,
|
||||
},
|
||||
})
|
||||
|
||||
self.hass.start()
|
||||
time.sleep(0.05)
|
||||
|
||||
def tearDown(self):
|
||||
"""Stop everything that was started."""
|
||||
self.hass.stop()
|
||||
|
||||
@requests_mock.Mocker(real_http=True)
|
||||
def test_media_image_proxy(self, m):
|
||||
"""Test the media server image proxy server ."""
|
||||
fake_picture_data = 'test.test'
|
||||
m.get('https://graph.facebook.com/v2.5/107771475912710/'
|
||||
'picture?type=large', text=fake_picture_data)
|
||||
self.hass.block_till_done()
|
||||
assert setup_component(
|
||||
self.hass, mp.DOMAIN,
|
||||
{'media_player': {'platform': 'demo'}})
|
||||
assert self.hass.states.is_state(entity_id, 'playing')
|
||||
state = self.hass.states.get(entity_id)
|
||||
req = requests.get(HTTP_BASE_URL +
|
||||
state.attributes.get('entity_picture'))
|
||||
assert req.status_code == 200
|
||||
assert req.text == fake_picture_data
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Test HTML5 notify platform."""
|
||||
import asyncio
|
||||
import json
|
||||
from unittest.mock import patch, MagicMock, mock_open
|
||||
|
||||
from werkzeug.test import EnvironBuilder
|
||||
from aiohttp import web
|
||||
|
||||
from homeassistant.components.http import request_class
|
||||
from homeassistant.components.notify import html5
|
||||
|
||||
SUBSCRIPTION_1 = {
|
||||
@@ -35,6 +35,9 @@ SUBSCRIPTION_3 = {
|
||||
},
|
||||
}
|
||||
|
||||
REGISTER_URL = '/api/notify.html5'
|
||||
PUBLISH_URL = '/api/notify.html5/callback'
|
||||
|
||||
|
||||
class TestHtml5Notify(object):
|
||||
"""Tests for HTML5 notify platform."""
|
||||
@@ -94,9 +97,13 @@ class TestHtml5Notify(object):
|
||||
assert payload['body'] == 'Hello'
|
||||
assert payload['icon'] == 'beer.png'
|
||||
|
||||
def test_registering_new_device_view(self):
|
||||
@asyncio.coroutine
|
||||
def test_registering_new_device_view(self, loop, test_client):
|
||||
"""Test that the HTML view works."""
|
||||
hass = MagicMock()
|
||||
expected = {
|
||||
'unnamed device': SUBSCRIPTION_1,
|
||||
}
|
||||
|
||||
m = mock_open()
|
||||
with patch(
|
||||
@@ -114,21 +121,20 @@ class TestHtml5Notify(object):
|
||||
assert view.json_path == hass.config.path.return_value
|
||||
assert view.registrations == {}
|
||||
|
||||
builder = EnvironBuilder(method='POST',
|
||||
data=json.dumps(SUBSCRIPTION_1))
|
||||
Request = request_class()
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
resp = yield from client.post(REGISTER_URL,
|
||||
data=json.dumps(SUBSCRIPTION_1))
|
||||
|
||||
expected = {
|
||||
'unnamed device': SUBSCRIPTION_1,
|
||||
}
|
||||
|
||||
assert resp.status_code == 200, resp.response
|
||||
content = yield from resp.text()
|
||||
assert resp.status == 200, content
|
||||
assert view.registrations == expected
|
||||
handle = m()
|
||||
assert json.loads(handle.write.call_args[0][0]) == expected
|
||||
|
||||
def test_registering_new_device_validation(self):
|
||||
@asyncio.coroutine
|
||||
def test_registering_new_device_validation(self, loop, test_client):
|
||||
"""Test various errors when registering a new device."""
|
||||
hass = MagicMock()
|
||||
|
||||
@@ -146,34 +152,34 @@ class TestHtml5Notify(object):
|
||||
|
||||
view = hass.mock_calls[1][1][0]
|
||||
|
||||
Request = request_class()
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
builder = EnvironBuilder(method='POST', data=json.dumps({
|
||||
resp = yield from client.post(REGISTER_URL, data=json.dumps({
|
||||
'browser': 'invalid browser',
|
||||
'subscription': 'sub info',
|
||||
}))
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
assert resp.status_code == 400, resp.response
|
||||
assert resp.status == 400
|
||||
|
||||
builder = EnvironBuilder(method='POST', data=json.dumps({
|
||||
resp = yield from client.post(REGISTER_URL, data=json.dumps({
|
||||
'browser': 'chrome',
|
||||
}))
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
assert resp.status_code == 400, resp.response
|
||||
assert resp.status == 400
|
||||
|
||||
builder = EnvironBuilder(method='POST', data=json.dumps({
|
||||
'browser': 'chrome',
|
||||
'subscription': 'sub info',
|
||||
}))
|
||||
with patch('homeassistant.components.notify.html5._save_config',
|
||||
return_value=False):
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
assert resp.status_code == 400, resp.response
|
||||
# resp = view.post(Request(builder.get_environ()))
|
||||
resp = yield from client.post(REGISTER_URL, data=json.dumps({
|
||||
'browser': 'chrome',
|
||||
'subscription': 'sub info',
|
||||
}))
|
||||
|
||||
@patch('homeassistant.components.notify.html5.os')
|
||||
def test_unregistering_device_view(self, mock_os):
|
||||
assert resp.status == 400
|
||||
|
||||
@asyncio.coroutine
|
||||
def test_unregistering_device_view(self, loop, test_client):
|
||||
"""Test that the HTML unregister view works."""
|
||||
mock_os.path.isfile.return_value = True
|
||||
hass = MagicMock()
|
||||
|
||||
config = {
|
||||
@@ -182,11 +188,14 @@ class TestHtml5Notify(object):
|
||||
}
|
||||
|
||||
m = mock_open(read_data=json.dumps(config))
|
||||
with patch(
|
||||
'homeassistant.components.notify.html5.open', m, create=True
|
||||
):
|
||||
|
||||
with patch('homeassistant.components.notify.html5.open', m,
|
||||
create=True):
|
||||
hass.config.path.return_value = 'file.conf'
|
||||
service = html5.get_service(hass, {})
|
||||
|
||||
with patch('homeassistant.components.notify.html5.os.path.isfile',
|
||||
return_value=True):
|
||||
service = html5.get_service(hass, {})
|
||||
|
||||
assert service is not None
|
||||
|
||||
@@ -197,23 +206,25 @@ class TestHtml5Notify(object):
|
||||
assert view.json_path == hass.config.path.return_value
|
||||
assert view.registrations == config
|
||||
|
||||
builder = EnvironBuilder(method='DELETE', data=json.dumps({
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
resp = yield from client.delete(REGISTER_URL, data=json.dumps({
|
||||
'subscription': SUBSCRIPTION_1['subscription'],
|
||||
}))
|
||||
Request = request_class()
|
||||
resp = view.delete(Request(builder.get_environ()))
|
||||
|
||||
config.pop('some device')
|
||||
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.status == 200, resp.response
|
||||
assert view.registrations == config
|
||||
handle = m()
|
||||
assert json.loads(handle.write.call_args[0][0]) == config
|
||||
|
||||
@patch('homeassistant.components.notify.html5.os')
|
||||
def test_unregister_device_view_handle_unknown_subscription(self, mock_os):
|
||||
@asyncio.coroutine
|
||||
def test_unregister_device_view_handle_unknown_subscription(self, loop,
|
||||
test_client):
|
||||
"""Test that the HTML unregister view handles unknown subscriptions."""
|
||||
mock_os.path.isfile.return_value = True
|
||||
hass = MagicMock()
|
||||
|
||||
config = {
|
||||
@@ -226,7 +237,9 @@ class TestHtml5Notify(object):
|
||||
'homeassistant.components.notify.html5.open', m, create=True
|
||||
):
|
||||
hass.config.path.return_value = 'file.conf'
|
||||
service = html5.get_service(hass, {})
|
||||
with patch('homeassistant.components.notify.html5.os.path.isfile',
|
||||
return_value=True):
|
||||
service = html5.get_service(hass, {})
|
||||
|
||||
assert service is not None
|
||||
|
||||
@@ -237,21 +250,23 @@ class TestHtml5Notify(object):
|
||||
assert view.json_path == hass.config.path.return_value
|
||||
assert view.registrations == config
|
||||
|
||||
builder = EnvironBuilder(method='DELETE', data=json.dumps({
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
resp = yield from client.delete(REGISTER_URL, data=json.dumps({
|
||||
'subscription': SUBSCRIPTION_3['subscription']
|
||||
}))
|
||||
Request = request_class()
|
||||
resp = view.delete(Request(builder.get_environ()))
|
||||
|
||||
assert resp.status_code == 200, resp.response
|
||||
assert resp.status == 200, resp.response
|
||||
assert view.registrations == config
|
||||
handle = m()
|
||||
assert handle.write.call_count == 0
|
||||
|
||||
@patch('homeassistant.components.notify.html5.os')
|
||||
def test_unregistering_device_view_handles_json_safe_error(self, mock_os):
|
||||
@asyncio.coroutine
|
||||
def test_unregistering_device_view_handles_json_safe_error(self, loop,
|
||||
test_client):
|
||||
"""Test that the HTML unregister view handles JSON write errors."""
|
||||
mock_os.path.isfile.return_value = True
|
||||
hass = MagicMock()
|
||||
|
||||
config = {
|
||||
@@ -264,7 +279,9 @@ class TestHtml5Notify(object):
|
||||
'homeassistant.components.notify.html5.open', m, create=True
|
||||
):
|
||||
hass.config.path.return_value = 'file.conf'
|
||||
service = html5.get_service(hass, {})
|
||||
with patch('homeassistant.components.notify.html5.os.path.isfile',
|
||||
return_value=True):
|
||||
service = html5.get_service(hass, {})
|
||||
|
||||
assert service is not None
|
||||
|
||||
@@ -275,21 +292,23 @@ class TestHtml5Notify(object):
|
||||
assert view.json_path == hass.config.path.return_value
|
||||
assert view.registrations == config
|
||||
|
||||
builder = EnvironBuilder(method='DELETE', data=json.dumps({
|
||||
'subscription': SUBSCRIPTION_1['subscription'],
|
||||
}))
|
||||
Request = request_class()
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
with patch('homeassistant.components.notify.html5._save_config',
|
||||
return_value=False):
|
||||
resp = view.delete(Request(builder.get_environ()))
|
||||
resp = yield from client.delete(REGISTER_URL, data=json.dumps({
|
||||
'subscription': SUBSCRIPTION_1['subscription'],
|
||||
}))
|
||||
|
||||
assert resp.status_code == 500, resp.response
|
||||
assert resp.status == 500, resp.response
|
||||
assert view.registrations == config
|
||||
handle = m()
|
||||
assert handle.write.call_count == 0
|
||||
|
||||
def test_callback_view_no_jwt(self):
|
||||
@asyncio.coroutine
|
||||
def test_callback_view_no_jwt(self, loop, test_client):
|
||||
"""Test that the notification callback view works without JWT."""
|
||||
hass = MagicMock()
|
||||
|
||||
@@ -307,20 +326,20 @@ class TestHtml5Notify(object):
|
||||
|
||||
view = hass.mock_calls[2][1][0]
|
||||
|
||||
builder = EnvironBuilder(method='POST', data=json.dumps({
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
resp = yield from client.post(PUBLISH_URL, data=json.dumps({
|
||||
'type': 'push',
|
||||
'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
|
||||
}))
|
||||
Request = request_class()
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
|
||||
assert resp.status_code == 401, resp.response
|
||||
assert resp.status == 401, resp.response
|
||||
|
||||
@patch('homeassistant.components.notify.html5.os')
|
||||
@patch('pywebpush.WebPusher')
|
||||
def test_callback_view_with_jwt(self, mock_wp, mock_os):
|
||||
@asyncio.coroutine
|
||||
def test_callback_view_with_jwt(self, loop, test_client):
|
||||
"""Test that the notification callback view works with JWT."""
|
||||
mock_os.path.isfile.return_value = True
|
||||
hass = MagicMock()
|
||||
|
||||
data = {
|
||||
@@ -332,15 +351,18 @@ class TestHtml5Notify(object):
|
||||
'homeassistant.components.notify.html5.open', m, create=True
|
||||
):
|
||||
hass.config.path.return_value = 'file.conf'
|
||||
service = html5.get_service(hass, {'gcm_sender_id': '100'})
|
||||
with patch('homeassistant.components.notify.html5.os.path.isfile',
|
||||
return_value=True):
|
||||
service = html5.get_service(hass, {'gcm_sender_id': '100'})
|
||||
|
||||
assert service is not None
|
||||
|
||||
# assert hass.called
|
||||
assert len(hass.mock_calls) == 3
|
||||
|
||||
service.send_message('Hello', target=['device'],
|
||||
data={'icon': 'beer.png'})
|
||||
with patch('pywebpush.WebPusher') as mock_wp:
|
||||
service.send_message('Hello', target=['device'],
|
||||
data={'icon': 'beer.png'})
|
||||
|
||||
assert len(mock_wp.mock_calls) == 2
|
||||
|
||||
@@ -359,13 +381,14 @@ class TestHtml5Notify(object):
|
||||
|
||||
bearer_token = "Bearer {}".format(push_payload['data']['jwt'])
|
||||
|
||||
builder = EnvironBuilder(method='POST', data=json.dumps({
|
||||
app = web.Application(loop=loop)
|
||||
view.register(app.router)
|
||||
client = yield from test_client(app)
|
||||
|
||||
resp = yield from client.post(PUBLISH_URL, data=json.dumps({
|
||||
'type': 'push',
|
||||
}), headers={'Authorization': bearer_token})
|
||||
Request = request_class()
|
||||
resp = view.post(Request(builder.get_environ()))
|
||||
|
||||
assert resp.status_code == 200, resp.response
|
||||
returned = resp.response[0].decode('utf-8')
|
||||
expected = '{"event": "push", "status": "ok"}'
|
||||
assert json.loads(returned) == json.loads(expected)
|
||||
assert resp.status == 200
|
||||
body = yield from resp.json()
|
||||
assert body == {"event": "push", "status": "ok"}
|
||||
@@ -1,33 +1,29 @@
|
||||
"""The tests for the Yr sensor platform."""
|
||||
from datetime import datetime
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
|
||||
import requests_mock
|
||||
|
||||
from homeassistant.bootstrap import _setup_component
|
||||
import homeassistant.util.dt as dt_util
|
||||
from tests.common import get_test_home_assistant, load_fixture
|
||||
|
||||
|
||||
class TestSensorYr(TestCase):
|
||||
class TestSensorYr:
|
||||
"""Test the Yr sensor."""
|
||||
|
||||
def setUp(self):
|
||||
def setup_method(self):
|
||||
"""Setup things to be run when tests are started."""
|
||||
self.hass = get_test_home_assistant()
|
||||
self.hass.config.latitude = 32.87336
|
||||
self.hass.config.longitude = 117.22743
|
||||
|
||||
def tearDown(self):
|
||||
def teardown_method(self):
|
||||
"""Stop everything that was started."""
|
||||
self.hass.stop()
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_default_setup(self, m):
|
||||
def test_default_setup(self, requests_mock):
|
||||
"""Test the default setup."""
|
||||
m.get('http://api.yr.no/weatherapi/locationforecast/1.9/',
|
||||
text=load_fixture('yr.no.json'))
|
||||
requests_mock.get('http://api.yr.no/weatherapi/locationforecast/1.9/',
|
||||
text=load_fixture('yr.no.json'))
|
||||
now = datetime(2016, 6, 9, 1, tzinfo=dt_util.UTC)
|
||||
|
||||
with patch('homeassistant.components.sensor.yr.dt_util.utcnow',
|
||||
@@ -42,11 +38,10 @@ class TestSensorYr(TestCase):
|
||||
assert state.state.isnumeric()
|
||||
assert state.attributes.get('unit_of_measurement') is None
|
||||
|
||||
@requests_mock.Mocker()
|
||||
def test_custom_setup(self, m):
|
||||
def test_custom_setup(self, requests_mock):
|
||||
"""Test a custom setup."""
|
||||
m.get('http://api.yr.no/weatherapi/locationforecast/1.9/',
|
||||
text=load_fixture('yr.no.json'))
|
||||
requests_mock.get('http://api.yr.no/weatherapi/locationforecast/1.9/',
|
||||
text=load_fixture('yr.no.json'))
|
||||
now = datetime(2016, 6, 9, 1, tzinfo=dt_util.UTC)
|
||||
|
||||
with patch('homeassistant.components.sensor.yr.dt_util.utcnow',
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""The tests for the Home Assistant API component."""
|
||||
# pylint: disable=protected-access,too-many-public-methods
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from aiohttp import web
|
||||
import requests
|
||||
|
||||
from homeassistant import bootstrap, const
|
||||
@@ -243,20 +245,18 @@ class TestAPI(unittest.TestCase):
|
||||
|
||||
def test_api_get_error_log(self):
|
||||
"""Test the return of the error log."""
|
||||
test_string = 'Test String°'.encode('UTF-8')
|
||||
test_string = 'Test String°'
|
||||
|
||||
# Can't use read_data with wsgiserver in Python 3.4.2. Due to a
|
||||
# bug in read_data, it can't handle byte types ('Type str doesn't
|
||||
# support the buffer API'), but wsgiserver requires byte types
|
||||
# ('WSGI Applications must yield bytes'). So just mock our own
|
||||
# read method.
|
||||
m_open = Mock(return_value=Mock(
|
||||
read=Mock(side_effect=[test_string]))
|
||||
)
|
||||
with patch('homeassistant.components.http.open', m_open, create=True):
|
||||
@asyncio.coroutine
|
||||
def mock_send():
|
||||
"""Mock file send."""
|
||||
return web.Response(text=test_string)
|
||||
|
||||
with patch('homeassistant.components.http.HomeAssistantView.file',
|
||||
Mock(return_value=mock_send())):
|
||||
req = requests.get(_url(const.URL_API_ERROR_LOG),
|
||||
headers=HA_HEADERS)
|
||||
self.assertEqual(test_string, req.text.encode('UTF-8'))
|
||||
self.assertEqual(test_string, req.text)
|
||||
self.assertIsNone(req.headers.get('expires'))
|
||||
|
||||
def test_api_get_event_listeners(self):
|
||||
|
||||
@@ -34,12 +34,12 @@ def setUpModule(): # pylint: disable=invalid-name
|
||||
hass.bus.listen('test_event', lambda _: _)
|
||||
hass.states.set('test.test', 'a_state')
|
||||
|
||||
bootstrap.setup_component(
|
||||
assert bootstrap.setup_component(
|
||||
hass, http.DOMAIN,
|
||||
{http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD,
|
||||
http.CONF_SERVER_PORT: SERVER_PORT}})
|
||||
|
||||
bootstrap.setup_component(hass, 'frontend')
|
||||
assert bootstrap.setup_component(hass, 'frontend')
|
||||
|
||||
hass.start()
|
||||
time.sleep(0.05)
|
||||
@@ -71,7 +71,7 @@ class TestFrontend(unittest.TestCase):
|
||||
|
||||
self.assertIsNotNone(frontendjs)
|
||||
|
||||
req = requests.head(_url(frontendjs.groups(0)[0]))
|
||||
req = requests.get(_url(frontendjs.groups(0)[0]))
|
||||
|
||||
self.assertEqual(200, req.status_code)
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def setUpModule():
|
||||
|
||||
bootstrap.setup_component(hass, 'api')
|
||||
|
||||
hass.wsgi.trusted_networks = [
|
||||
hass.http.trusted_networks = [
|
||||
ip_network(trusted_network)
|
||||
for trusted_network in TRUSTED_NETWORKS]
|
||||
|
||||
@@ -159,12 +159,9 @@ class TestHttp:
|
||||
headers={const.HTTP_HEADER_ORIGIN: HTTP_BASE_URL})
|
||||
|
||||
allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
|
||||
allow_headers = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS
|
||||
all_allow_headers = ', '.join(const.ALLOWED_CORS_HEADERS)
|
||||
|
||||
assert req.status_code == 200
|
||||
assert req.headers.get(allow_origin) == HTTP_BASE_URL
|
||||
assert req.headers.get(allow_headers) == all_allow_headers
|
||||
|
||||
def test_cors_allowed_with_password_in_header(self):
|
||||
"""Test cross origin resource sharing with password in header."""
|
||||
@@ -175,12 +172,9 @@ class TestHttp:
|
||||
req = requests.get(_url(const.URL_API), headers=headers)
|
||||
|
||||
allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
|
||||
allow_headers = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS
|
||||
all_allow_headers = ', '.join(const.ALLOWED_CORS_HEADERS)
|
||||
|
||||
assert req.status_code == 200
|
||||
assert req.headers.get(allow_origin) == HTTP_BASE_URL
|
||||
assert req.headers.get(allow_headers) == all_allow_headers
|
||||
|
||||
def test_cors_denied_without_origin_header(self):
|
||||
"""Test cross origin resource sharing with password in header."""
|
||||
@@ -207,8 +201,8 @@ class TestHttp:
|
||||
|
||||
allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
|
||||
allow_headers = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS
|
||||
all_allow_headers = ', '.join(const.ALLOWED_CORS_HEADERS)
|
||||
|
||||
assert req.status_code == 200
|
||||
assert req.headers.get(allow_origin) == HTTP_BASE_URL
|
||||
assert req.headers.get(allow_headers) == all_allow_headers
|
||||
assert req.headers.get(allow_headers) == \
|
||||
const.HTTP_HEADER_HA_AUTH.upper()
|
||||
@@ -1,6 +1,7 @@
|
||||
"""The tests for the InfluxDB component."""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
from unittest.mock import patch
|
||||
|
||||
import influxdb as influx_client
|
||||
|
||||
@@ -60,6 +61,8 @@ class TestInfluxDB(unittest.TestCase):
|
||||
|
||||
assert setup_component(self.hass, influxdb.DOMAIN, config)
|
||||
|
||||
@patch('homeassistant.components.persistent_notification.create',
|
||||
mock.MagicMock())
|
||||
def test_setup_missing_password(self, mock_client):
|
||||
"""Test the setup with existing username and missing password."""
|
||||
config = {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Setup some common test helper things."""
|
||||
import functools
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
import requests_mock as _requests_mock
|
||||
|
||||
from homeassistant import util
|
||||
from homeassistant.util import location
|
||||
|
||||
from .common import async_test_home_assistant
|
||||
from .test_util.aiohttp import mock_aiohttp_client
|
||||
|
||||
logging.basicConfig()
|
||||
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
|
||||
|
||||
|
||||
def test_real(func):
|
||||
"""Force a function to require a keyword _test_real to be passed in."""
|
||||
@functools.wraps(func)
|
||||
def guard_func(*args, **kwargs):
|
||||
real = kwargs.pop('_test_real', None)
|
||||
|
||||
if not real:
|
||||
raise Exception('Forgot to mock or pass "_test_real=True" to %s',
|
||||
func.__name__)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return guard_func
|
||||
|
||||
# Guard a few functions that would make network connections
|
||||
location.detect_location_info = test_real(location.detect_location_info)
|
||||
location.elevation = test_real(location.elevation)
|
||||
util.get_local_ip = lambda: '127.0.0.1'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hass(loop):
|
||||
"""Fixture to provide a test instance of HASS."""
|
||||
hass = loop.run_until_complete(async_test_home_assistant(loop))
|
||||
|
||||
yield hass
|
||||
|
||||
loop.run_until_complete(hass.async_stop())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def requests_mock():
|
||||
"""Fixture to provide a requests mocker."""
|
||||
with _requests_mock.mock() as m:
|
||||
yield m
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def aioclient_mock():
|
||||
"""Fixture to mock aioclient calls."""
|
||||
with mock_aiohttp_client() as mock_session:
|
||||
yield mock_session
|
||||
+37
-25
@@ -1,4 +1,5 @@
|
||||
"""Test state helpers."""
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -20,6 +21,42 @@ from homeassistant.components.sun import (STATE_ABOVE_HORIZON,
|
||||
from tests.common import get_test_home_assistant, mock_service
|
||||
|
||||
|
||||
def test_async_track_states(event_loop):
|
||||
"""Test AsyncTrackStates context manager."""
|
||||
hass = get_test_home_assistant()
|
||||
|
||||
try:
|
||||
point1 = dt_util.utcnow()
|
||||
point2 = point1 + timedelta(seconds=5)
|
||||
point3 = point2 + timedelta(seconds=5)
|
||||
|
||||
@asyncio.coroutine
|
||||
@patch('homeassistant.core.dt_util.utcnow')
|
||||
def run_test(mock_utcnow):
|
||||
"""Run the test."""
|
||||
mock_utcnow.return_value = point2
|
||||
|
||||
with state.AsyncTrackStates(hass) as states:
|
||||
mock_utcnow.return_value = point1
|
||||
hass.states.set('light.test', 'on')
|
||||
|
||||
mock_utcnow.return_value = point2
|
||||
hass.states.set('light.test2', 'on')
|
||||
state2 = hass.states.get('light.test2')
|
||||
|
||||
mock_utcnow.return_value = point3
|
||||
hass.states.set('light.test3', 'on')
|
||||
state3 = hass.states.get('light.test3')
|
||||
|
||||
assert [state2, state3] == \
|
||||
sorted(states, key=lambda state: state.entity_id)
|
||||
|
||||
event_loop.run_until_complete(run_test())
|
||||
|
||||
finally:
|
||||
hass.stop()
|
||||
|
||||
|
||||
class TestStateHelpers(unittest.TestCase):
|
||||
"""Test the Home Assistant event helpers."""
|
||||
|
||||
@@ -54,31 +91,6 @@ class TestStateHelpers(unittest.TestCase):
|
||||
[state2, state3],
|
||||
state.get_changed_since([state1, state2, state3], point2))
|
||||
|
||||
def test_track_states(self):
|
||||
"""Test tracking of states."""
|
||||
point1 = dt_util.utcnow()
|
||||
point2 = point1 + timedelta(seconds=5)
|
||||
point3 = point2 + timedelta(seconds=5)
|
||||
|
||||
with patch('homeassistant.core.dt_util.utcnow') as mock_utcnow:
|
||||
mock_utcnow.return_value = point2
|
||||
|
||||
with state.TrackStates(self.hass) as states:
|
||||
mock_utcnow.return_value = point1
|
||||
self.hass.states.set('light.test', 'on')
|
||||
|
||||
mock_utcnow.return_value = point2
|
||||
self.hass.states.set('light.test2', 'on')
|
||||
state2 = self.hass.states.get('light.test2')
|
||||
|
||||
mock_utcnow.return_value = point3
|
||||
self.hass.states.set('light.test3', 'on')
|
||||
state3 = self.hass.states.get('light.test3')
|
||||
|
||||
self.assertEqual(
|
||||
sorted([state2, state3], key=lambda state: state.entity_id),
|
||||
sorted(states, key=lambda state: state.entity_id))
|
||||
|
||||
def test_reproduce_with_no_entity(self):
|
||||
"""Test reproduce_state with no entity."""
|
||||
calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Aiohttp test utils."""
|
||||
import asyncio
|
||||
from contextlib import contextmanager
|
||||
import functools
|
||||
import json as _json
|
||||
from unittest import mock
|
||||
|
||||
|
||||
class AiohttpClientMocker:
|
||||
"""Mock Aiohttp client requests."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the request mocker."""
|
||||
self._mocks = []
|
||||
self.mock_calls = []
|
||||
|
||||
def request(self, method, url, *,
|
||||
status=200,
|
||||
text=None,
|
||||
content=None,
|
||||
json=None):
|
||||
"""Mock a request."""
|
||||
if json:
|
||||
text = _json.dumps(json)
|
||||
if text:
|
||||
content = text.encode('utf-8')
|
||||
if content is None:
|
||||
content = b''
|
||||
|
||||
self._mocks.append(AiohttpClientMockResponse(
|
||||
method, url, status, content))
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
"""Register a mock get request."""
|
||||
self.request('get', *args, **kwargs)
|
||||
|
||||
def put(self, *args, **kwargs):
|
||||
"""Register a mock put request."""
|
||||
self.request('put', *args, **kwargs)
|
||||
|
||||
def post(self, *args, **kwargs):
|
||||
"""Register a mock post request."""
|
||||
self.request('post', *args, **kwargs)
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
"""Register a mock delete request."""
|
||||
self.request('delete', *args, **kwargs)
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
"""Register a mock options request."""
|
||||
self.request('options', *args, **kwargs)
|
||||
|
||||
@property
|
||||
def call_count(self):
|
||||
"""Number of requests made."""
|
||||
return len(self.mock_calls)
|
||||
|
||||
@asyncio.coroutine
|
||||
def match_request(self, method, url):
|
||||
"""Match a request against pre-registered requests."""
|
||||
for response in self._mocks:
|
||||
if response.match_request(method, url):
|
||||
self.mock_calls.append((method, url))
|
||||
return response
|
||||
|
||||
assert False, "No mock registered for {} {}".format(method.upper(),
|
||||
url)
|
||||
|
||||
|
||||
class AiohttpClientMockResponse:
|
||||
"""Mock Aiohttp client response."""
|
||||
|
||||
def __init__(self, method, url, status, response):
|
||||
"""Initialize a fake response."""
|
||||
self.method = method
|
||||
self.url = url
|
||||
self.status = status
|
||||
self.response = response
|
||||
|
||||
def match_request(self, method, url):
|
||||
"""Test if response answers request."""
|
||||
return method == self.method and url == self.url
|
||||
|
||||
@asyncio.coroutine
|
||||
def read(self):
|
||||
"""Return mock response."""
|
||||
return self.response
|
||||
|
||||
@asyncio.coroutine
|
||||
def text(self, encoding='utf-8'):
|
||||
"""Return mock response as a string."""
|
||||
return self.response.decode(encoding)
|
||||
|
||||
@asyncio.coroutine
|
||||
def release(self):
|
||||
"""Mock release."""
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mock_aiohttp_client():
|
||||
"""Context manager to mock aiohttp client."""
|
||||
mocker = AiohttpClientMocker()
|
||||
|
||||
with mock.patch('aiohttp.ClientSession') as mock_session:
|
||||
instance = mock_session()
|
||||
|
||||
for method in ('get', 'post', 'put', 'options', 'delete'):
|
||||
setattr(instance, method,
|
||||
functools.partial(mocker.match_request, method))
|
||||
|
||||
yield mocker
|
||||
Reference in new issue
Block a user