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,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 = {
|
||||
|
||||
Reference in new issue
Block a user