Great migration notify (#22406)

* Move notify platforms into components

* Move notify tests

* Fix notify tests

* More fixes

* Update requirements

* Update .coveragerc

* Run gen reqs
This commit is contained in:
Robbie Trencheny authored and Paulus Schoutsen committed 2019-03-27 20:36:13 -07:00
1 parent 92457ca5ca
commit 7741ec4d5a
105 files changed
+653 -582

No files matched your search

-410
View File
@@ -1,410 +0,0 @@
"""The tests for the APNS component."""
import io
import unittest
from unittest.mock import Mock, patch, mock_open
from apns2.errors import Unregistered
import yaml
import homeassistant.components.notify as notify
from homeassistant.setup import setup_component
from homeassistant.components.notify import apns
from homeassistant.core import State
from tests.common import assert_setup_component, get_test_home_assistant
CONFIG = {
notify.DOMAIN: {
'platform': 'apns',
'name': 'test_app',
'topic': 'testapp.appname',
'cert_file': 'test_app.pem'
}
}
@patch('homeassistant.components.notify.apns.open', mock_open(), create=True)
class TestApns(unittest.TestCase):
"""Test the APNS component."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@patch('os.path.isfile', Mock(return_value=True))
@patch('os.access', Mock(return_value=True))
def _setup_notify(self):
assert isinstance(apns.load_yaml_config_file, Mock), \
'Found unmocked load_yaml'
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, CONFIG)
assert handle_config[notify.DOMAIN]
@patch('os.path.isfile', return_value=True)
@patch('os.access', return_value=True)
def test_apns_setup_full(self, mock_access, mock_isfile):
"""Test setup with all data."""
config = {
'notify': {
'platform': 'apns',
'name': 'test_app',
'sandbox': 'True',
'topic': 'testapp.appname',
'cert_file': 'test_app.pem'
}
}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
def test_apns_setup_missing_name(self):
"""Test setup with missing name."""
config = {
'notify': {
'platform': 'apns',
'topic': 'testapp.appname',
'cert_file': 'test_app.pem',
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
def test_apns_setup_missing_certificate(self):
"""Test setup with missing certificate."""
config = {
'notify': {
'platform': 'apns',
'name': 'test_app',
'topic': 'testapp.appname',
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
def test_apns_setup_missing_topic(self):
"""Test setup with missing topic."""
config = {
'notify': {
'platform': 'apns',
'name': 'test_app',
'cert_file': 'test_app.pem',
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
@patch('homeassistant.components.notify.apns._write_device')
def test_register_new_device(self, mock_write):
"""Test registering a new device with a name."""
yaml_file = {5678: {'name': 'test device 2'}}
written_devices = []
def fake_write(_out, device):
"""Fake write_device."""
written_devices.append(device)
mock_write.side_effect = fake_write
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', {
'push_id': '1234',
'name': 'test device'
}, blocking=True)
assert len(written_devices) == 1
assert written_devices[0].name == 'test device'
@patch('homeassistant.components.notify.apns._write_device')
def test_register_device_without_name(self, mock_write):
"""Test registering a without a name."""
yaml_file = {
1234: {
'name': 'test device 1',
'tracking_device_id': 'tracking123',
},
5678: {
'name': 'test device 2',
'tracking_device_id': 'tracking456',
},
}
written_devices = []
def fake_write(_out, device):
"""Fake write_device."""
written_devices.append(device)
mock_write.side_effect = fake_write
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', {
'push_id': '1234'
}, blocking=True)
devices = {dev.push_id: dev for dev in written_devices}
test_device = devices.get('1234')
assert test_device is not None
assert test_device.name is None
@patch('homeassistant.components.notify.apns._write_device')
def test_update_existing_device(self, mock_write):
"""Test updating an existing device."""
yaml_file = {
1234: {
'name': 'test device 1',
},
5678: {
'name': 'test device 2',
},
}
written_devices = []
def fake_write(_out, device):
"""Fake write_device."""
written_devices.append(device)
mock_write.side_effect = fake_write
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', {
'push_id': '1234',
'name': 'updated device 1'
}, blocking=True)
devices = {dev.push_id: dev for dev in written_devices}
test_device_1 = devices.get('1234')
test_device_2 = devices.get('5678')
assert test_device_1 is not None
assert test_device_2 is not None
assert 'updated device 1' == test_device_1.name
@patch('homeassistant.components.notify.apns._write_device')
def test_update_existing_device_with_tracking_id(self, mock_write):
"""Test updating an existing device that has a tracking id."""
yaml_file = {
1234: {
'name': 'test device 1',
'tracking_device_id': 'tracking123',
},
5678: {
'name': 'test device 2',
'tracking_device_id': 'tracking456',
},
}
written_devices = []
def fake_write(_out, device):
"""Fake write_device."""
written_devices.append(device)
mock_write.side_effect = fake_write
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', {
'push_id': '1234',
'name': 'updated device 1'
}, blocking=True)
devices = {dev.push_id: dev for dev in written_devices}
test_device_1 = devices.get('1234')
test_device_2 = devices.get('5678')
assert test_device_1 is not None
assert test_device_2 is not None
assert 'tracking123' == \
test_device_1.tracking_device_id
assert 'tracking456' == \
test_device_2.tracking_device_id
@patch('apns2.client.APNsClient')
def test_send(self, mock_client):
"""Test updating an existing device."""
send = mock_client.return_value.send_notification
yaml_file = {1234: {'name': 'test device 1'}}
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(
'notify', 'test_app',
{'message': 'Hello', 'data': {
'badge': 1,
'sound': 'test.mp3',
'category': 'testing'}},
blocking=True)
assert send.called
assert 1 == len(send.mock_calls)
target = send.mock_calls[0][1][0]
payload = send.mock_calls[0][1][1]
assert '1234' == target
assert 'Hello' == payload.alert
assert 1 == payload.badge
assert 'test.mp3' == payload.sound
assert 'testing' == payload.category
@patch('apns2.client.APNsClient')
def test_send_when_disabled(self, mock_client):
"""Test updating an existing device."""
send = mock_client.return_value.send_notification
yaml_file = {1234: {
'name': 'test device 1',
'disabled': True,
}}
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call(
'notify', 'test_app',
{'message': 'Hello', 'data': {
'badge': 1,
'sound': 'test.mp3',
'category': 'testing'}},
blocking=True)
assert not send.called
@patch('apns2.client.APNsClient')
def test_send_with_state(self, mock_client):
"""Test updating an existing device."""
send = mock_client.return_value.send_notification
yaml_file = {
1234: {
'name': 'test device 1',
'tracking_device_id': 'tracking123',
},
5678: {
'name': 'test device 2',
'tracking_device_id': 'tracking456',
},
}
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)), \
patch('os.path.isfile', Mock(return_value=True)):
notify_service = apns.ApnsNotificationService(
self.hass,
'test_app',
'testapp.appname',
False,
'test_app.pem'
)
notify_service.device_state_changed_listener(
'device_tracker.tracking456',
State('device_tracker.tracking456', None),
State('device_tracker.tracking456', 'home'))
notify_service.send_message(message='Hello', target='home')
assert send.called
assert 1 == len(send.mock_calls)
target = send.mock_calls[0][1][0]
payload = send.mock_calls[0][1][1]
assert '5678' == target
assert 'Hello' == payload.alert
@patch('apns2.client.APNsClient')
@patch('homeassistant.components.notify.apns._write_device')
def test_disable_when_unregistered(self, mock_write, mock_client):
"""Test disabling a device when it is unregistered."""
send = mock_client.return_value.send_notification
send.side_effect = Unregistered()
yaml_file = {
1234: {
'name': 'test device 1',
'tracking_device_id': 'tracking123',
},
5678: {
'name': 'test device 2',
'tracking_device_id': 'tracking456',
},
}
written_devices = []
def fake_write(_out, device):
"""Fake write_device."""
written_devices.append(device)
mock_write.side_effect = fake_write
with patch(
'homeassistant.components.notify.apns.load_yaml_config_file',
Mock(return_value=yaml_file)):
self._setup_notify()
assert self.hass.services.call('notify', 'test_app',
{'message': 'Hello'},
blocking=True)
devices = {dev.push_id: dev for dev in written_devices}
test_device_1 = devices.get('1234')
assert test_device_1 is not None
assert test_device_1.disabled is True
def test_write_device():
"""Test writing device."""
out = io.StringIO()
device = apns.ApnsDevice('123', 'name', 'track_id', True)
apns._write_device(out, device)
data = yaml.load(out.getvalue())
assert data == {
123: {
'name': 'name',
'tracking_device_id': 'track_id',
'disabled': True
},
}
@@ -1,83 +0,0 @@
"""The tests for the command line notification platform."""
import os
import tempfile
import unittest
from unittest.mock import patch
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify
from tests.common import assert_setup_component, get_test_home_assistant
class TestCommandLine(unittest.TestCase):
"""Test the command line notifications."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup(self):
"""Test setup."""
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, 'notify', {
'notify': {
'name': 'test',
'platform': 'command_line',
'command': 'echo $(cat); exit 1', }
})
assert handle_config[notify.DOMAIN]
def test_bad_config(self):
"""Test set up the platform with bad/missing configuration."""
config = {
notify.DOMAIN: {
'name': 'test',
'platform': 'command_line',
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
def test_command_line_output(self):
"""Test the command line output."""
with tempfile.TemporaryDirectory() as tempdirname:
filename = os.path.join(tempdirname, 'message.txt')
message = 'one, two, testing, testing'
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, {
'notify': {
'name': 'test',
'platform': 'command_line',
'command': 'echo $(cat) > {}'.format(filename)
}
})
assert handle_config[notify.DOMAIN]
assert self.hass.services.call(
'notify', 'test', {'message': message}, blocking=True)
with open(filename) as fil:
# the echo command adds a line break
assert fil.read() == "{}\n".format(message)
@patch('homeassistant.components.notify.command_line._LOGGER.error')
def test_error_for_none_zero_exit_code(self, mock_error):
"""Test if an error is logged for non zero exit codes."""
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, {
'notify': {
'name': 'test',
'platform': 'command_line',
'command': 'echo $(cat); exit 1'
}
})
assert handle_config[notify.DOMAIN]
assert self.hass.services.call('notify', 'test', {'message': 'error'},
blocking=True)
assert 1 == mock_error.call_count
-201
View File
@@ -1,201 +0,0 @@
"""The tests for the notify demo platform."""
import unittest
from unittest.mock import patch
import pytest
import voluptuous as vol
import homeassistant.components.notify as notify
from homeassistant.setup import setup_component
from homeassistant.components.notify import demo
from homeassistant.core import callback
from homeassistant.helpers import discovery, script
from tests.common import assert_setup_component, get_test_home_assistant
from tests.components.notify import common
CONFIG = {
notify.DOMAIN: {
'platform': 'demo'
}
}
class TestNotifyDemo(unittest.TestCase):
"""Test the demo notify."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.events = []
self.calls = []
@callback
def record_event(event):
"""Record event to send notification."""
self.events.append(event)
self.hass.bus.listen(demo.EVENT_NOTIFY, record_event)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def _setup_notify(self):
with assert_setup_component(1) as config:
assert setup_component(self.hass, notify.DOMAIN, CONFIG)
assert config[notify.DOMAIN]
def test_setup(self):
"""Test setup."""
self._setup_notify()
@patch('homeassistant.components.notify.demo.get_service', autospec=True)
def test_no_notify_service(self, mock_demo_get_service):
"""Test missing platform notify service instance."""
mock_demo_get_service.return_value = None
with self.assertLogs('homeassistant.components.notify',
level='ERROR') as log_handle:
self._setup_notify()
self.hass.block_till_done()
assert mock_demo_get_service.called
assert log_handle.output == \
['ERROR:homeassistant.components.notify:'
'Failed to initialize notification service demo']
@patch('homeassistant.components.notify.demo.get_service', autospec=True)
def test_discover_notify(self, mock_demo_get_service):
"""Test discovery of notify demo platform."""
assert notify.DOMAIN not in self.hass.config.components
discovery.load_platform(
self.hass, 'notify', 'demo', {'test_key': 'test_val'},
{'notify': {}})
self.hass.block_till_done()
assert notify.DOMAIN in self.hass.config.components
assert mock_demo_get_service.called
assert mock_demo_get_service.call_args[0] == (
self.hass, {}, {'test_key': 'test_val'})
@callback
def record_calls(self, *args):
"""Record calls."""
self.calls.append(args)
def test_sending_none_message(self):
"""Test send with None as message."""
self._setup_notify()
with pytest.raises(vol.Invalid):
common.send_message(self.hass, None)
self.hass.block_till_done()
assert len(self.events) == 0
def test_sending_templated_message(self):
"""Send a templated message."""
self._setup_notify()
self.hass.states.set('sensor.temperature', 10)
common.send_message(self.hass, '{{ states.sensor.temperature.state }}',
'{{ states.sensor.temperature.name }}')
self.hass.block_till_done()
last_event = self.events[-1]
assert last_event.data[notify.ATTR_TITLE] == 'temperature'
assert last_event.data[notify.ATTR_MESSAGE] == '10'
def test_method_forwards_correct_data(self):
"""Test that all data from the service gets forwarded to service."""
self._setup_notify()
common.send_message(self.hass, 'my message', 'my title',
{'hello': 'world'})
self.hass.block_till_done()
assert len(self.events) == 1
data = self.events[0].data
assert {
'message': 'my message',
'title': 'my title',
'data': {'hello': 'world'}
} == data
def test_calling_notify_from_script_loaded_from_yaml_without_title(self):
"""Test if we can call a notify from a script."""
self._setup_notify()
conf = {
'service': 'notify.notify',
'data': {
'data': {
'push': {
'sound':
'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'
}
}
},
'data_template': {'message': 'Test 123 {{ 2 + 2 }}\n'},
}
script.call_from_config(self.hass, conf)
self.hass.block_till_done()
assert len(self.events) == 1
assert {
'message': 'Test 123 4',
'data': {
'push': {
'sound':
'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'}}
} == self.events[0].data
def test_calling_notify_from_script_loaded_from_yaml_with_title(self):
"""Test if we can call a notify from a script."""
self._setup_notify()
conf = {
'service': 'notify.notify',
'data': {
'data': {
'push': {
'sound':
'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'
}
}
},
'data_template': {
'message': 'Test 123 {{ 2 + 2 }}\n',
'title': 'Test'
}
}
script.call_from_config(self.hass, conf)
self.hass.block_till_done()
assert len(self.events) == 1
assert {
'message': 'Test 123 4',
'title': 'Test',
'data': {
'push': {
'sound':
'US-EN-Morgan-Freeman-Roommate-Is-Arriving.wav'}}
} == self.events[0].data
def test_targets_are_services(self):
"""Test that all targets are exposed as individual services."""
self._setup_notify()
assert self.hass.services.has_service("notify", "demo") is not None
service = "demo_test_target_name"
assert self.hass.services.has_service("notify", service) is not None
def test_messages_to_targets_route(self):
"""Test message routing to specific target services."""
self._setup_notify()
self.hass.bus.listen_once("notify", self.record_calls)
self.hass.services.call("notify", "demo_test_target_name",
{'message': 'my message',
'title': 'my title',
'data': {'hello': 'world'}})
self.hass.block_till_done()
data = self.calls[0][0].data
assert {
'message': 'my message',
'target': ['test target id'],
'title': 'my title',
'data': {'hello': 'world'}
} == data
-129
View File
@@ -1,129 +0,0 @@
"""The test for the Facebook notify module."""
import unittest
import requests_mock
import homeassistant.components.notify.facebook as facebook
class TestFacebook(unittest.TestCase):
"""Tests for Facebook notification service."""
def setUp(self):
"""Set up test variables."""
access_token = "page-access-token"
self.facebook = facebook.FacebookNotificationService(access_token)
@requests_mock.Mocker()
def test_send_simple_message(self, mock):
"""Test sending a simple message with success."""
mock.register_uri(
requests_mock.POST,
facebook.BASE_URL,
status_code=200
)
message = "This is just a test"
target = ["+15555551234"]
self.facebook.send_message(message=message, target=target)
assert mock.called
assert mock.call_count == 1
expected_body = {
"recipient": {"phone_number": target[0]},
"message": {"text": message}
}
assert mock.last_request.json() == expected_body
expected_params = {"access_token": ["page-access-token"]}
assert mock.last_request.qs == expected_params
@requests_mock.Mocker()
def test_sending_multiple_messages(self, mock):
"""Test sending a message to multiple targets."""
mock.register_uri(
requests_mock.POST,
facebook.BASE_URL,
status_code=200
)
message = "This is just a test"
targets = ["+15555551234", "+15555551235"]
self.facebook.send_message(message=message, target=targets)
assert mock.called
assert mock.call_count == 2
for idx, target in enumerate(targets):
request = mock.request_history[idx]
expected_body = {
"recipient": {"phone_number": target},
"message": {"text": message}
}
assert request.json() == expected_body
expected_params = {"access_token": ["page-access-token"]}
assert request.qs == expected_params
@requests_mock.Mocker()
def test_send_message_attachment(self, mock):
"""Test sending a message with a remote attachment."""
mock.register_uri(
requests_mock.POST,
facebook.BASE_URL,
status_code=200
)
message = "This will be thrown away."
data = {
"attachment": {
"type": "image",
"payload": {"url": "http://www.example.com/image.jpg"}
}
}
target = ["+15555551234"]
self.facebook.send_message(message=message, data=data, target=target)
assert mock.called
assert mock.call_count == 1
expected_body = {
"recipient": {"phone_number": target[0]},
"message": data
}
assert mock.last_request.json() == expected_body
expected_params = {"access_token": ["page-access-token"]}
assert mock.last_request.qs == expected_params
@requests_mock.Mocker()
def test_send_targetless_message(self, mock):
"""Test sending a message without a target."""
mock.register_uri(
requests_mock.POST,
facebook.BASE_URL,
status_code=200
)
self.facebook.send_message(message="goin nowhere")
assert not mock.called
@requests_mock.Mocker()
def test_send_message_with_400(self, mock):
"""Test sending a message with a 400 from Facebook."""
mock.register_uri(
requests_mock.POST,
facebook.BASE_URL,
status_code=400,
json={
"error": {
"message": "Invalid OAuth access token.",
"type": "OAuthException",
"code": 190,
"fbtrace_id": "G4Da2pFp2Dp"
}
}
)
self.facebook.send_message(message="nope!", target=["+15555551234"])
assert mock.called
assert mock.call_count == 1
-89
View File
@@ -1,89 +0,0 @@
"""The tests for the notify file platform."""
import os
import unittest
from unittest.mock import call, mock_open, patch
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify
from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT)
import homeassistant.util.dt as dt_util
from tests.common import assert_setup_component, get_test_home_assistant
class TestNotifyFile(unittest.TestCase):
"""Test the file notify."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_bad_config(self):
"""Test set up the platform with bad/missing config."""
config = {
notify.DOMAIN: {
'name': 'test',
'platform': 'file',
},
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
def _test_notify_file(self, timestamp):
"""Test the notify file output."""
filename = 'mock_file'
message = 'one, two, testing, testing'
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, {
'notify': {
'name': 'test',
'platform': 'file',
'filename': filename,
'timestamp': timestamp,
}
})
assert handle_config[notify.DOMAIN]
m_open = mock_open()
with patch(
'homeassistant.components.notify.file.open',
m_open, create=True
), patch('homeassistant.components.notify.file.os.stat') as mock_st, \
patch('homeassistant.util.dt.utcnow',
return_value=dt_util.utcnow()):
mock_st.return_value.st_size = 0
title = '{} notifications (Log started: {})\n{}\n'.format(
ATTR_TITLE_DEFAULT,
dt_util.utcnow().isoformat(),
'-' * 80)
self.hass.services.call('notify', 'test', {'message': message},
blocking=True)
full_filename = os.path.join(self.hass.config.path(), filename)
assert m_open.call_count == 1
assert m_open.call_args == call(full_filename, 'a')
assert m_open.return_value.write.call_count == 2
if not timestamp:
assert m_open.return_value.write.call_args_list == \
[call(title), call('{}\n'.format(message))]
else:
assert m_open.return_value.write.call_args_list == \
[call(title), call('{} {}\n'.format(
dt_util.utcnow().isoformat(), message))]
def test_notify_file(self):
"""Test the notify file output without timestamp."""
self._test_notify_file(False)
def test_notify_file_timestamp(self):
"""Test the notify file output with timestamp."""
self._test_notify_file(True)
-76
View File
@@ -1,76 +0,0 @@
"""The tests for the notify.group platform."""
import unittest
from unittest.mock import MagicMock, patch
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify
from homeassistant.components.notify import group, demo
from homeassistant.util.async_ import run_coroutine_threadsafe
from tests.common import assert_setup_component, get_test_home_assistant
class TestNotifyGroup(unittest.TestCase):
"""Test the notify.group platform."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.events = []
self.service1 = demo.DemoNotificationService(self.hass)
self.service2 = demo.DemoNotificationService(self.hass)
self.service1.send_message = MagicMock(autospec=True)
self.service2.send_message = MagicMock(autospec=True)
def mock_get_service(hass, config, discovery_info=None):
if config['name'] == 'demo1':
return self.service1
return self.service2
with assert_setup_component(2), \
patch.object(demo, 'get_service', mock_get_service):
setup_component(self.hass, notify.DOMAIN, {
'notify': [{
'name': 'demo1',
'platform': 'demo'
}, {
'name': 'demo2',
'platform': 'demo'
}]
})
self.service = run_coroutine_threadsafe(
group.async_get_service(self.hass, {'services': [
{'service': 'demo1'},
{'service': 'demo2',
'data': {'target': 'unnamed device',
'data': {'test': 'message'}}}]}),
self.hass.loop
).result()
assert self.service is not None
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
def test_send_message_with_data(self):
"""Test sending a message with to a notify group."""
run_coroutine_threadsafe(
self.service.async_send_message(
'Hello', title='Test notification', data={'hello': 'world'}),
self.hass.loop).result()
self.hass.block_till_done()
assert self.service1.send_message.mock_calls[0][1][0] == 'Hello'
assert self.service1.send_message.mock_calls[0][2] == {
'title': 'Test notification',
'data': {'hello': 'world'}
}
assert self.service2.send_message.mock_calls[0][1][0] == 'Hello'
assert self.service2.send_message.mock_calls[0][2] == {
'target': ['unnamed device'],
'title': 'Test notification',
'data': {'hello': 'world', 'test': 'message'}
}
-78
View File
@@ -1,78 +0,0 @@
"""The tests for the Homematic notification platform."""
import unittest
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify_comp
from tests.common import assert_setup_component, get_test_home_assistant
class TestHomematicNotify(unittest.TestCase):
"""Test the Homematic notifications."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_full(self):
"""Test valid configuration."""
setup_component(self.hass, 'homematic', {
'homematic': {
'hosts': {
'ccu2': {
'host': '127.0.0.1'
}
}
}
})
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, 'notify', {
'notify': {
'name': 'test',
'platform': 'homematic',
'address': 'NEQXXXXXXX',
'channel': 2,
'param': 'SUBMIT',
'value': '1,1,108000,2',
'interface': 'my-interface'}
})
assert handle_config[notify_comp.DOMAIN]
def test_setup_without_optional(self):
"""Test valid configuration without optional."""
setup_component(self.hass, 'homematic', {
'homematic': {
'hosts': {
'ccu2': {
'host': '127.0.0.1'
}
}
}
})
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, 'notify', {
'notify': {
'name': 'test',
'platform': 'homematic',
'address': 'NEQXXXXXXX',
'channel': 2,
'param': 'SUBMIT',
'value': '1,1,108000,2'}
})
assert handle_config[notify_comp.DOMAIN]
def test_bad_config(self):
"""Test invalid configuration."""
config = {
notify_comp.DOMAIN: {
'name': 'test',
'platform': 'homematic'
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify_comp.DOMAIN, config)
assert not handle_config[notify_comp.DOMAIN]
-429
View File
@@ -1,429 +0,0 @@
"""Test HTML5 notify platform."""
import json
from unittest.mock import patch, MagicMock, mock_open
from aiohttp.hdrs import AUTHORIZATION
from homeassistant.setup import async_setup_component
from homeassistant.exceptions import HomeAssistantError
from homeassistant.components.notify import html5
CONFIG_FILE = 'file.conf'
SUBSCRIPTION_1 = {
'browser': 'chrome',
'subscription': {
'endpoint': 'https://googleapis.com',
'keys': {'auth': 'auth', 'p256dh': 'p256dh'}
},
}
SUBSCRIPTION_2 = {
'browser': 'firefox',
'subscription': {
'endpoint': 'https://example.com',
'keys': {
'auth': 'bla',
'p256dh': 'bla',
},
},
}
SUBSCRIPTION_3 = {
'browser': 'chrome',
'subscription': {
'endpoint': 'https://example.com/not_exist',
'keys': {
'auth': 'bla',
'p256dh': 'bla',
},
},
}
SUBSCRIPTION_4 = {
'browser': 'chrome',
'subscription': {
'endpoint': 'https://googleapis.com',
'expirationTime': None,
'keys': {'auth': 'auth', 'p256dh': 'p256dh'}
},
}
REGISTER_URL = '/api/notify.html5'
PUBLISH_URL = '/api/notify.html5/callback'
async def mock_client(hass, hass_client, registrations=None):
"""Create a test client for HTML5 views."""
if registrations is None:
registrations = {}
with patch('homeassistant.components.notify.html5._load_config',
return_value=registrations):
await async_setup_component(hass, 'notify', {
'notify': {
'platform': 'html5'
}
})
return await hass_client()
class TestHtml5Notify:
"""Tests for HTML5 notify platform."""
def test_get_service_with_no_json(self):
"""Test empty json file."""
hass = MagicMock()
m = mock_open()
with patch(
'homeassistant.util.json.open',
m, create=True
):
service = html5.get_service(hass, {})
assert service is not None
@patch('pywebpush.WebPusher')
def test_dismissing_message(self, mock_wp):
"""Test dismissing message."""
hass = MagicMock()
data = {
'device': SUBSCRIPTION_1
}
m = mock_open(read_data=json.dumps(data))
with patch(
'homeassistant.util.json.open',
m, create=True
):
service = html5.get_service(hass, {'gcm_sender_id': '100'})
assert service is not None
service.dismiss(target=['device', 'non_existing'],
data={'tag': 'test'})
assert len(mock_wp.mock_calls) == 3
# WebPusher constructor
assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription']
# Third mock_call checks the status_code of the response.
assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'
# Call to send
payload = json.loads(mock_wp.mock_calls[1][1][0])
assert payload['dismiss'] is True
assert payload['tag'] == 'test'
@patch('pywebpush.WebPusher')
def test_sending_message(self, mock_wp):
"""Test sending message."""
hass = MagicMock()
data = {
'device': SUBSCRIPTION_1
}
m = mock_open(read_data=json.dumps(data))
with patch(
'homeassistant.util.json.open',
m, create=True
):
service = html5.get_service(hass, {'gcm_sender_id': '100'})
assert service is not None
service.send_message('Hello', target=['device', 'non_existing'],
data={'icon': 'beer.png'})
assert len(mock_wp.mock_calls) == 3
# WebPusher constructor
assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription']
# Third mock_call checks the status_code of the response.
assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'
# Call to send
payload = json.loads(mock_wp.mock_calls[1][1][0])
assert payload['body'] == 'Hello'
assert payload['icon'] == 'beer.png'
@patch('pywebpush.WebPusher')
def test_gcm_key_include(self, mock_wp):
"""Test if the gcm_key is only included for GCM endpoints."""
hass = MagicMock()
data = {
'chrome': SUBSCRIPTION_1,
'firefox': SUBSCRIPTION_2
}
m = mock_open(read_data=json.dumps(data))
with patch('homeassistant.util.json.open', m, create=True):
service = html5.get_service(hass, {
'gcm_sender_id': '100',
'gcm_api_key': 'Y6i0JdZ0mj9LOaSI'
})
assert service is not None
service.send_message('Hello', target=['chrome', 'firefox'])
assert len(mock_wp.mock_calls) == 6
# WebPusher constructor
assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription']
assert mock_wp.mock_calls[3][1][0] == SUBSCRIPTION_2['subscription']
# Third mock_call checks the status_code of the response.
assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'
assert mock_wp.mock_calls[5][0] == '().send().status_code.__eq__'
# Get the keys passed to the WebPusher's send method
assert mock_wp.mock_calls[1][2]['gcm_key'] is not None
assert mock_wp.mock_calls[4][2]['gcm_key'] is None
async def test_registering_new_device_view(hass, hass_client):
"""Test that the HTML view works."""
client = await mock_client(hass, hass_client)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
assert resp.status == 200
assert len(mock_save.mock_calls) == 1
assert mock_save.mock_calls[0][1][1] == {
'unnamed device': SUBSCRIPTION_1,
}
async def test_registering_new_device_view_with_name(hass, hass_client):
"""Test that the HTML view works with name attribute."""
client = await mock_client(hass, hass_client)
SUB_WITH_NAME = SUBSCRIPTION_1.copy()
SUB_WITH_NAME['name'] = 'test device'
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))
assert resp.status == 200
assert len(mock_save.mock_calls) == 1
assert mock_save.mock_calls[0][1][1] == {
'test device': SUBSCRIPTION_1,
}
async def test_registering_new_device_expiration_view(hass, hass_client):
"""Test that the HTML view works."""
client = await mock_client(hass, hass_client)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200
assert mock_save.mock_calls[0][1][1] == {
'unnamed device': SUBSCRIPTION_4,
}
async def test_registering_new_device_fails_view(hass, hass_client):
"""Test subs. are not altered when registering a new device fails."""
registrations = {}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json',
side_effect=HomeAssistantError()):
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 500
assert registrations == {}
async def test_registering_existing_device_view(hass, hass_client):
"""Test subscription is updated when registering existing device."""
registrations = {}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200
assert mock_save.mock_calls[0][1][1] == {
'unnamed device': SUBSCRIPTION_4,
}
assert registrations == {
'unnamed device': SUBSCRIPTION_4,
}
async def test_registering_existing_device_view_with_name(hass, hass_client):
"""Test subscription is updated when reg'ing existing device with name."""
registrations = {}
client = await mock_client(hass, hass_client, registrations)
SUB_WITH_NAME = SUBSCRIPTION_1.copy()
SUB_WITH_NAME['name'] = 'test device'
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 200
assert mock_save.mock_calls[0][1][1] == {
'test device': SUBSCRIPTION_4,
}
assert registrations == {
'test device': SUBSCRIPTION_4,
}
async def test_registering_existing_device_fails_view(hass, hass_client):
"""Test sub. is not updated when registering existing device fails."""
registrations = {}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
mock_save.side_effect = HomeAssistantError
resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))
assert resp.status == 500
assert registrations == {
'unnamed device': SUBSCRIPTION_1,
}
async def test_registering_new_device_validation(hass, hass_client):
"""Test various errors when registering a new device."""
client = await mock_client(hass, hass_client)
resp = await client.post(REGISTER_URL, data=json.dumps({
'browser': 'invalid browser',
'subscription': 'sub info',
}))
assert resp.status == 400
resp = await client.post(REGISTER_URL, data=json.dumps({
'browser': 'chrome',
}))
assert resp.status == 400
with patch('homeassistant.components.notify.html5.save_json',
return_value=False):
resp = await client.post(REGISTER_URL, data=json.dumps({
'browser': 'chrome',
'subscription': 'sub info',
}))
assert resp.status == 400
async def test_unregistering_device_view(hass, hass_client):
"""Test that the HTML unregister view works."""
registrations = {
'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2,
}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.delete(REGISTER_URL, data=json.dumps({
'subscription': SUBSCRIPTION_1['subscription'],
}))
assert resp.status == 200
assert len(mock_save.mock_calls) == 1
assert registrations == {
'other device': SUBSCRIPTION_2
}
async def test_unregister_device_view_handle_unknown_subscription(
hass, hass_client):
"""Test that the HTML unregister view handles unknown subscriptions."""
registrations = {}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json') as mock_save:
resp = await client.delete(REGISTER_URL, data=json.dumps({
'subscription': SUBSCRIPTION_3['subscription']
}))
assert resp.status == 200, resp.response
assert registrations == {}
assert len(mock_save.mock_calls) == 0
async def test_unregistering_device_view_handles_save_error(
hass, hass_client):
"""Test that the HTML unregister view handles save errors."""
registrations = {
'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2,
}
client = await mock_client(hass, hass_client, registrations)
with patch('homeassistant.components.notify.html5.save_json',
side_effect=HomeAssistantError()):
resp = await client.delete(REGISTER_URL, data=json.dumps({
'subscription': SUBSCRIPTION_1['subscription'],
}))
assert resp.status == 500, resp.response
assert registrations == {
'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2,
}
async def test_callback_view_no_jwt(hass, hass_client):
"""Test that the notification callback view works without JWT."""
client = await mock_client(hass, hass_client)
resp = await client.post(PUBLISH_URL, data=json.dumps({
'type': 'push',
'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
}))
assert resp.status == 401
async def test_callback_view_with_jwt(hass, hass_client):
"""Test that the notification callback view works with JWT."""
registrations = {
'device': SUBSCRIPTION_1
}
client = await mock_client(hass, hass_client, registrations)
with patch('pywebpush.WebPusher') as mock_wp:
await hass.services.async_call('notify', 'notify', {
'message': 'Hello',
'target': ['device'],
'data': {'icon': 'beer.png'}
}, blocking=True)
assert len(mock_wp.mock_calls) == 3
# WebPusher constructor
assert mock_wp.mock_calls[0][1][0] == \
SUBSCRIPTION_1['subscription']
# Third mock_call checks the status_code of the response.
assert mock_wp.mock_calls[2][0] == '().send().status_code.__eq__'
# Call to send
push_payload = json.loads(mock_wp.mock_calls[1][1][0])
assert push_payload['body'] == 'Hello'
assert push_payload['icon'] == 'beer.png'
bearer_token = "Bearer {}".format(push_payload['data']['jwt'])
resp = await client.post(PUBLISH_URL, json={
'type': 'push',
}, headers={AUTHORIZATION: bearer_token})
assert resp.status == 200
body = await resp.json()
assert body == {"event": "push", "status": "ok"}
-243
View File
@@ -1,243 +0,0 @@
"""The tests for the pushbullet notification platform."""
import json
import unittest
from unittest.mock import patch
from pushbullet import PushBullet
import requests_mock
from homeassistant.setup import setup_component
import homeassistant.components.notify as notify
from tests.common import (
assert_setup_component, get_test_home_assistant, load_fixture)
class TestPushBullet(unittest.TestCase):
"""Tests the Pushbullet Component."""
def setUp(self):
"""Initialize values for this test case class."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that we started."""
self.hass.stop()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_config(self, mock__get_data):
"""Test setup."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
def test_pushbullet_config_bad(self):
"""Test set up the platform with bad/missing configuration."""
config = {
notify.DOMAIN: {
'platform': 'pushbullet',
}
}
with assert_setup_component(0) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert not handle_config[notify.DOMAIN]
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_default(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message'}
self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
assert mock.called
assert mock.call_count == 1
expected_body = {'body': 'Test Message',
'title': 'Test Title',
'type': 'note'}
assert mock.last_request.json() == expected_body
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_device(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message',
'target': ['device/DESKTOP']}
self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
assert mock.called
assert mock.call_count == 1
expected_body = {'body': 'Test Message',
'device_iden': 'identity1',
'title': 'Test Title',
'type': 'note'}
assert mock.last_request.json() == expected_body
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_devices(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message',
'target': ['device/DESKTOP', 'device/My iPhone']}
self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
assert mock.called
assert mock.call_count == 2
assert len(mock.request_history) == 2
expected_body = {'body': 'Test Message',
'device_iden': 'identity1',
'title': 'Test Title',
'type': 'note'}
assert mock.request_history[0].json() == expected_body
expected_body = {'body': 'Test Message',
'device_iden': 'identity2',
'title': 'Test Title',
'type': 'note'}
assert mock.request_history[1].json() == expected_body
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_email(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message',
'target': ['email/user@host.net']}
self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
assert mock.called
assert mock.call_count == 1
assert len(mock.request_history) == 1
expected_body = {'body': 'Test Message',
'email': 'user@host.net',
'title': 'Test Title',
'type': 'note'}
assert mock.request_history[0].json() == expected_body
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_mixed(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message',
'target': ['device/DESKTOP', 'email/user@host.net']}
self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
assert mock.called
assert mock.call_count == 2
assert len(mock.request_history) == 2
expected_body = {'body': 'Test Message',
'device_iden': 'identity1',
'title': 'Test Title',
'type': 'note'}
assert mock.request_history[0].json() == expected_body
expected_body = {'body': 'Test Message',
'email': 'user@host.net',
'title': 'Test Title',
'type': 'note'}
assert mock.request_history[1].json() == expected_body
@requests_mock.Mocker()
@patch.object(PushBullet, '_get_data',
return_value=json.loads(load_fixture(
'pushbullet_devices.json')))
def test_pushbullet_push_no_file(self, mock, mock__get_data):
"""Test pushbullet push to default target."""
config = {notify.DOMAIN: {'name': 'test',
'platform': 'pushbullet',
'api_key': 'MYFAKEKEY'}}
with assert_setup_component(1) as handle_config:
assert setup_component(self.hass, notify.DOMAIN, config)
assert handle_config[notify.DOMAIN]
mock.register_uri(
requests_mock.POST,
'https://api.pushbullet.com/v2/pushes',
status_code=200,
json={'mock_response': 'Ok'}
)
data = {'title': 'Test Title',
'message': 'Test Message',
'target': ['device/DESKTOP', 'device/My iPhone'],
'data': {'file': 'not_a_file'}}
assert not self.hass.services.call(notify.DOMAIN, 'test', data)
self.hass.block_till_done()
-77
View File
@@ -1,77 +0,0 @@
"""The tests for the notify smtp platform."""
import unittest
from unittest.mock import patch
from homeassistant.components.notify import smtp
from tests.common import get_test_home_assistant
import re
class MockSMTP(smtp.MailNotificationService):
"""Test SMTP object that doesn't need a working server."""
def _send_email(self, msg):
"""Just return string for testing."""
return msg.as_string()
class TestNotifySmtp(unittest.TestCase):
"""Test the smtp notify."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mailer = MockSMTP('localhost', 25, 5, 'test@test.com', 1,
'testuser', 'testpass',
['recip1@example.com', 'testrecip@test.com'],
'HomeAssistant', 0)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
@patch('email.utils.make_msgid', return_value='<mock@mock>')
def test_text_email(self, mock_make_msgid):
"""Test build of default text email behavior."""
msg = self.mailer.send_message('Test msg')
expected = ('^Content-Type: text/plain; charset="us-ascii"\n'
'MIME-Version: 1.0\n'
'Content-Transfer-Encoding: 7bit\n'
'Subject: Home Assistant\n'
'To: recip1@example.com,testrecip@test.com\n'
'From: HomeAssistant <test@test.com>\n'
'X-Mailer: HomeAssistant\n'
'Date: [^\n]+\n'
'Message-Id: <[^@]+@[^>]+>\n'
'\n'
'Test msg$')
assert re.search(expected, msg)
@patch('email.utils.make_msgid', return_value='<mock@mock>')
def test_mixed_email(self, mock_make_msgid):
"""Test build of mixed text email behavior."""
msg = self.mailer.send_message('Test msg',
data={'images': ['test.jpg']})
assert 'Content-Type: multipart/related' in msg
@patch('email.utils.make_msgid', return_value='<mock@mock>')
def test_html_email(self, mock_make_msgid):
"""Test build of html email behavior."""
html = '''
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"></head>
<body>
<div>
<h1>Intruder alert at apartment!!</h1>
</div>
<div>
<img alt="test.jpg" src="cid:test.jpg"/>
</div>
</body>
</html>'''
msg = self.mailer.send_message('Test msg',
data={'html': html,
'images': ['test.jpg']})
assert 'Content-Type: multipart/related' in msg
-208
View File
@@ -1,208 +0,0 @@
"""The tests for the notify yessssms platform."""
import unittest
import requests_mock
from homeassistant.components.notify import yessssms
class TestNotifyYesssSMS(unittest.TestCase):
"""Test the yessssms notify."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
login = "06641234567"
passwd = "testpasswd"
recipient = "06501234567"
self.yessssms = yessssms.YesssSMSNotificationService(
login, passwd, recipient)
@requests_mock.Mocker()
def test_login_error(self, mock):
"""Test login that fails."""
mock.register_uri(
requests_mock.POST,
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
status_code=200,
text="BlaBlaBla<strong>Login nicht erfolgreichBlaBla"
)
message = "Testing YesssSMS platform :)"
with self.assertLogs("homeassistant.components.notify",
level='ERROR'):
self.yessssms.send_message(message)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 1)
def test_empty_message_error(self):
"""Test for an empty SMS message error."""
message = ""
with self.assertLogs("homeassistant.components.notify",
level='ERROR'):
self.yessssms.send_message(message)
@requests_mock.Mocker()
def test_error_account_suspended(self, mock):
"""Test login that fails after multiple attempts."""
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
status_code=200,
text="BlaBlaBla<strong>Login nicht erfolgreichBlaBla"
)
message = "Testing YesssSMS platform :)"
with self.assertLogs("homeassistant.components.notify",
level='ERROR'):
self.yessssms.send_message(message)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 1)
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
status_code=200,
text="Wegen 3 ungültigen Login-Versuchen ist Ihr Account für "
"eine Stunde gesperrt."
)
message = "Testing YesssSMS platform :)"
with self.assertLogs("homeassistant.components.notify",
level='ERROR'):
self.yessssms.send_message(message)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 2)
def test_error_account_suspended_2(self):
"""Test login that fails after multiple attempts."""
message = "Testing YesssSMS platform :)"
# pylint: disable=protected-access
self.yessssms.yesss._suspended = True
with self.assertLogs("homeassistant.components.notify",
level='ERROR') as context:
self.yessssms.send_message(message)
self.assertIn("Account is suspended, cannot send SMS.",
context.output[0])
@requests_mock.Mocker()
def test_send_message(self, mock):
"""Test send message."""
message = "Testing YesssSMS platform :)"
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
status_code=302,
# pylint: disable=protected-access
headers={'location': self.yessssms.yesss._kontomanager}
)
# pylint: disable=protected-access
login = self.yessssms.yesss._logindata['login_rufnummer']
mock.register_uri(
'GET',
# pylint: disable=protected-access
self.yessssms.yesss._kontomanager,
status_code=200,
text="test..." + login + "</a>"
)
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._websms_url,
status_code=200,
text="<h1>Ihre SMS wurde erfolgreich verschickt!</h1>"
)
mock.register_uri(
'GET',
# pylint: disable=protected-access
self.yessssms.yesss._logout_url,
status_code=200,
)
with self.assertLogs("homeassistant.components.notify",
level='INFO') as context:
self.yessssms.send_message(message)
self.assertIn("SMS sent", context.output[0])
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 4)
self.assertIn(mock.last_request.scheme + "://" +
mock.last_request.hostname +
mock.last_request.path + "?" +
mock.last_request.query,
# pylint: disable=protected-access
self.yessssms.yesss._logout_url)
def test_no_recipient_error(self):
"""Test for missing/empty recipient."""
message = "Testing YesssSMS platform :)"
# pylint: disable=protected-access
self.yessssms._recipient = ""
with self.assertLogs("homeassistant.components.notify",
level='ERROR') as context:
self.yessssms.send_message(message)
self.assertIn("You need to provide a recipient for SMS notification",
context.output[0])
@requests_mock.Mocker()
def test_sms_sending_error(self, mock):
"""Test sms sending error."""
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
status_code=302,
# pylint: disable=protected-access
headers={'location': self.yessssms.yesss._kontomanager}
)
# pylint: disable=protected-access
login = self.yessssms.yesss._logindata['login_rufnummer']
mock.register_uri(
'GET',
# pylint: disable=protected-access
self.yessssms.yesss._kontomanager,
status_code=200,
text="test..." + login + "</a>"
)
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._websms_url,
status_code=500
)
message = "Testing YesssSMS platform :)"
with self.assertLogs("homeassistant.components.notify",
level='ERROR') as context:
self.yessssms.send_message(message)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 3)
self.assertIn("YesssSMS: error sending SMS", context.output[0])
@requests_mock.Mocker()
def test_connection_error(self, mock):
"""Test connection error."""
mock.register_uri(
'POST',
# pylint: disable=protected-access
self.yessssms.yesss._login_url,
exc=ConnectionError
)
message = "Testing YesssSMS platform :)"
with self.assertLogs("homeassistant.components.notify",
level='ERROR') as context:
self.yessssms.send_message(message)
self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 1)
self.assertIn("unable to connect", context.output[0])