Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

notify.html5: use new json save and load functions #10416

Merged
merged 3 commits into from
Nov 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 10 additions & 31 deletions homeassistant/components/notify/html5.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
import datetime
import json
import logging
import os
import time
import uuid

from aiohttp.hdrs import AUTHORIZATION
import voluptuous as vol
from voluptuous.humanize import humanize_error

from homeassistant.util.json import load_json, save_json
from homeassistant.exceptions import HomeAssistantError
from homeassistant.components.frontend import add_manifest_json_key
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.notify import (
Expand Down Expand Up @@ -125,21 +126,11 @@ def get_service(hass, config, discovery_info=None):

def _load_config(filename):
"""Load configuration."""
if not os.path.isfile(filename):
return {}

try:
with open(filename, 'r') as fdesc:
inp = fdesc.read()

# In case empty file
if not inp:
return {}

return json.loads(inp)
except (IOError, ValueError) as error:
_LOGGER.error("Reading config file %s failed: %s", filename, error)
return None
return load_json(filename)
except HomeAssistantError:
pass
return {}


class JSONBytesDecoder(json.JSONEncoder):
Expand All @@ -153,18 +144,6 @@ def default(self, obj):
return json.JSONEncoder.default(self, obj)


def _save_config(filename, config):
"""Save configuration."""
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(
config, cls=JSONBytesDecoder, indent=4, sort_keys=True))
except (IOError, TypeError) as error:
_LOGGER.error("Saving configuration file failed: %s", error)
return False
return True


class HTML5PushRegistrationView(HomeAssistantView):
"""Accepts push registrations from a browser."""

Expand Down Expand Up @@ -194,7 +173,7 @@ def post(self, request):

self.registrations[name] = data

if not _save_config(self.json_path, self.registrations):
if not save_json(self.json_path, self.registrations):
return self.json_message(
'Error saving registration.', HTTP_INTERNAL_SERVER_ERROR)

Expand Down Expand Up @@ -223,7 +202,7 @@ def delete(self, request):

reg = self.registrations.pop(found)

if not _save_config(self.json_path, self.registrations):
if not save_json(self.json_path, self.registrations):
self.registrations[found] = reg
return self.json_message(
'Error saving registration.', HTTP_INTERNAL_SERVER_ERROR)
Expand Down Expand Up @@ -411,8 +390,8 @@ def send_message(self, message="", **kwargs):
if response.status_code == 410:
_LOGGER.info("Notification channel has expired")
reg = self.registrations.pop(target)
if not _save_config(self.registrations_json_path,
self.registrations):
if not save_json(self.registrations_json_path,
self.registrations):
self.registrations[target] = reg
_LOGGER.error("Error saving registration")
else:
Expand Down
71 changes: 30 additions & 41 deletions tests/components/notify/test_html5.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,24 +57,13 @@ def test_get_service_with_no_json(self):

m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
service = html5.get_service(hass, {})

assert service is not None

def test_get_service_with_bad_json(self):
"""Test ."""
hass = MagicMock()

m = mock_open(read_data='I am not JSON')
with patch(
'homeassistant.components.notify.html5.open', m, create=True
):
service = html5.get_service(hass, {})

assert service is None

@patch('pywebpush.WebPusher')
def test_sending_message(self, mock_wp):
"""Test sending message."""
Expand All @@ -86,7 +75,8 @@ def test_sending_message(self, mock_wp):

m = mock_open(read_data=json.dumps(data))
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
service = html5.get_service(hass, {'gcm_sender_id': '100'})

Expand Down Expand Up @@ -120,7 +110,8 @@ def test_registering_new_device_view(self, loop, test_client):

m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
service = html5.get_service(hass, {})
Expand Down Expand Up @@ -158,7 +149,8 @@ def test_registering_new_device_expiration_view(self, loop, test_client):

m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
service = html5.get_service(hass, {})
Expand Down Expand Up @@ -193,7 +185,8 @@ def test_registering_new_device_validation(self, loop, test_client):

m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
service = html5.get_service(hass, {})
Expand Down Expand Up @@ -222,7 +215,7 @@ def test_registering_new_device_validation(self, loop, test_client):
}))
assert resp.status == 400

with patch('homeassistant.components.notify.html5._save_config',
with patch('homeassistant.components.notify.html5.save_json',
return_value=False):
# resp = view.post(Request(builder.get_environ()))
resp = yield from client.post(REGISTER_URL, data=json.dumps({
Expand All @@ -243,14 +236,12 @@ def test_unregistering_device_view(self, loop, test_client):
}

m = mock_open(read_data=json.dumps(config))

with patch('homeassistant.components.notify.html5.open', m,
create=True):
with patch(
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'

with patch('homeassistant.components.notify.html5.os.path.isfile',
return_value=True):
service = html5.get_service(hass, {})
service = html5.get_service(hass, {})

assert service is not None

Expand Down Expand Up @@ -291,12 +282,11 @@ def test_unregister_device_view_handle_unknown_subscription(

m = mock_open(read_data=json.dumps(config))
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
with patch('homeassistant.components.notify.html5.os.path.isfile',
return_value=True):
service = html5.get_service(hass, {})
service = html5.get_service(hass, {})

assert service is not None

Expand Down Expand Up @@ -324,7 +314,7 @@ def test_unregister_device_view_handle_unknown_subscription(

@asyncio.coroutine
def test_unregistering_device_view_handles_json_safe_error(
self, loop, test_client):
self, loop, test_client):
"""Test that the HTML unregister view handles JSON write errors."""
hass = MagicMock()

Expand All @@ -335,12 +325,11 @@ def test_unregistering_device_view_handles_json_safe_error(

m = mock_open(read_data=json.dumps(config))
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
with patch('homeassistant.components.notify.html5.os.path.isfile',
return_value=True):
service = html5.get_service(hass, {})
service = html5.get_service(hass, {})

assert service is not None

Expand All @@ -357,7 +346,7 @@ def test_unregistering_device_view_handles_json_safe_error(
client = yield from test_client(app)
hass.http.is_banned_ip.return_value = False

with patch('homeassistant.components.notify.html5._save_config',
with patch('homeassistant.components.notify.html5.save_json',
return_value=False):
resp = yield from client.delete(REGISTER_URL, data=json.dumps({
'subscription': SUBSCRIPTION_1['subscription'],
Expand All @@ -375,7 +364,8 @@ def test_callback_view_no_jwt(self, loop, test_client):

m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
service = html5.get_service(hass, {})
Expand Down Expand Up @@ -406,17 +396,16 @@ def test_callback_view_with_jwt(self, loop, test_client):
hass = MagicMock()

data = {
'device': SUBSCRIPTION_1,
'device': SUBSCRIPTION_1
}

m = mock_open(read_data=json.dumps(data))
with patch(
'homeassistant.components.notify.html5.open', m, create=True
'homeassistant.util.json.open',
m, create=True
):
hass.config.path.return_value = 'file.conf'
with patch('homeassistant.components.notify.html5.os.path.isfile',
return_value=True):
service = html5.get_service(hass, {'gcm_sender_id': '100'})
service = html5.get_service(hass, {'gcm_sender_id': '100'})

assert service is not None

Expand Down