Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -21,14 +21,14 @@ def registry(hass):
|
||||
async def create_registrations(authed_api_client):
|
||||
"""Return two new registrations."""
|
||||
enc_reg = await authed_api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER
|
||||
"/api/mobile_app/registrations", json=REGISTER
|
||||
)
|
||||
|
||||
assert enc_reg.status == 201
|
||||
enc_reg_json = await enc_reg.json()
|
||||
|
||||
clear_reg = await authed_api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER_CLEARTEXT
|
||||
"/api/mobile_app/registrations", json=REGISTER_CLEARTEXT
|
||||
)
|
||||
|
||||
assert clear_reg.status == 201
|
||||
@@ -56,5 +56,5 @@ async def authed_api_client(hass, hass_client):
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_ws(hass):
|
||||
"""Configure the websocket_api component."""
|
||||
assert await async_setup_component(hass, 'websocket_api', {})
|
||||
assert await async_setup_component(hass, "websocket_api", {})
|
||||
await hass.async_block_till_done()
|
||||
@@ -1,65 +1,50 @@
|
||||
"""Constants for mobile_app tests."""
|
||||
CALL_SERVICE = {
|
||||
'type': 'call_service',
|
||||
'data': {
|
||||
'domain': 'test',
|
||||
'service': 'mobile_app',
|
||||
'service_data': {
|
||||
'foo': 'bar'
|
||||
}
|
||||
}
|
||||
"type": "call_service",
|
||||
"data": {"domain": "test", "service": "mobile_app", "service_data": {"foo": "bar"}},
|
||||
}
|
||||
|
||||
FIRE_EVENT = {
|
||||
'type': 'fire_event',
|
||||
'data': {
|
||||
'event_type': 'test_event',
|
||||
'event_data': {
|
||||
'hello': 'yo world'
|
||||
}
|
||||
}
|
||||
"type": "fire_event",
|
||||
"data": {"event_type": "test_event", "event_data": {"hello": "yo world"}},
|
||||
}
|
||||
|
||||
REGISTER = {
|
||||
'app_data': {'foo': 'bar'},
|
||||
'app_id': 'io.homeassistant.mobile_app_test',
|
||||
'app_name': 'Mobile App Tests',
|
||||
'app_version': '1.0.0',
|
||||
'device_name': 'Test 1',
|
||||
'manufacturer': 'mobile_app',
|
||||
'model': 'Test',
|
||||
'os_name': 'Linux',
|
||||
'os_version': '1.0',
|
||||
'supports_encryption': True
|
||||
"app_data": {"foo": "bar"},
|
||||
"app_id": "io.homeassistant.mobile_app_test",
|
||||
"app_name": "Mobile App Tests",
|
||||
"app_version": "1.0.0",
|
||||
"device_name": "Test 1",
|
||||
"manufacturer": "mobile_app",
|
||||
"model": "Test",
|
||||
"os_name": "Linux",
|
||||
"os_version": "1.0",
|
||||
"supports_encryption": True,
|
||||
}
|
||||
|
||||
REGISTER_CLEARTEXT = {
|
||||
'app_data': {'foo': 'bar'},
|
||||
'app_id': 'io.homeassistant.mobile_app_test',
|
||||
'app_name': 'Mobile App Tests',
|
||||
'app_version': '1.0.0',
|
||||
'device_name': 'Test 1',
|
||||
'manufacturer': 'mobile_app',
|
||||
'model': 'Test',
|
||||
'os_name': 'Linux',
|
||||
'os_version': '1.0',
|
||||
'supports_encryption': False
|
||||
"app_data": {"foo": "bar"},
|
||||
"app_id": "io.homeassistant.mobile_app_test",
|
||||
"app_name": "Mobile App Tests",
|
||||
"app_version": "1.0.0",
|
||||
"device_name": "Test 1",
|
||||
"manufacturer": "mobile_app",
|
||||
"model": "Test",
|
||||
"os_name": "Linux",
|
||||
"os_version": "1.0",
|
||||
"supports_encryption": False,
|
||||
}
|
||||
|
||||
RENDER_TEMPLATE = {
|
||||
'type': 'render_template',
|
||||
'data': {
|
||||
'one': {
|
||||
'template': 'Hello world'
|
||||
}
|
||||
}
|
||||
"type": "render_template",
|
||||
"data": {"one": {"template": "Hello world"}},
|
||||
}
|
||||
|
||||
UPDATE = {
|
||||
'app_data': {'foo': 'bar'},
|
||||
'app_version': '2.0.0',
|
||||
'device_name': 'Test 1',
|
||||
'manufacturer': 'mobile_app',
|
||||
'model': 'Test',
|
||||
'os_version': '1.0'
|
||||
"app_data": {"foo": "bar"},
|
||||
"app_version": "2.0.0",
|
||||
"device_name": "Test 1",
|
||||
"manufacturer": "mobile_app",
|
||||
"model": "Test",
|
||||
"os_version": "1.0",
|
||||
}
|
||||
@@ -4,113 +4,111 @@
|
||||
async def test_sending_location(hass, create_registrations, webhook_client):
|
||||
"""Test sending a location via a webhook."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json={
|
||||
'type': 'update_location',
|
||||
'data': {
|
||||
'gps': [10, 20],
|
||||
'gps_accuracy': 30,
|
||||
'battery': 40,
|
||||
'altitude': 50,
|
||||
'course': 60,
|
||||
'speed': 70,
|
||||
'vertical_accuracy': 80,
|
||||
'location_name': 'bar',
|
||||
}
|
||||
}
|
||||
"type": "update_location",
|
||||
"data": {
|
||||
"gps": [10, 20],
|
||||
"gps_accuracy": 30,
|
||||
"battery": 40,
|
||||
"altitude": 50,
|
||||
"course": 60,
|
||||
"speed": 70,
|
||||
"vertical_accuracy": 80,
|
||||
"location_name": "bar",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get('device_tracker.test_1_2')
|
||||
state = hass.states.get("device_tracker.test_1_2")
|
||||
assert state is not None
|
||||
assert state.name == 'Test 1'
|
||||
assert state.state == 'bar'
|
||||
assert state.attributes['source_type'] == 'gps'
|
||||
assert state.attributes['latitude'] == 10
|
||||
assert state.attributes['longitude'] == 20
|
||||
assert state.attributes['gps_accuracy'] == 30
|
||||
assert state.attributes['battery_level'] == 40
|
||||
assert state.attributes['altitude'] == 50
|
||||
assert state.attributes['course'] == 60
|
||||
assert state.attributes['speed'] == 70
|
||||
assert state.attributes['vertical_accuracy'] == 80
|
||||
assert state.name == "Test 1"
|
||||
assert state.state == "bar"
|
||||
assert state.attributes["source_type"] == "gps"
|
||||
assert state.attributes["latitude"] == 10
|
||||
assert state.attributes["longitude"] == 20
|
||||
assert state.attributes["gps_accuracy"] == 30
|
||||
assert state.attributes["battery_level"] == 40
|
||||
assert state.attributes["altitude"] == 50
|
||||
assert state.attributes["course"] == 60
|
||||
assert state.attributes["speed"] == 70
|
||||
assert state.attributes["vertical_accuracy"] == 80
|
||||
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json={
|
||||
'type': 'update_location',
|
||||
'data': {
|
||||
'gps': [1, 2],
|
||||
'gps_accuracy': 3,
|
||||
'battery': 4,
|
||||
'altitude': 5,
|
||||
'course': 6,
|
||||
'speed': 7,
|
||||
'vertical_accuracy': 8,
|
||||
}
|
||||
}
|
||||
"type": "update_location",
|
||||
"data": {
|
||||
"gps": [1, 2],
|
||||
"gps_accuracy": 3,
|
||||
"battery": 4,
|
||||
"altitude": 5,
|
||||
"course": 6,
|
||||
"speed": 7,
|
||||
"vertical_accuracy": 8,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get('device_tracker.test_1_2')
|
||||
state = hass.states.get("device_tracker.test_1_2")
|
||||
assert state is not None
|
||||
assert state.state == 'not_home'
|
||||
assert state.attributes['source_type'] == 'gps'
|
||||
assert state.attributes['latitude'] == 1
|
||||
assert state.attributes['longitude'] == 2
|
||||
assert state.attributes['gps_accuracy'] == 3
|
||||
assert state.attributes['battery_level'] == 4
|
||||
assert state.attributes['altitude'] == 5
|
||||
assert state.attributes['course'] == 6
|
||||
assert state.attributes['speed'] == 7
|
||||
assert state.attributes['vertical_accuracy'] == 8
|
||||
assert state.state == "not_home"
|
||||
assert state.attributes["source_type"] == "gps"
|
||||
assert state.attributes["latitude"] == 1
|
||||
assert state.attributes["longitude"] == 2
|
||||
assert state.attributes["gps_accuracy"] == 3
|
||||
assert state.attributes["battery_level"] == 4
|
||||
assert state.attributes["altitude"] == 5
|
||||
assert state.attributes["course"] == 6
|
||||
assert state.attributes["speed"] == 7
|
||||
assert state.attributes["vertical_accuracy"] == 8
|
||||
|
||||
|
||||
async def test_restoring_location(hass, create_registrations, webhook_client):
|
||||
"""Test sending a location via a webhook."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json={
|
||||
'type': 'update_location',
|
||||
'data': {
|
||||
'gps': [10, 20],
|
||||
'gps_accuracy': 30,
|
||||
'battery': 40,
|
||||
'altitude': 50,
|
||||
'course': 60,
|
||||
'speed': 70,
|
||||
'vertical_accuracy': 80,
|
||||
'location_name': 'bar',
|
||||
}
|
||||
}
|
||||
"type": "update_location",
|
||||
"data": {
|
||||
"gps": [10, 20],
|
||||
"gps_accuracy": 30,
|
||||
"battery": 40,
|
||||
"altitude": 50,
|
||||
"course": 60,
|
||||
"speed": 70,
|
||||
"vertical_accuracy": 80,
|
||||
"location_name": "bar",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
await hass.async_block_till_done()
|
||||
state_1 = hass.states.get('device_tracker.test_1_2')
|
||||
state_1 = hass.states.get("device_tracker.test_1_2")
|
||||
assert state_1 is not None
|
||||
|
||||
config_entry = hass.config_entries.async_entries('mobile_app')[1]
|
||||
config_entry = hass.config_entries.async_entries("mobile_app")[1]
|
||||
|
||||
# mobile app doesn't support unloading, so we just reload device tracker
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry,
|
||||
'device_tracker')
|
||||
await hass.config_entries.async_forward_entry_setup(config_entry,
|
||||
'device_tracker')
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "device_tracker")
|
||||
await hass.config_entries.async_forward_entry_setup(config_entry, "device_tracker")
|
||||
|
||||
state_2 = hass.states.get('device_tracker.test_1_2')
|
||||
state_2 = hass.states.get("device_tracker.test_1_2")
|
||||
assert state_2 is not None
|
||||
|
||||
assert state_1 is not state_2
|
||||
assert state_2.name == 'Test 1'
|
||||
assert state_2.attributes['source_type'] == 'gps'
|
||||
assert state_2.attributes['latitude'] == 10
|
||||
assert state_2.attributes['longitude'] == 20
|
||||
assert state_2.attributes['gps_accuracy'] == 30
|
||||
assert state_2.attributes['battery_level'] == 40
|
||||
assert state_2.attributes['altitude'] == 50
|
||||
assert state_2.attributes['course'] == 60
|
||||
assert state_2.attributes['speed'] == 70
|
||||
assert state_2.attributes['vertical_accuracy'] == 80
|
||||
assert state_2.name == "Test 1"
|
||||
assert state_2.attributes["source_type"] == "gps"
|
||||
assert state_2.attributes["latitude"] == 10
|
||||
assert state_2.attributes["longitude"] == 20
|
||||
assert state_2.attributes["gps_accuracy"] == 30
|
||||
assert state_2.attributes["battery_level"] == 40
|
||||
assert state_2.attributes["altitude"] == 50
|
||||
assert state_2.attributes["course"] == 60
|
||||
assert state_2.attributes["speed"] == 70
|
||||
assert state_2.attributes["vertical_accuracy"] == 80
|
||||
@@ -5,114 +5,108 @@ import logging
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def test_sensor(hass, create_registrations, webhook_client): # noqa: F401, F811, E501
|
||||
async def test_sensor(
|
||||
hass, create_registrations, webhook_client
|
||||
): # noqa: F401, F811, E501
|
||||
"""Test that sensors can be registered and updated."""
|
||||
webhook_id = create_registrations[1]['webhook_id']
|
||||
webhook_url = '/api/webhook/{}'.format(webhook_id)
|
||||
webhook_id = create_registrations[1]["webhook_id"]
|
||||
webhook_url = "/api/webhook/{}".format(webhook_id)
|
||||
|
||||
reg_resp = await webhook_client.post(
|
||||
webhook_url,
|
||||
json={
|
||||
'type': 'register_sensor',
|
||||
'data': {
|
||||
'attributes': {
|
||||
'foo': 'bar'
|
||||
},
|
||||
'device_class': 'battery',
|
||||
'icon': 'mdi:battery',
|
||||
'name': 'Battery State',
|
||||
'state': 100,
|
||||
'type': 'sensor',
|
||||
'unique_id': 'battery_state',
|
||||
'unit_of_measurement': '%'
|
||||
}
|
||||
}
|
||||
"type": "register_sensor",
|
||||
"data": {
|
||||
"attributes": {"foo": "bar"},
|
||||
"device_class": "battery",
|
||||
"icon": "mdi:battery",
|
||||
"name": "Battery State",
|
||||
"state": 100,
|
||||
"type": "sensor",
|
||||
"unique_id": "battery_state",
|
||||
"unit_of_measurement": "%",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert reg_resp.status == 201
|
||||
|
||||
json = await reg_resp.json()
|
||||
assert json == {'success': True}
|
||||
assert json == {"success": True}
|
||||
await hass.async_block_till_done()
|
||||
|
||||
entity = hass.states.get('sensor.battery_state')
|
||||
entity = hass.states.get("sensor.battery_state")
|
||||
assert entity is not None
|
||||
|
||||
assert entity.attributes['device_class'] == 'battery'
|
||||
assert entity.attributes['icon'] == 'mdi:battery'
|
||||
assert entity.attributes['unit_of_measurement'] == '%'
|
||||
assert entity.attributes['foo'] == 'bar'
|
||||
assert entity.domain == 'sensor'
|
||||
assert entity.name == 'Battery State'
|
||||
assert entity.state == '100'
|
||||
assert entity.attributes["device_class"] == "battery"
|
||||
assert entity.attributes["icon"] == "mdi:battery"
|
||||
assert entity.attributes["unit_of_measurement"] == "%"
|
||||
assert entity.attributes["foo"] == "bar"
|
||||
assert entity.domain == "sensor"
|
||||
assert entity.name == "Battery State"
|
||||
assert entity.state == "100"
|
||||
|
||||
update_resp = await webhook_client.post(
|
||||
webhook_url,
|
||||
json={
|
||||
'type': 'update_sensor_states',
|
||||
'data': [
|
||||
"type": "update_sensor_states",
|
||||
"data": [
|
||||
{
|
||||
'icon': 'mdi:battery-unknown',
|
||||
'state': 123,
|
||||
'type': 'sensor',
|
||||
'unique_id': 'battery_state'
|
||||
"icon": "mdi:battery-unknown",
|
||||
"state": 123,
|
||||
"type": "sensor",
|
||||
"unique_id": "battery_state",
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert update_resp.status == 200
|
||||
|
||||
updated_entity = hass.states.get('sensor.battery_state')
|
||||
assert updated_entity.state == '123'
|
||||
updated_entity = hass.states.get("sensor.battery_state")
|
||||
assert updated_entity.state == "123"
|
||||
|
||||
|
||||
async def test_sensor_must_register(hass, create_registrations, # noqa: F401, F811, E501
|
||||
webhook_client): # noqa: F401, F811, E501
|
||||
async def test_sensor_must_register(
|
||||
hass, create_registrations, webhook_client # noqa: F401, F811, E501
|
||||
): # noqa: F401, F811, E501
|
||||
"""Test that sensors must be registered before updating."""
|
||||
webhook_id = create_registrations[1]['webhook_id']
|
||||
webhook_url = '/api/webhook/{}'.format(webhook_id)
|
||||
webhook_id = create_registrations[1]["webhook_id"]
|
||||
webhook_url = "/api/webhook/{}".format(webhook_id)
|
||||
resp = await webhook_client.post(
|
||||
webhook_url,
|
||||
json={
|
||||
'type': 'update_sensor_states',
|
||||
'data': [
|
||||
{
|
||||
'state': 123,
|
||||
'type': 'sensor',
|
||||
'unique_id': 'battery_state'
|
||||
}
|
||||
]
|
||||
}
|
||||
"type": "update_sensor_states",
|
||||
"data": [{"state": 123, "type": "sensor", "unique_id": "battery_state"}],
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
json = await resp.json()
|
||||
assert json['battery_state']['success'] is False
|
||||
assert json['battery_state']['error']['code'] == 'not_registered'
|
||||
assert json["battery_state"]["success"] is False
|
||||
assert json["battery_state"]["error"]["code"] == "not_registered"
|
||||
|
||||
|
||||
async def test_sensor_id_no_dupes(hass, create_registrations, # noqa: F401, F811, E501
|
||||
webhook_client): # noqa: F401, F811, E501
|
||||
async def test_sensor_id_no_dupes(
|
||||
hass, create_registrations, webhook_client # noqa: F401, F811, E501
|
||||
): # noqa: F401, F811, E501
|
||||
"""Test that sensors must have a unique ID."""
|
||||
webhook_id = create_registrations[1]['webhook_id']
|
||||
webhook_url = '/api/webhook/{}'.format(webhook_id)
|
||||
webhook_id = create_registrations[1]["webhook_id"]
|
||||
webhook_url = "/api/webhook/{}".format(webhook_id)
|
||||
|
||||
payload = {
|
||||
'type': 'register_sensor',
|
||||
'data': {
|
||||
'attributes': {
|
||||
'foo': 'bar'
|
||||
},
|
||||
'device_class': 'battery',
|
||||
'icon': 'mdi:battery',
|
||||
'name': 'Battery State',
|
||||
'state': 100,
|
||||
'type': 'sensor',
|
||||
'unique_id': 'battery_state',
|
||||
'unit_of_measurement': '%'
|
||||
}
|
||||
"type": "register_sensor",
|
||||
"data": {
|
||||
"attributes": {"foo": "bar"},
|
||||
"device_class": "battery",
|
||||
"icon": "mdi:battery",
|
||||
"name": "Battery State",
|
||||
"state": 100,
|
||||
"type": "sensor",
|
||||
"unique_id": "battery_state",
|
||||
"unit_of_measurement": "%",
|
||||
},
|
||||
}
|
||||
|
||||
reg_resp = await webhook_client.post(webhook_url, json=payload)
|
||||
@@ -120,12 +114,12 @@ async def test_sensor_id_no_dupes(hass, create_registrations, # noqa: F401, F81
|
||||
assert reg_resp.status == 201
|
||||
|
||||
reg_json = await reg_resp.json()
|
||||
assert reg_json == {'success': True}
|
||||
assert reg_json == {"success": True}
|
||||
|
||||
dupe_resp = await webhook_client.post(webhook_url, json=payload)
|
||||
|
||||
assert dupe_resp.status == 409
|
||||
|
||||
dupe_json = await dupe_resp.json()
|
||||
assert dupe_json['success'] is False
|
||||
assert dupe_json['error']['code'] == 'duplicate_unique_id'
|
||||
assert dupe_json["success"] is False
|
||||
assert dupe_json["error"]["code"] == "duplicate_unique_id"
|
||||
@@ -25,9 +25,7 @@ async def test_registration(hass, hass_client):
|
||||
|
||||
api_client = await hass_client()
|
||||
|
||||
resp = await api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER
|
||||
)
|
||||
resp = await api_client.post("/api/mobile_app/registrations", json=REGISTER)
|
||||
|
||||
assert resp.status == 201
|
||||
register_json = await resp.json()
|
||||
@@ -36,46 +34,40 @@ async def test_registration(hass, hass_client):
|
||||
|
||||
entries = hass.config_entries.async_entries(DOMAIN)
|
||||
|
||||
assert entries[0].data['app_data'] == REGISTER['app_data']
|
||||
assert entries[0].data['app_id'] == REGISTER['app_id']
|
||||
assert entries[0].data['app_name'] == REGISTER['app_name']
|
||||
assert entries[0].data['app_version'] == REGISTER['app_version']
|
||||
assert entries[0].data['device_name'] == REGISTER['device_name']
|
||||
assert entries[0].data['manufacturer'] == REGISTER['manufacturer']
|
||||
assert entries[0].data['model'] == REGISTER['model']
|
||||
assert entries[0].data['os_name'] == REGISTER['os_name']
|
||||
assert entries[0].data['os_version'] == REGISTER['os_version']
|
||||
assert entries[0].data['supports_encryption'] == \
|
||||
REGISTER['supports_encryption']
|
||||
assert entries[0].data["app_data"] == REGISTER["app_data"]
|
||||
assert entries[0].data["app_id"] == REGISTER["app_id"]
|
||||
assert entries[0].data["app_name"] == REGISTER["app_name"]
|
||||
assert entries[0].data["app_version"] == REGISTER["app_version"]
|
||||
assert entries[0].data["device_name"] == REGISTER["device_name"]
|
||||
assert entries[0].data["manufacturer"] == REGISTER["manufacturer"]
|
||||
assert entries[0].data["model"] == REGISTER["model"]
|
||||
assert entries[0].data["os_name"] == REGISTER["os_name"]
|
||||
assert entries[0].data["os_version"] == REGISTER["os_version"]
|
||||
assert entries[0].data["supports_encryption"] == REGISTER["supports_encryption"]
|
||||
|
||||
keylen = SecretBox.KEY_SIZE
|
||||
key = register_json[CONF_SECRET].encode("utf-8")
|
||||
key = key[:keylen]
|
||||
key = key.ljust(keylen, b'\0')
|
||||
key = key.ljust(keylen, b"\0")
|
||||
|
||||
payload = json.dumps(RENDER_TEMPLATE['data']).encode("utf-8")
|
||||
payload = json.dumps(RENDER_TEMPLATE["data"]).encode("utf-8")
|
||||
|
||||
data = SecretBox(key).encrypt(payload,
|
||||
encoder=Base64Encoder).decode("utf-8")
|
||||
data = SecretBox(key).encrypt(payload, encoder=Base64Encoder).decode("utf-8")
|
||||
|
||||
container = {
|
||||
'type': 'render_template',
|
||||
'encrypted': True,
|
||||
'encrypted_data': data,
|
||||
}
|
||||
container = {"type": "render_template", "encrypted": True, "encrypted_data": data}
|
||||
|
||||
resp = await api_client.post(
|
||||
'/api/webhook/{}'.format(register_json[CONF_WEBHOOK_ID]),
|
||||
json=container
|
||||
"/api/webhook/{}".format(register_json[CONF_WEBHOOK_ID]), json=container
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
webhook_json = await resp.json()
|
||||
assert 'encrypted_data' in webhook_json
|
||||
assert "encrypted_data" in webhook_json
|
||||
|
||||
decrypted_data = SecretBox(key).decrypt(webhook_json['encrypted_data'],
|
||||
encoder=Base64Encoder)
|
||||
decrypted_data = SecretBox(key).decrypt(
|
||||
webhook_json["encrypted_data"], encoder=Base64Encoder
|
||||
)
|
||||
decrypted_data = decrypted_data.decode("utf-8")
|
||||
|
||||
assert json.loads(decrypted_data) == {'one': 'Hello world'}
|
||||
assert json.loads(decrypted_data) == {"one": "Hello world"}
|
||||
@@ -12,31 +12,32 @@ from tests.common import MockConfigEntry
|
||||
@pytest.fixture
|
||||
async def setup_push_receiver(hass, aioclient_mock):
|
||||
"""Fixture that sets up a mocked push receiver."""
|
||||
push_url = 'https://mobile-push.home-assistant.dev/push'
|
||||
push_url = "https://mobile-push.home-assistant.dev/push"
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
now = (datetime.now() + timedelta(hours=24))
|
||||
|
||||
now = datetime.now() + timedelta(hours=24)
|
||||
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
aioclient_mock.post(push_url, json={
|
||||
'rateLimits': {
|
||||
'attempts': 1,
|
||||
'successful': 1,
|
||||
'errors': 0,
|
||||
'total': 1,
|
||||
'maximum': 150,
|
||||
'remaining': 149,
|
||||
'resetsAt': iso_time
|
||||
}
|
||||
})
|
||||
aioclient_mock.post(
|
||||
push_url,
|
||||
json={
|
||||
"rateLimits": {
|
||||
"attempts": 1,
|
||||
"successful": 1,
|
||||
"errors": 0,
|
||||
"total": 1,
|
||||
"maximum": 150,
|
||||
"remaining": 149,
|
||||
"resetsAt": iso_time,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
entry = MockConfigEntry(
|
||||
connection_class="cloud_push",
|
||||
data={
|
||||
"app_data": {
|
||||
"push_token": "PUSH_TOKEN",
|
||||
"push_url": push_url
|
||||
},
|
||||
"app_data": {"push_token": "PUSH_TOKEN", "push_url": push_url},
|
||||
"app_id": "io.homeassistant.mobile_app",
|
||||
"app_name": "mobile_app tests",
|
||||
"app_version": "1.0",
|
||||
@@ -49,12 +50,12 @@ async def setup_push_receiver(hass, aioclient_mock):
|
||||
"secret": "123abc",
|
||||
"supports_encryption": False,
|
||||
"user_id": "1a2b3c",
|
||||
"webhook_id": "webhook_id"
|
||||
"webhook_id": "webhook_id",
|
||||
},
|
||||
domain=DOMAIN,
|
||||
source="registration",
|
||||
title="mobile_app test entry",
|
||||
version=1
|
||||
version=1,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
@@ -64,10 +65,10 @@ async def setup_push_receiver(hass, aioclient_mock):
|
||||
|
||||
async def test_notify_works(hass, aioclient_mock, setup_push_receiver):
|
||||
"""Test notify works."""
|
||||
assert hass.services.has_service('notify', 'mobile_app_test') is True
|
||||
assert await hass.services.async_call('notify', 'mobile_app_test',
|
||||
{'message': 'Hello world'},
|
||||
blocking=True)
|
||||
assert hass.services.has_service("notify", "mobile_app_test") is True
|
||||
assert await hass.services.async_call(
|
||||
"notify", "mobile_app_test", {"message": "Hello world"}, blocking=True
|
||||
)
|
||||
|
||||
assert len(aioclient_mock.mock_calls) == 1
|
||||
call = aioclient_mock.mock_calls
|
||||
@@ -76,6 +77,5 @@ async def test_notify_works(hass, aioclient_mock, setup_push_receiver):
|
||||
|
||||
assert call_json["push_token"] == "PUSH_TOKEN"
|
||||
assert call_json["message"] == "Hello world"
|
||||
assert call_json["registration_info"]["app_id"] == \
|
||||
"io.homeassistant.mobile_app"
|
||||
assert call_json["registration_info"]["app_id"] == "io.homeassistant.mobile_app"
|
||||
assert call_json["registration_info"]["app_version"] == "1.0"
|
||||
@@ -11,34 +11,33 @@ from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import async_mock_service
|
||||
|
||||
from .const import (CALL_SERVICE, FIRE_EVENT, REGISTER_CLEARTEXT,
|
||||
RENDER_TEMPLATE, UPDATE)
|
||||
from .const import CALL_SERVICE, FIRE_EVENT, REGISTER_CLEARTEXT, RENDER_TEMPLATE, UPDATE
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def test_webhook_handle_render_template(create_registrations,
|
||||
webhook_client):
|
||||
async def test_webhook_handle_render_template(create_registrations, webhook_client):
|
||||
"""Test that we render templates properly."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
json=RENDER_TEMPLATE
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json=RENDER_TEMPLATE,
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
json = await resp.json()
|
||||
assert json == {'one': 'Hello world'}
|
||||
assert json == {"one": "Hello world"}
|
||||
|
||||
|
||||
async def test_webhook_handle_call_services(hass, create_registrations,
|
||||
webhook_client): # noqa: E501 F811
|
||||
async def test_webhook_handle_call_services(
|
||||
hass, create_registrations, webhook_client
|
||||
): # noqa: E501 F811
|
||||
"""Test that we call services properly."""
|
||||
calls = async_mock_service(hass, 'test', 'mobile_app')
|
||||
calls = async_mock_service(hass, "test", "mobile_app")
|
||||
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
json=CALL_SERVICE
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json=CALL_SERVICE,
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
@@ -46,8 +45,7 @@ async def test_webhook_handle_call_services(hass, create_registrations,
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
async def test_webhook_handle_fire_event(hass, create_registrations,
|
||||
webhook_client):
|
||||
async def test_webhook_handle_fire_event(hass, create_registrations, webhook_client):
|
||||
"""Test that we can fire events."""
|
||||
events = []
|
||||
|
||||
@@ -56,11 +54,10 @@ async def test_webhook_handle_fire_event(hass, create_registrations,
|
||||
"""Helepr to store events."""
|
||||
events.append(event)
|
||||
|
||||
hass.bus.async_listen('test_event', store_event)
|
||||
hass.bus.async_listen("test_event", store_event)
|
||||
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
json=FIRE_EVENT
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]), json=FIRE_EVENT
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
@@ -68,14 +65,16 @@ async def test_webhook_handle_fire_event(hass, create_registrations,
|
||||
assert json == {}
|
||||
|
||||
assert len(events) == 1
|
||||
assert events[0].data['hello'] == 'yo world'
|
||||
assert events[0].data["hello"] == "yo world"
|
||||
|
||||
|
||||
async def test_webhook_update_registration(webhook_client, hass_client): # noqa: E501 F811
|
||||
async def test_webhook_update_registration(
|
||||
webhook_client, hass_client
|
||||
): # noqa: E501 F811
|
||||
"""Test that a we can update an existing registration via webhook."""
|
||||
authed_api_client = await hass_client()
|
||||
register_resp = await authed_api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER_CLEARTEXT
|
||||
"/api/mobile_app/registrations", json=REGISTER_CLEARTEXT
|
||||
)
|
||||
|
||||
assert register_resp.status == 201
|
||||
@@ -83,97 +82,93 @@ async def test_webhook_update_registration(webhook_client, hass_client): # noqa
|
||||
|
||||
webhook_id = register_json[CONF_WEBHOOK_ID]
|
||||
|
||||
update_container = {
|
||||
'type': 'update_registration',
|
||||
'data': UPDATE
|
||||
}
|
||||
update_container = {"type": "update_registration", "data": UPDATE}
|
||||
|
||||
update_resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(webhook_id), json=update_container
|
||||
"/api/webhook/{}".format(webhook_id), json=update_container
|
||||
)
|
||||
|
||||
assert update_resp.status == 200
|
||||
update_json = await update_resp.json()
|
||||
assert update_json['app_version'] == '2.0.0'
|
||||
assert update_json["app_version"] == "2.0.0"
|
||||
assert CONF_WEBHOOK_ID not in update_json
|
||||
assert CONF_SECRET not in update_json
|
||||
|
||||
|
||||
async def test_webhook_handle_get_zones(hass, create_registrations,
|
||||
webhook_client):
|
||||
async def test_webhook_handle_get_zones(hass, create_registrations, webhook_client):
|
||||
"""Test that we can get zones properly."""
|
||||
await async_setup_component(hass, ZONE_DOMAIN, {
|
||||
ZONE_DOMAIN: {
|
||||
'name': 'test',
|
||||
'latitude': 32.880837,
|
||||
'longitude': -117.237561,
|
||||
'radius': 250,
|
||||
}
|
||||
})
|
||||
await async_setup_component(
|
||||
hass,
|
||||
ZONE_DOMAIN,
|
||||
{
|
||||
ZONE_DOMAIN: {
|
||||
"name": "test",
|
||||
"latitude": 32.880837,
|
||||
"longitude": -117.237561,
|
||||
"radius": 250,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
json={'type': 'get_zones'}
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json={"type": "get_zones"},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
json = await resp.json()
|
||||
assert len(json) == 1
|
||||
assert json[0]['entity_id'] == 'zone.home'
|
||||
assert json[0]["entity_id"] == "zone.home"
|
||||
|
||||
|
||||
async def test_webhook_handle_get_config(hass, create_registrations,
|
||||
webhook_client):
|
||||
async def test_webhook_handle_get_config(hass, create_registrations, webhook_client):
|
||||
"""Test that we can get config properly."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
json={'type': 'get_config'}
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
|
||||
json={"type": "get_config"},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
json = await resp.json()
|
||||
if 'components' in json:
|
||||
json['components'] = set(json['components'])
|
||||
if 'whitelist_external_dirs' in json:
|
||||
json['whitelist_external_dirs'] = \
|
||||
set(json['whitelist_external_dirs'])
|
||||
if "components" in json:
|
||||
json["components"] = set(json["components"])
|
||||
if "whitelist_external_dirs" in json:
|
||||
json["whitelist_external_dirs"] = set(json["whitelist_external_dirs"])
|
||||
|
||||
hass_config = hass.config.as_dict()
|
||||
|
||||
expected_dict = {
|
||||
'latitude': hass_config['latitude'],
|
||||
'longitude': hass_config['longitude'],
|
||||
'elevation': hass_config['elevation'],
|
||||
'unit_system': hass_config['unit_system'],
|
||||
'location_name': hass_config['location_name'],
|
||||
'time_zone': hass_config['time_zone'],
|
||||
'components': hass_config['components'],
|
||||
'version': hass_config['version'],
|
||||
'theme_color': '#03A9F4', # Default frontend theme color
|
||||
"latitude": hass_config["latitude"],
|
||||
"longitude": hass_config["longitude"],
|
||||
"elevation": hass_config["elevation"],
|
||||
"unit_system": hass_config["unit_system"],
|
||||
"location_name": hass_config["location_name"],
|
||||
"time_zone": hass_config["time_zone"],
|
||||
"components": hass_config["components"],
|
||||
"version": hass_config["version"],
|
||||
"theme_color": "#03A9F4", # Default frontend theme color
|
||||
}
|
||||
|
||||
assert expected_dict == json
|
||||
|
||||
|
||||
async def test_webhook_returns_error_incorrect_json(webhook_client,
|
||||
create_registrations,
|
||||
caplog): # noqa: E501 F811
|
||||
async def test_webhook_returns_error_incorrect_json(
|
||||
webhook_client, create_registrations, caplog
|
||||
): # noqa: E501 F811
|
||||
"""Test that an error is returned when JSON is invalid."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[1]['webhook_id']),
|
||||
data='not json'
|
||||
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]), data="not json"
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
json = await resp.json()
|
||||
assert json == {}
|
||||
assert 'invalid JSON' in caplog.text
|
||||
assert "invalid JSON" in caplog.text
|
||||
|
||||
|
||||
async def test_webhook_handle_decryption(webhook_client,
|
||||
create_registrations):
|
||||
async def test_webhook_handle_decryption(webhook_client, create_registrations):
|
||||
"""Test that we can encrypt/decrypt properly."""
|
||||
try:
|
||||
# pylint: disable=unused-import
|
||||
@@ -186,49 +181,43 @@ async def test_webhook_handle_decryption(webhook_client,
|
||||
import json
|
||||
|
||||
keylen = SecretBox.KEY_SIZE
|
||||
key = create_registrations[0]['secret'].encode("utf-8")
|
||||
key = create_registrations[0]["secret"].encode("utf-8")
|
||||
key = key[:keylen]
|
||||
key = key.ljust(keylen, b'\0')
|
||||
key = key.ljust(keylen, b"\0")
|
||||
|
||||
payload = json.dumps(RENDER_TEMPLATE['data']).encode("utf-8")
|
||||
payload = json.dumps(RENDER_TEMPLATE["data"]).encode("utf-8")
|
||||
|
||||
data = SecretBox(key).encrypt(payload,
|
||||
encoder=Base64Encoder).decode("utf-8")
|
||||
data = SecretBox(key).encrypt(payload, encoder=Base64Encoder).decode("utf-8")
|
||||
|
||||
container = {
|
||||
'type': 'render_template',
|
||||
'encrypted': True,
|
||||
'encrypted_data': data,
|
||||
}
|
||||
container = {"type": "render_template", "encrypted": True, "encrypted_data": data}
|
||||
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[0]['webhook_id']),
|
||||
json=container
|
||||
"/api/webhook/{}".format(create_registrations[0]["webhook_id"]), json=container
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
|
||||
webhook_json = await resp.json()
|
||||
assert 'encrypted_data' in webhook_json
|
||||
assert "encrypted_data" in webhook_json
|
||||
|
||||
decrypted_data = SecretBox(key).decrypt(webhook_json['encrypted_data'],
|
||||
encoder=Base64Encoder)
|
||||
decrypted_data = SecretBox(key).decrypt(
|
||||
webhook_json["encrypted_data"], encoder=Base64Encoder
|
||||
)
|
||||
decrypted_data = decrypted_data.decode("utf-8")
|
||||
|
||||
assert json.loads(decrypted_data) == {'one': 'Hello world'}
|
||||
assert json.loads(decrypted_data) == {"one": "Hello world"}
|
||||
|
||||
|
||||
async def test_webhook_requires_encryption(webhook_client,
|
||||
create_registrations):
|
||||
async def test_webhook_requires_encryption(webhook_client, create_registrations):
|
||||
"""Test that encrypted registrations only accept encrypted data."""
|
||||
resp = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(create_registrations[0]['webhook_id']),
|
||||
json=RENDER_TEMPLATE
|
||||
"/api/webhook/{}".format(create_registrations[0]["webhook_id"]),
|
||||
json=RENDER_TEMPLATE,
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
|
||||
webhook_json = await resp.json()
|
||||
assert 'error' in webhook_json
|
||||
assert webhook_json['success'] is False
|
||||
assert webhook_json['error']['code'] == 'encryption_required'
|
||||
assert "error" in webhook_json
|
||||
assert webhook_json["success"] is False
|
||||
assert webhook_json["error"]["code"] == "encryption_required"
|
||||
@@ -1,26 +1,27 @@
|
||||
"""Test the mobile_app websocket API."""
|
||||
# pylint: disable=redefined-outer-name,unused-import
|
||||
from homeassistant.components.mobile_app.const import (CONF_SECRET, DOMAIN)
|
||||
from homeassistant.components.mobile_app.const import CONF_SECRET, DOMAIN
|
||||
from homeassistant.components.websocket_api.const import TYPE_RESULT
|
||||
from homeassistant.const import CONF_WEBHOOK_ID
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .const import (CALL_SERVICE, REGISTER)
|
||||
from .const import CALL_SERVICE, REGISTER
|
||||
|
||||
|
||||
async def test_webocket_get_user_registrations(hass, aiohttp_client,
|
||||
hass_ws_client,
|
||||
hass_read_only_access_token):
|
||||
async def test_webocket_get_user_registrations(
|
||||
hass, aiohttp_client, hass_ws_client, hass_read_only_access_token
|
||||
):
|
||||
"""Test get_user_registrations websocket command from admin perspective."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
user_api_client = await aiohttp_client(hass.http.app, headers={
|
||||
'Authorization': "Bearer {}".format(hass_read_only_access_token)
|
||||
})
|
||||
user_api_client = await aiohttp_client(
|
||||
hass.http.app,
|
||||
headers={"Authorization": "Bearer {}".format(hass_read_only_access_token)},
|
||||
)
|
||||
|
||||
# First a read only user registers.
|
||||
register_resp = await user_api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER
|
||||
"/api/mobile_app/registrations", json=REGISTER
|
||||
)
|
||||
|
||||
assert register_resp.status == 201
|
||||
@@ -30,25 +31,23 @@ async def test_webocket_get_user_registrations(hass, aiohttp_client,
|
||||
|
||||
# Then the admin user attempts to access it.
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'mobile_app/get_user_registrations',
|
||||
})
|
||||
await client.send_json({"id": 5, "type": "mobile_app/get_user_registrations"})
|
||||
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert len(msg['result']) == 1
|
||||
assert msg["id"] == 5
|
||||
assert msg["type"] == TYPE_RESULT
|
||||
assert msg["success"]
|
||||
assert len(msg["result"]) == 1
|
||||
|
||||
|
||||
async def test_webocket_delete_registration(hass, hass_client,
|
||||
hass_ws_client, webhook_client):
|
||||
async def test_webocket_delete_registration(
|
||||
hass, hass_client, hass_ws_client, webhook_client
|
||||
):
|
||||
"""Test delete_registration websocket command."""
|
||||
authed_api_client = await hass_client() # noqa: F811
|
||||
register_resp = await authed_api_client.post(
|
||||
'/api/mobile_app/registrations', json=REGISTER
|
||||
"/api/mobile_app/registrations", json=REGISTER
|
||||
)
|
||||
|
||||
assert register_resp.status == 201
|
||||
@@ -59,21 +58,19 @@ async def test_webocket_delete_registration(hass, hass_client,
|
||||
webhook_id = register_json[CONF_WEBHOOK_ID]
|
||||
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'mobile_app/delete_registration',
|
||||
CONF_WEBHOOK_ID: webhook_id,
|
||||
})
|
||||
await client.send_json(
|
||||
{"id": 5, "type": "mobile_app/delete_registration", CONF_WEBHOOK_ID: webhook_id}
|
||||
)
|
||||
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert msg['result'] == 'ok'
|
||||
assert msg["id"] == 5
|
||||
assert msg["type"] == TYPE_RESULT
|
||||
assert msg["success"]
|
||||
assert msg["result"] == "ok"
|
||||
|
||||
ensure_four_ten_gone = await webhook_client.post(
|
||||
'/api/webhook/{}'.format(webhook_id), json=CALL_SERVICE
|
||||
"/api/webhook/{}".format(webhook_id), json=CALL_SERVICE
|
||||
)
|
||||
|
||||
assert ensure_four_ten_gone.status == 410
|
||||
Reference in new issue
Block a user