-
-
Notifications
You must be signed in to change notification settings - Fork 37.5k
Expand file tree
/
Copy pathtest_commands.py
More file actions
4503 lines (3923 loc) · 141 KB
/
test_commands.py
File metadata and controls
4503 lines (3923 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for WebSocket API commands."""
import asyncio
from copy import deepcopy
import io
import logging
import math
from typing import Any
from unittest.mock import ANY, AsyncMock, Mock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
import voluptuous as vol
from homeassistant import loader
from homeassistant.components.device_automation import toggle_entity
from homeassistant.components.group import DOMAIN as GROUP_DOMAIN
from homeassistant.components.light import LightEntityFeature
from homeassistant.components.logger import DOMAIN as LOGGER_DOMAIN
from homeassistant.components.websocket_api import const
from homeassistant.components.websocket_api.auth import (
TYPE_AUTH,
TYPE_AUTH_OK,
TYPE_AUTH_REQUIRED,
)
from homeassistant.components.websocket_api.automation import (
AUTOMATION_COMPONENT_LOOKUP_CACHE,
_get_automation_component_lookup_table,
)
from homeassistant.components.websocket_api.commands import (
ALL_CONDITION_DESCRIPTIONS_JSON_CACHE,
ALL_SERVICE_DESCRIPTIONS_JSON_CACHE,
ALL_TRIGGER_DESCRIPTIONS_JSON_CACHE,
)
from homeassistant.components.websocket_api.const import FEATURE_COALESCE_MESSAGES, URL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
CONF_EXTERNAL_URL,
SIGNAL_BOOTSTRAP_INTEGRATIONS,
EntityCategory,
)
from homeassistant.core import Context, HomeAssistant, State, SupportsResponse, callback
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
label_registry as lr,
)
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.loader import Integration, async_get_integration
from homeassistant.setup import async_set_domains_to_be_loaded, async_setup_component
from homeassistant.util.json import json_loads
from homeassistant.util.yaml.loader import JSON_TYPE, parse_yaml
from tests.common import (
MockConfigEntry,
MockEntity,
MockEntityPlatform,
MockModule,
MockUser,
async_mock_service,
mock_device_registry,
mock_integration,
mock_platform,
)
from tests.typing import (
ClientSessionGenerator,
MockHAClientWebSocket,
WebSocketGenerator,
)
STATE_KEY_SHORT_NAMES = {
"entity_id": "e",
"state": "s",
"last_changed": "lc",
"last_updated": "lu",
"context": "c",
"attributes": "a",
}
STATE_KEY_LONG_NAMES = {v: k for k, v in STATE_KEY_SHORT_NAMES.items()}
@pytest.fixture
def fake_integration(hass: HomeAssistant):
"""Set up a mock integration with device automation support."""
DOMAIN = "fake_integration"
hass.config.components.add(DOMAIN)
mock_platform(
hass,
f"{DOMAIN}.device_action",
Mock(
ACTION_SCHEMA=toggle_entity.ACTION_SCHEMA.extend(
{vol.Required("domain"): DOMAIN}
),
spec=["ACTION_SCHEMA"],
),
)
@pytest.fixture
async def target_entities(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
entity_registry: er.EntityRegistry,
label_registry: lr.LabelRegistry,
):
"""Fixture to create targets and entities used in target-based tests.
The list of created entities, areas, labels, and devices can be found in the
assertions at the end.
"""
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
kitchen_area = area_registry.async_create("Kitchen")
living_room_area = area_registry.async_create("Living Room")
label_area = area_registry.async_create("Bathroom")
label1 = label_registry.async_create("Label 1")
label2 = label_registry.async_create("Label 2")
area_registry.async_update(label_area.id, labels={label1.label_id})
device1 = dr.DeviceEntry(id="device1", identifiers={("test", "device1")})
device2 = dr.DeviceEntry(id="device2", identifiers={("test", "device2")})
area_device = dr.DeviceEntry(
id="area_device", identifiers={("test", "device3")}, area_id=kitchen_area.id
)
label2_device = dr.DeviceEntry(
id="label_device", identifiers={("test", "device4")}, labels={label2.label_id}
)
mock_device_registry(
hass,
{
device1.id: device1,
device2.id: device2,
area_device.id: area_device,
label2_device.id: label2_device,
},
)
# Create entities
not_registry_light = MockEntity(entity_id="light.not_registry")
device1_light = MockEntity(
entity_id="light.test1",
unique_id="test1",
device_info=dr.DeviceInfo(identifiers=device1.identifiers),
)
label_device_light = MockEntity(
entity_id="light.test4",
unique_id="test4",
device_info=dr.DeviceInfo(identifiers=label2_device.identifiers),
)
area_light = MockEntity(entity_id="light.test6", unique_id="test6")
light_platform = MockEntityPlatform(hass, domain="light", platform_name="test")
light_platform.config_entry = config_entry
await light_platform.async_add_entities(
[not_registry_light, device1_light, label_device_light, area_light]
)
assert entity_registry.async_get(not_registry_light.entity_id) is None
device1_switch = MockEntity(
entity_id="switch.test2",
unique_id="test2",
device_info=dr.DeviceInfo(identifiers=device1.identifiers),
)
area_device_switch = MockEntity(
entity_id="switch.test5",
unique_id="test5",
device_info=dr.DeviceInfo(identifiers=area_device.identifiers),
)
switch_platform = MockEntityPlatform(hass, domain="switch", platform_name="test")
switch_platform.config_entry = config_entry
await switch_platform.async_add_entities([device1_switch, area_device_switch])
area_device_diagnostic_sensor = MockEntity(
entity_id="sensor.test7",
unique_id="test7",
device_info=dr.DeviceInfo(identifiers=area_device.identifiers),
entity_category=EntityCategory.DIAGNOSTIC,
)
label2_device_config_sensor = MockEntity(
entity_id="sensor.potato",
unique_id="potato",
device_info=dr.DeviceInfo(identifiers=label2_device.identifiers),
entity_category=EntityCategory.CONFIG,
)
sensor_platform = MockEntityPlatform(hass, domain="sensor", platform_name="test")
sensor_platform.config_entry = config_entry
await sensor_platform.async_add_entities(
[area_device_diagnostic_sensor, label2_device_config_sensor]
)
component1_light = MockEntity(
entity_id="light.component1_light", unique_id="component1_light"
)
component1_flash_light = MockEntity(
entity_id="light.component1_flash_light",
unique_id="component1_flash_light",
supported_features=LightEntityFeature.FLASH,
)
component1_effect_flash_light = MockEntity(
entity_id="light.component1_effect_flash_light",
unique_id="component1_effect_flash_light",
supported_features=LightEntityFeature.EFFECT | LightEntityFeature.FLASH,
)
component1_flash_transition_light = MockEntity(
entity_id="light.component1_flash_transition_light",
unique_id="component1_flash_transition_light",
supported_features=LightEntityFeature.FLASH | LightEntityFeature.TRANSITION,
)
component1_light_platform = MockEntityPlatform(
hass, domain="light", platform_name="component1"
)
component1_light_platform.config_entry = config_entry
await component1_light_platform.async_add_entities(
[
component1_light,
component1_flash_light,
component1_effect_flash_light,
component1_flash_transition_light,
]
)
label_component1_switch = MockEntity(
entity_id="switch.component1_switch", unique_id="component1_switch"
)
component1_switch_platform = MockEntityPlatform(
hass, domain="switch", platform_name="component1"
)
component1_switch_platform.config_entry = config_entry
await component1_switch_platform.async_add_entities([label_component1_switch])
device2_component1_sensor = MockEntity(
entity_id="sensor.component1_sensor",
unique_id="component1_sensor",
device_class="illuminance",
device_info=dr.DeviceInfo(identifiers=device2.identifiers),
)
component1_sensor_platform = MockEntityPlatform(
hass, domain="sensor", platform_name="component1"
)
component1_sensor_platform.config_entry = config_entry
await component1_sensor_platform.async_add_entities([device2_component1_sensor])
# Associate entities with areas and labels
entity_registry.async_update_entity(
area_light.entity_id, area_id=living_room_area.id
)
entity_registry.async_update_entity(
label_component1_switch.entity_id, labels={label1.label_id}
)
assert set(hass.states.async_entity_ids()) == {
"light.not_registry",
"light.test1",
"light.test4",
"light.test6",
"switch.test2",
"switch.test5",
"sensor.test7",
"sensor.potato",
"light.component1_light",
"light.component1_flash_light",
"light.component1_effect_flash_light",
"light.component1_flash_transition_light",
"switch.component1_switch",
"sensor.component1_sensor",
}
assert set(label_registry.labels) == {"label_1", "label_2"}
assert set(area_registry.areas) == {"kitchen", "living_room", "bathroom"}
assert set(dr.async_get(hass).devices) == {
"device1",
"device2",
"area_device",
"label_device",
}
def _apply_entities_changes(state_dict: dict, change_dict: dict) -> None:
"""Apply a diff set to a dict.
Port of the client side merging
"""
additions = change_dict.get("+", {})
if "lc" in additions:
additions["lu"] = additions["lc"]
if attributes := additions.pop("a", None):
state_dict["attributes"].update(attributes)
if context := additions.pop("c", None):
if isinstance(context, str):
state_dict["context"]["id"] = context
else:
state_dict["context"].update(context)
for k, v in additions.items():
state_dict[STATE_KEY_LONG_NAMES[k]] = v
for key, items in change_dict.get("-", {}).items():
for item in items:
del state_dict[STATE_KEY_LONG_NAMES[key]][item]
def _assert_extract_from_target_command_result(
msg: dict[str, Any],
entities: set[str] | None = None,
devices: set[str] | None = None,
areas: set[str] | None = None,
missing_devices: set[str] | None = None,
missing_areas: set[str] | None = None,
missing_labels: set[str] | None = None,
missing_floors: set[str] | None = None,
) -> None:
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
result = msg["result"]
assert set(result["referenced_entities"]) == (entities or set())
assert set(result["referenced_devices"]) == (devices or set())
assert set(result["referenced_areas"]) == (areas or set())
assert set(result["missing_devices"]) == (missing_devices or set())
assert set(result["missing_areas"]) == (missing_areas or set())
assert set(result["missing_floors"]) == (missing_floors or set())
assert set(result["missing_labels"]) == (missing_labels or set())
async def test_fire_event(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test fire event command."""
runs = []
async def event_handler(event):
runs.append(event)
hass.bus.async_listen_once("event_type_test", event_handler)
await websocket_client.send_json_auto_id(
{
"type": "fire_event",
"event_type": "event_type_test",
"event_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(runs) == 1
assert runs[0].event_type == "event_type_test"
assert runs[0].data == {"hello": "world"}
async def test_fire_event_without_data(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test fire event command."""
runs = []
async def event_handler(event):
runs.append(event)
hass.bus.async_listen_once("event_type_test", event_handler)
await websocket_client.send_json_auto_id(
{
"type": "fire_event",
"event_type": "event_type_test",
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(runs) == 1
assert runs[0].event_type == "event_type_test"
assert runs[0].data == {}
async def test_call_service(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test call service command."""
calls = async_mock_service(hass, "domain_test", "test_service")
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(calls) == 1
call = calls[0]
assert call.domain == "domain_test"
assert call.service == "test_service"
assert call.data == {"hello": "world"}
assert call.context.as_dict() == msg["result"]["context"]
async def test_return_response_error(hass: HomeAssistant, websocket_client) -> None:
"""Test return_response=True errors when service has no response."""
hass.services.async_register(
"domain_test", "test_service_with_no_response", lambda x: None
)
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service_with_no_response",
"service_data": {"hello": "world"},
"return_response": True,
},
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == "service_validation_error"
@pytest.mark.parametrize("command", ["call_service", "call_service_action"])
async def test_call_service_blocking(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket, command
) -> None:
"""Test call service commands block, except for homeassistant restart / stop."""
async_mock_service(
hass,
"domain_test",
"test_service",
response={"hello": "world"},
supports_response=SupportsResponse.OPTIONAL,
)
with patch(
"homeassistant.core.ServiceRegistry.async_call", autospec=True
) as mock_call:
mock_call.return_value = {"foo": "bar"}
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
"return_response": True,
},
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"]["response"] == {"foo": "bar"}
mock_call.assert_called_once_with(
ANY,
"domain_test",
"test_service",
{"hello": "world"},
blocking=True,
context=ANY,
target=ANY,
return_response=True,
)
with patch(
"homeassistant.core.ServiceRegistry.async_call", autospec=True
) as mock_call:
mock_call.return_value = None
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
},
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
mock_call.assert_called_once_with(
ANY,
"domain_test",
"test_service",
{"hello": "world"},
blocking=True,
context=ANY,
target=ANY,
return_response=False,
)
async_mock_service(hass, "homeassistant", "test_service")
with patch(
"homeassistant.core.ServiceRegistry.async_call", autospec=True
) as mock_call:
mock_call.return_value = None
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "homeassistant",
"service": "test_service",
},
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
mock_call.assert_called_once_with(
ANY,
"homeassistant",
"test_service",
ANY,
blocking=True,
context=ANY,
target=ANY,
return_response=False,
)
async_mock_service(hass, "homeassistant", "restart")
with patch(
"homeassistant.core.ServiceRegistry.async_call", autospec=True
) as mock_call:
mock_call.return_value = None
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "homeassistant",
"service": "restart",
},
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
mock_call.assert_called_once_with(
ANY,
"homeassistant",
"restart",
ANY,
blocking=True,
context=ANY,
target=ANY,
return_response=False,
)
async def test_call_service_target(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test call service command with target."""
calls = async_mock_service(hass, "domain_test", "test_service")
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
"target": {
"entity_id": ["entity.one", "entity.two"],
"device_id": "deviceid",
},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(calls) == 1
call = calls[0]
assert call.domain == "domain_test"
assert call.service == "test_service"
assert call.data == {
"hello": "world",
"entity_id": ["entity.one", "entity.two"],
"device_id": ["deviceid"],
}
assert call.context.as_dict() == msg["result"]["context"]
async def test_call_service_target_template(
hass: HomeAssistant, websocket_client
) -> None:
"""Test call service command with target does not allow template."""
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
"target": {
"entity_id": "{{ 1 }}",
},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
async def test_call_service_not_found(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test call service command."""
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_NOT_FOUND
assert msg["error"]["message"] == "Service domain_test.test_service not found."
assert msg["error"]["translation_placeholders"] == {
"domain": "domain_test",
"service": "test_service",
}
assert msg["error"]["translation_key"] == "service_not_found"
assert msg["error"]["translation_domain"] == "homeassistant"
async def test_call_service_child_not_found(
hass: HomeAssistant, websocket_client
) -> None:
"""Test not reporting not found errors if it's not the called service."""
async def serv_handler(call):
await hass.services.async_call("non", "existing")
hass.services.async_register("domain_test", "test_service", serv_handler)
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_HOME_ASSISTANT_ERROR
assert (
msg["error"]["message"] == "Service non.existing called service "
"domain_test.test_service which was not found."
)
assert msg["error"]["translation_placeholders"] == {
"domain": "domain_test",
"service": "test_service",
"child_domain": "non",
"child_service": "existing",
}
assert msg["error"]["translation_key"] == "child_service_not_found"
assert msg["error"]["translation_domain"] == "websocket_api"
async def test_call_service_schema_validation_error(
hass: HomeAssistant, websocket_client
) -> None:
"""Test call service command with invalid service data."""
calls = []
service_schema = vol.Schema(
{
vol.Required("message"): str,
}
)
@callback
def service_call(call):
calls.append(call)
hass.services.async_register(
"domain_test",
"test_service",
service_call,
schema=service_schema,
)
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"extra_key": "not allowed"},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"message": []},
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
assert len(calls) == 0
@pytest.mark.parametrize("ignore_translations_for_mock_domains", ["test"])
async def test_call_service_error(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
websocket_client: MockHAClientWebSocket,
) -> None:
"""Test call service command with error."""
caplog.set_level(logging.ERROR)
@callback
def ha_error_call(_):
raise HomeAssistantError(
"error_message",
translation_domain="test",
translation_key="custom_error",
translation_placeholders={"option": "bla"},
)
hass.services.async_register("domain_test", "ha_error", ha_error_call)
@callback
def service_error_call(_):
raise ServiceValidationError(
"error_message",
translation_domain="test",
translation_key="custom_error",
translation_placeholders={"option": "bla"},
)
hass.services.async_register("domain_test", "service_error", service_error_call)
async def unknown_error_call(_):
raise ValueError("value_error")
hass.services.async_register("domain_test", "unknown_error", unknown_error_call)
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "ha_error",
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"] is False
assert msg["error"]["code"] == "home_assistant_error"
assert msg["error"]["message"] == "error_message"
assert msg["error"]["translation_placeholders"] == {"option": "bla"}
assert msg["error"]["translation_key"] == "custom_error"
assert msg["error"]["translation_domain"] == "test"
assert "Traceback" not in caplog.text
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "service_error",
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"] is False
assert msg["error"]["code"] == "service_validation_error"
assert msg["error"]["message"] == "Validation error: error_message"
assert msg["error"]["translation_placeholders"] == {"option": "bla"}
assert msg["error"]["translation_key"] == "custom_error"
assert msg["error"]["translation_domain"] == "test"
assert "Traceback" not in caplog.text
await websocket_client.send_json_auto_id(
{
"type": "call_service",
"domain": "domain_test",
"service": "unknown_error",
}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"] is False
assert msg["error"]["code"] == "unknown_error"
assert msg["error"]["message"] == "value_error"
assert "Traceback" in caplog.text
async def test_subscribe_unsubscribe_events(
hass: HomeAssistant, websocket_client
) -> None:
"""Test subscribe/unsubscribe events command."""
init_count = sum(hass.bus.async_listeners().values())
await websocket_client.send_json_auto_id(
{"type": "subscribe_events", "event_type": "test_event"}
)
msg = await websocket_client.receive_json()
subscription = msg["id"]
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Verify we have a new listener
assert sum(hass.bus.async_listeners().values()) == init_count + 1
hass.bus.async_fire("ignore_event")
hass.bus.async_fire("test_event", {"hello": "world"})
hass.bus.async_fire("ignore_event")
async with asyncio.timeout(3):
msg = await websocket_client.receive_json()
assert msg["id"] == subscription
assert msg["type"] == "event"
event = msg["event"]
assert event["event_type"] == "test_event"
assert event["data"] == {"hello": "world"}
assert event["origin"] == "LOCAL"
await websocket_client.send_json_auto_id(
{"type": "unsubscribe_events", "subscription": subscription}
)
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Check our listener got unsubscribed
assert sum(hass.bus.async_listeners().values()) == init_count
async def test_get_states(
hass: HomeAssistant, websocket_client: MockHAClientWebSocket
) -> None:
"""Test get_states command."""
hass.states.async_set("greeting.hello", "world")
hass.states.async_set("greeting.bye", "universe")
await websocket_client.send_json_auto_id({"type": "get_states"})
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
states = [state.as_dict() for state in hass.states.async_all()]
assert msg["result"] == states
async def test_get_services(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
snapshot: SnapshotAssertion,
) -> None:
"""Test get_services command."""
assert ALL_SERVICE_DESCRIPTIONS_JSON_CACHE not in hass.data
await websocket_client.send_json_auto_id({"type": "get_services"})
msg = await websocket_client.receive_json()
assert msg == {"id": 1, "result": {}, "success": True, "type": "result"}
# Check cache is reused
old_cache = hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE]
await websocket_client.send_json_auto_id({"type": "get_services"})
msg = await websocket_client.receive_json()
assert msg == {"id": 2, "result": {}, "success": True, "type": "result"}
assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is old_cache
# Set up an integration that has services and check cache is updated
assert await async_setup_component(hass, GROUP_DOMAIN, {GROUP_DOMAIN: {}})
await websocket_client.send_json_auto_id({"type": "get_services"})
msg = await websocket_client.receive_json()
assert msg == {
"id": 3,
"result": {GROUP_DOMAIN: ANY},
"success": True,
"type": "result",
}
group_services = msg["result"][GROUP_DOMAIN]
assert group_services == snapshot
assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is not old_cache
# Check cache is reused
old_cache = hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE]
await websocket_client.send_json_auto_id({"type": "get_services"})
msg = await websocket_client.receive_json()
assert msg == {
"id": 4,
"result": {GROUP_DOMAIN: group_services},
"success": True,
"type": "result",
}
assert hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] is old_cache
# Set up an integration with legacy translations in services.yaml
def _load_services_file(integration: Integration) -> JSON_TYPE:
return {
"set_default_level": {
"description": "Translated description",
"fields": {
"level": {
"description": "Field description",
"example": "Field example",
"name": "Field name",
"selector": {
"select": {
"options": [
"debug",
"info",
"warning",
"error",
"fatal",
"critical",
],
"translation_key": "level",
}
},
}
},
"name": "Translated name",
},
"set_level": None,
}
await async_setup_component(hass, LOGGER_DOMAIN, {LOGGER_DOMAIN: {}})
await hass.async_block_till_done()
with (
patch(
"homeassistant.helpers.service._load_services_file",
side_effect=_load_services_file,
),
):
await websocket_client.send_json_auto_id({"type": "get_services"})
msg = await websocket_client.receive_json()
assert msg == {
"id": 5,
"result": {
LOGGER_DOMAIN: ANY,
GROUP_DOMAIN: group_services,
},
"success": True,
"type": "result",
}
logger_services = msg["result"][LOGGER_DOMAIN]
assert logger_services == snapshot
@patch("annotatedyaml.loader.load_yaml")
@patch.object(Integration, "has_conditions", return_value=True)
async def test_subscribe_conditions(
mock_has_conditions: Mock,
mock_load_yaml: Mock,