def test_registering_existing_device_fails_view(self, loop, test_client): """Test sub. is not updated when registering existing device fails.""" hass = MagicMock() expected = { 'unnamed device': SUBSCRIPTION_1, } hass.config.path.return_value = CONFIG_FILE html5.get_service(hass, {}) view = hass.mock_calls[1][1][0] hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False yield from client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1)) hass.async_add_job.side_effect = HomeAssistantError() resp = yield from client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) content = yield from resp.text() assert resp.status == 500, content assert view.registrations == expected
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( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == {} 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)) 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_view(self): """Test that the HTML view works.""" hass = MagicMock() m = mock_open() with patch( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] 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())) expected = { 'unnamed device': SUBSCRIPTION_1, } assert resp.status_code == 200, resp.response assert view.registrations == expected handle = m() assert json.loads(handle.write.call_args[0][0]) == expected
def test_unregister_device_view_handle_unknown_subscription(self, loop, test_client): """Test that the HTML unregister view handles unknown subscriptions.""" hass = MagicMock() config = {"some device": SUBSCRIPTION_1, "other device": SUBSCRIPTION_2} m = mock_open(read_data=json.dumps(config)) with patch("homeassistant.components.notify.html5.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, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.delete( REGISTER_URL, data=json.dumps({"subscription": SUBSCRIPTION_3["subscription"]}) ) assert resp.status == 200, resp.response assert view.registrations == config handle = m() assert handle.write.call_count == 0
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
def test_registering_new_device_expiration_view(self, loop, test_client): """Test that the HTML view works.""" hass = MagicMock() expected = { 'unnamed device': SUBSCRIPTION_4, } hass.config.path.return_value = CONFIG_FILE service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == {} hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) content = yield from resp.text() assert resp.status == 200, content assert view.registrations == expected hass.async_add_job.assert_called_with(save_json, CONFIG_FILE, expected)
def test_sending_message(self, mock_wp): """Test sending message.""" hass = MagicMock() data = {'device': SUBSCRIPTION_1} with tempfile.NamedTemporaryFile() as fp: fp.write(json.dumps(data).encode('utf-8')) fp.flush() hass.config.path.return_value = fp.name 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) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription'] # Call to send payload = json.loads(mock_wp.mock_calls[1][1][0]) assert payload['body'] == 'Hello' assert payload['icon'] == 'beer.png'
def test_unregistering_device_view_handles_unknown_subscription(self): """Test that the HTML unregister view handles unknown subscriptions.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } with tempfile.NamedTemporaryFile() as fp: hass.config.path.return_value = fp.name fp.write(json.dumps(config).encode('utf-8')) fp.flush() service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == fp.name assert view.registrations == config builder = EnvironBuilder(method='DELETE', 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 view.registrations == config with open(fp.name) as fpp: assert json.load(fpp) == config
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
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'
def test_callback_view_no_jwt(self): """Test that the notification callback view works without JWT.""" hass = MagicMock() with tempfile.NamedTemporaryFile() as fp: hass.config.path.return_value = fp.name fp.close() service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[2][1][0] builder = EnvironBuilder(method='POST', 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
def test_callback_view_no_jwt(self): """Test that the notification callback view works without JWT.""" hass = MagicMock() m = mock_open() with patch( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[2][1][0] builder = EnvironBuilder(method='POST', 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
def test_registering_new_device_view(self): """Test that the HTML view works.""" hass = MagicMock() with tempfile.NamedTemporaryFile() as fp: hass.config.path.return_value = fp.name fp.close() service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == fp.name assert view.registrations == {} builder = EnvironBuilder(method='POST', data=json.dumps(SUBSCRIPTION_1)) Request = request_class() resp = view.post(Request(builder.get_environ())) expected = { 'unnamed device': SUBSCRIPTION_1, } assert resp.status_code == 200, resp.response assert view.registrations == expected with open(fp.name) as fpp: assert json.load(fpp) == expected
def test_registering_new_device_view(self): """Test that the HTML view works.""" hass = MagicMock() m = mock_open() with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] 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())) expected = { 'unnamed device': SUBSCRIPTION_1, } assert resp.status_code == 200, resp.response assert view.registrations == expected handle = m() assert json.loads(handle.write.call_args[0][0]) == expected
def test_sending_message(self, mock_wp): """Test sending message.""" hass = MagicMock() data = { 'device': SUBSCRIPTION_1 } with tempfile.NamedTemporaryFile() as fp: fp.write(json.dumps(data).encode('utf-8')) fp.flush() hass.config.path.return_value = fp.name 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) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription'] # Call to send payload = json.loads(mock_wp.mock_calls[1][1][0]) assert payload['body'] == 'Hello' assert payload['icon'] == 'beer.png'
def test_callback_view_no_jwt(self, loop, test_client): """Test that the notification callback view works without JWT.""" hass = MagicMock() m = mock_open() with patch( 'homeassistant.util.json.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[2][1][0] hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(PUBLISH_URL, data=json.dumps({ 'type': 'push', 'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72' })) assert resp.status == 401, resp.response
def test_callback_view_no_jwt(self): """Test that the notification callback view works without JWT.""" hass = MagicMock() m = mock_open() with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[2][1][0] builder = EnvironBuilder(method='POST', 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
def test_registering_new_device_expiration_view(self, loop, test_client): """Test that the HTML view works.""" hass = MagicMock() expected = { 'unnamed device': SUBSCRIPTION_4, } m = mock_open() with patch('homeassistant.util.json.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == {} hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4)) 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_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'}) print(mock_wp.mock_calls) 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'
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.components.notify.html5.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) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1['subscription'] # Call to send payload = json.loads(mock_wp.mock_calls[1][1][0]) assert payload['body'] == 'Hello' assert payload['icon'] == 'beer.png'
def test_callback_view_no_jwt(self, loop, test_client): """Test that the notification callback view works without JWT.""" hass = MagicMock() m = mock_open() with patch('homeassistant.util.json.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[2][1][0] hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post( PUBLISH_URL, data=json.dumps({ 'type': 'push', 'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72' })) assert resp.status == 401, resp.response
def test_callback_view_with_jwt(self, loop, test_client): """Test that the notification callback view works with JWT.""" hass = MagicMock() data = { 'device': SUBSCRIPTION_1, } m = mock_open(read_data=json.dumps(data)) with patch('homeassistant.components.notify.html5.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'}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 with patch('pywebpush.WebPusher') as mock_wp: service.send_message('Hello', target=['device'], data={'icon': 'beer.png'}) assert len(mock_wp.mock_calls) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == \ SUBSCRIPTION_1['subscription'] # 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' view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload['data']['jwt']) 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}) assert resp.status == 200 body = yield from resp.json() assert body == {"event": "push", "status": "ok"}
def test_callback_view_with_jwt(self, loop, test_client): """Test that the notification callback view works with JWT.""" hass = MagicMock() data = { 'device': SUBSCRIPTION_1, } m = mock_open(read_data=json.dumps(data)) with patch( 'homeassistant.components.notify.html5.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'}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 with patch('pywebpush.WebPusher') as mock_wp: service.send_message('Hello', target=['device'], 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 push_payload = json.loads(mock_wp.mock_calls[1][1][0]) assert push_payload['body'] == 'Hello' assert push_payload['icon'] == 'beer.png' view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload['data']['jwt']) hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(PUBLISH_URL, data=json.dumps({ 'type': 'push', }), headers={'Authorization': bearer_token}) assert resp.status == 200 body = yield from resp.json() assert body == {"event": "push", "status": "ok"}
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
def test_get_service_with_no_json(self): """Test empty json file.""" hass = MagicMock() with tempfile.NamedTemporaryFile() as fp: hass.config.path.return_value = fp.name service = html5.get_service(hass, {}) assert service is not None
def test_get_service_with_no_json(self): """Test empty json file.""" hass = MagicMock() m = mock_open() with patch("homeassistant.components.notify.html5.open", m, create=True): service = html5.get_service(hass, {}) assert service is not None
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
def test_callback_view_with_jwt(self, loop, test_client): """Test that the notification callback view works with JWT.""" hass = MagicMock() data = {'device': SUBSCRIPTION_1} m = mock_open(read_data=json.dumps(data)) with patch('homeassistant.util.json.open', m, create=True): hass.config.path.return_value = CONFIG_FILE service = html5.get_service(hass, {'gcm_sender_id': '100'}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 with patch('pywebpush.WebPusher') as mock_wp: service.send_message('Hello', target=['device'], 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 push_payload = json.loads(mock_wp.mock_calls[1][1][0]) assert push_payload['body'] == 'Hello' assert push_payload['icon'] == 'beer.png' view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload['data']['jwt']) hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post( PUBLISH_URL, data=json.dumps({ 'type': 'push', }), headers={AUTHORIZATION: bearer_token}) assert resp.status == 200 body = yield from resp.json() assert body == {"event": "push", "status": "ok"}
def test_callback_view_with_jwt(self, mock_wp, mock_os): """Test that the notification callback view works with JWT.""" mock_os.path.isfile.return_value = True hass = MagicMock() data = { 'device': SUBSCRIPTION_1, } m = mock_open(read_data=json.dumps(data)) with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' 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'}) assert len(mock_wp.mock_calls) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == \ SUBSCRIPTION_1['subscription'] # 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' view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload['data']['jwt']) builder = EnvironBuilder(method='POST', 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)
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
def test_get_service_with_bad_json(self): """Test .""" hass = MagicMock() with tempfile.NamedTemporaryFile() as fp: fp.write('I am not JSON'.encode('utf-8')) fp.flush() hass.config.path.return_value = fp.name service = html5.get_service(hass, {}) assert service is None
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
def test_registering_new_device_validation(self, loop, test_client): """Test various errors when registering a new device.""" hass = MagicMock() m = mock_open() with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(REGISTER_URL, data=json.dumps({ 'browser': 'invalid browser', 'subscription': 'sub info', })) assert resp.status == 400 resp = yield from client.post(REGISTER_URL, data=json.dumps({ 'browser': 'chrome', })) assert resp.status == 400 with patch('homeassistant.components.notify.html5._save_config', return_value=False): # resp = view.post(Request(builder.get_environ())) resp = yield from client.post(REGISTER_URL, data=json.dumps({ 'browser': 'chrome', 'subscription': 'sub info', })) assert resp.status == 400
def test_callback_view_with_jwt(self, mock_wp, mock_os): """Test that the notification callback view works with JWT.""" mock_os.path.isfile.return_value = True hass = MagicMock() data = { 'device': SUBSCRIPTION_1, } m = mock_open(read_data=json.dumps(data)) with patch( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' 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'}) assert len(mock_wp.mock_calls) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == \ SUBSCRIPTION_1['subscription'] # 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' view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload['data']['jwt']) builder = EnvironBuilder(method='POST', 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)
def test_callback_view_with_jwt(self, loop, test_client): """Test that the notification callback view works with JWT.""" hass = MagicMock() data = {"device": SUBSCRIPTION_1} m = mock_open(read_data=json.dumps(data)) with patch("homeassistant.components.notify.html5.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"}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 with patch("pywebpush.WebPusher") as mock_wp: service.send_message("Hello", target=["device"], data={"icon": "beer.png"}) assert len(mock_wp.mock_calls) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"] # 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" view = hass.mock_calls[2][1][0] view.registrations = data bearer_token = "Bearer {}".format(push_payload["data"]["jwt"]) hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post( PUBLISH_URL, data=json.dumps({"type": "push"}), headers={"Authorization": bearer_token} ) assert resp.status == 200 body = yield from resp.json() assert body == {"event": "push", "status": "ok"}
def test_registering_new_device_validation(self): """Test various errors when registering a new device.""" hass = MagicMock() m = mock_open() with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] Request = request_class() builder = EnvironBuilder(method='POST', data=json.dumps({ 'browser': 'invalid browser', 'subscription': 'sub info', })) resp = view.post(Request(builder.get_environ())) assert resp.status_code == 400, resp.response builder = EnvironBuilder(method='POST', data=json.dumps({ 'browser': 'chrome', })) resp = view.post(Request(builder.get_environ())) assert resp.status_code == 400, resp.response 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
def test_unregistering_device_view_handles_json_safe_error( self, loop, test_client): """Test that the HTML unregister view handles JSON write errors.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch('homeassistant.components.notify.html5.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, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False with patch('homeassistant.components.notify.html5._save_config', return_value=False): resp = yield from client.delete( REGISTER_URL, data=json.dumps({ 'subscription': SUBSCRIPTION_1['subscription'], })) assert resp.status == 500, resp.response assert view.registrations == config handle = m() assert handle.write.call_count == 0
def test_unregistering_device_view(self, loop, test_client): """Test that the HTML unregister view works.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch('homeassistant.components.notify.html5.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, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config 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'], })) config.pop('some device') assert resp.status == 200, resp.response assert view.registrations == config handle = m() assert json.loads(handle.write.call_args[0][0]) == config
def test_registering_new_device_validation(self, loop, test_client): """Test various errors when registering a new device.""" hass = MagicMock() m = mock_open() with patch( 'homeassistant.util.json.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.post(REGISTER_URL, data=json.dumps({ 'browser': 'invalid browser', 'subscription': 'sub info', })) assert resp.status == 400 resp = yield from 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 = view.post(Request(builder.get_environ())) resp = yield from client.post(REGISTER_URL, data=json.dumps({ 'browser': 'chrome', 'subscription': 'sub info', })) assert resp.status == 400
def test_unregistering_device_view_handles_json_safe_error(self, loop, test_client): """Test that the HTML unregister view handles JSON write errors.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch( 'homeassistant.components.notify.html5.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, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False with patch('homeassistant.components.notify.html5._save_config', return_value=False): resp = yield from client.delete(REGISTER_URL, data=json.dumps({ 'subscription': SUBSCRIPTION_1['subscription'], })) assert resp.status == 500, resp.response assert view.registrations == config handle = m() assert handle.write.call_count == 0
def test_unregistering_device_view(self, loop, test_client): """Test that the HTML unregister view works.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch( 'homeassistant.util.json.open', m, create=True ): hass.config.path.return_value = CONFIG_FILE service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.delete(REGISTER_URL, data=json.dumps({ 'subscription': SUBSCRIPTION_1['subscription'], })) config.pop('some device') assert resp.status == 200, resp.response assert view.registrations == config hass.async_add_job.assert_called_with(save_json, CONFIG_FILE, config)
def test_unregistering_device_view(self, loop, test_client): """Test that the HTML unregister view works.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch('homeassistant.util.json.open', m, create=True): hass.config.path.return_value = CONFIG_FILE service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == hass.config.path.return_value assert view.registrations == config hass.loop = loop app = mock_http_component_app(hass) view.register(app.router) client = yield from test_client(app) hass.http.is_banned_ip.return_value = False resp = yield from client.delete(REGISTER_URL, data=json.dumps({ 'subscription': SUBSCRIPTION_1['subscription'], })) config.pop('some device') assert resp.status == 200, resp.response assert view.registrations == config hass.async_add_job.assert_called_with(save_json, CONFIG_FILE, config)
def test_registering_new_device_validation(self): """Test various errors when registering a new device.""" hass = MagicMock() m = mock_open() with patch( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] Request = request_class() builder = EnvironBuilder(method='POST', data=json.dumps({ 'browser': 'invalid browser', 'subscription': 'sub info', })) resp = view.post(Request(builder.get_environ())) assert resp.status_code == 400, resp.response builder = EnvironBuilder(method='POST', data=json.dumps({ 'browser': 'chrome', })) resp = view.post(Request(builder.get_environ())) assert resp.status_code == 400, resp.response 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
def test_unregistering_device_view_handles_json_safe_error(self, mock_os): """Test that the HTML unregister view handles JSON write errors.""" mock_os.path.isfile.return_value = True hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch('homeassistant.components.notify.html5.open', m, create=True): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] 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() with patch('homeassistant.components.notify.html5._save_config', return_value=False): resp = view.delete(Request(builder.get_environ())) assert resp.status_code == 500, resp.response assert view.registrations == config handle = m() assert handle.write.call_count == 0
def test_unregistering_device_view_handles_json_safe_error(self, mock_os): """Test that the HTML unregister view handles JSON write errors.""" mock_os.path.isfile.return_value = True hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } m = mock_open(read_data=json.dumps(config)) with patch( 'homeassistant.components.notify.html5.open', m, create=True ): hass.config.path.return_value = 'file.conf' service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] 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() with patch('homeassistant.components.notify.html5._save_config', return_value=False): resp = view.delete(Request(builder.get_environ())) assert resp.status_code == 500, resp.response assert view.registrations == config handle = m() assert handle.write.call_count == 0
def test_unregistering_device_view_handles_json_safe_error(self): """Test that the HTML unregister view handles JSON write errors.""" hass = MagicMock() config = { 'some device': SUBSCRIPTION_1, 'other device': SUBSCRIPTION_2, } with tempfile.NamedTemporaryFile() as fp: hass.config.path.return_value = fp.name fp.write(json.dumps(config).encode('utf-8')) fp.flush() service = html5.get_service(hass, {}) assert service is not None # assert hass.called assert len(hass.mock_calls) == 3 view = hass.mock_calls[1][1][0] assert view.json_path == fp.name assert view.registrations == config builder = EnvironBuilder(method='DELETE', data=json.dumps({ 'subscription': SUBSCRIPTION_1['subscription'], })) Request = request_class() with patch('homeassistant.components.notify.html5._save_config', return_value=False): resp = view.delete(Request(builder.get_environ())) assert resp.status_code == 500, resp.response assert view.registrations == config with open(fp.name) as fpp: assert json.load(fpp) == config
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.components.notify.html5.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) == 2 # WebPusher constructor assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"] # Call to send payload = json.loads(mock_wp.mock_calls[1][1][0]) assert payload["body"] == "Hello" assert payload["icon"] == "beer.png"