forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_config.py
1791 lines (1575 loc) · 58.1 KB
/
test_config.py
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
"""Test config utils."""
import asyncio
from collections import OrderedDict
from collections.abc import Generator
import contextlib
import logging
import os
from pathlib import Path
from unittest import mock
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
import voluptuous as vol
import yaml
from homeassistant import loader
import homeassistant.config as config_util
from homeassistant.const import CONF_PACKAGES, __version__
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.exceptions import ConfigValidationError, HomeAssistantError
from homeassistant.helpers import check_config, config_validation as cv
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import Integration, async_get_integration
from homeassistant.setup import async_setup_component
from homeassistant.util.yaml import SECRET_YAML
from homeassistant.util.yaml.objects import NodeDictClass
from .common import (
MockModule,
MockPlatform,
get_test_config_dir,
mock_integration,
mock_platform,
)
CONFIG_DIR = get_test_config_dir()
YAML_PATH = os.path.join(CONFIG_DIR, config_util.YAML_CONFIG_FILE)
SECRET_PATH = os.path.join(CONFIG_DIR, SECRET_YAML)
VERSION_PATH = os.path.join(CONFIG_DIR, config_util.VERSION_FILE)
AUTOMATIONS_PATH = os.path.join(CONFIG_DIR, config_util.AUTOMATION_CONFIG_PATH)
SCRIPTS_PATH = os.path.join(CONFIG_DIR, config_util.SCRIPT_CONFIG_PATH)
SCENES_PATH = os.path.join(CONFIG_DIR, config_util.SCENE_CONFIG_PATH)
SAFE_MODE_PATH = os.path.join(CONFIG_DIR, config_util.SAFE_MODE_FILENAME)
def create_file(path):
"""Create an empty file."""
with open(path, "w", encoding="utf8"):
pass
@pytest.fixture(autouse=True)
def teardown():
"""Clean up."""
yield
if os.path.isfile(YAML_PATH):
os.remove(YAML_PATH)
if os.path.isfile(SECRET_PATH):
os.remove(SECRET_PATH)
if os.path.isfile(VERSION_PATH):
os.remove(VERSION_PATH)
if os.path.isfile(AUTOMATIONS_PATH):
os.remove(AUTOMATIONS_PATH)
if os.path.isfile(SCRIPTS_PATH):
os.remove(SCRIPTS_PATH)
if os.path.isfile(SCENES_PATH):
os.remove(SCENES_PATH)
if os.path.isfile(SAFE_MODE_PATH):
os.remove(SAFE_MODE_PATH)
IOT_DOMAIN_PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend({vol.Remove("old"): str})
@pytest.fixture
async def mock_iot_domain_integration(hass: HomeAssistant) -> Integration:
"""Mock an integration which provides an IoT domain."""
comp_platform_schema = cv.PLATFORM_SCHEMA.extend({vol.Remove("old"): str})
comp_platform_schema_base = comp_platform_schema.extend({}, extra=vol.ALLOW_EXTRA)
return mock_integration(
hass,
MockModule(
"iot_domain",
platform_schema_base=comp_platform_schema_base,
platform_schema=comp_platform_schema,
),
)
@pytest.fixture
async def mock_iot_domain_integration_with_docs(hass: HomeAssistant) -> Integration:
"""Mock an integration which provides an IoT domain."""
comp_platform_schema = cv.PLATFORM_SCHEMA.extend({vol.Remove("old"): str})
comp_platform_schema_base = comp_platform_schema.extend({}, extra=vol.ALLOW_EXTRA)
return mock_integration(
hass,
MockModule(
"iot_domain",
platform_schema_base=comp_platform_schema_base,
platform_schema=comp_platform_schema,
partial_manifest={
"documentation": "https://www.home-assistant.io/integrations/iot_domain"
},
),
)
@pytest.fixture
async def mock_non_adr_0007_integration(hass: HomeAssistant) -> None:
"""Mock a non-ADR-0007 compliant integration with iot_domain platform.
The integration allows setting up iot_domain entities under the iot_domain's
configuration key
"""
test_platform_schema = IOT_DOMAIN_PLATFORM_SCHEMA.extend(
{vol.Required("option1"): str, vol.Optional("option2"): str}
)
mock_platform(
hass,
"non_adr_0007.iot_domain",
MockPlatform(platform_schema=test_platform_schema),
)
@pytest.fixture
async def mock_non_adr_0007_integration_with_docs(hass: HomeAssistant) -> None:
"""Mock a non-ADR-0007 compliant integration with iot_domain platform.
The integration allows setting up iot_domain entities under the iot_domain's
configuration key
"""
mock_integration(
hass,
MockModule(
"non_adr_0007",
partial_manifest={
"documentation": "https://www.home-assistant.io/integrations/non_adr_0007"
},
),
)
test_platform_schema = IOT_DOMAIN_PLATFORM_SCHEMA.extend(
{vol.Required("option1"): str, vol.Optional("option2"): str}
)
mock_platform(
hass,
"non_adr_0007.iot_domain",
MockPlatform(platform_schema=test_platform_schema),
)
@pytest.fixture
async def mock_adr_0007_integrations(hass: HomeAssistant) -> list[Integration]:
"""Mock ADR-0007 compliant integrations."""
integrations = []
for domain in (
"adr_0007_1",
"adr_0007_2",
"adr_0007_3",
"adr_0007_4",
"adr_0007_5",
):
adr_0007_config_schema = vol.Schema(
{
domain: vol.Schema(
{
vol.Required("host"): str,
vol.Optional("port", default=8080): int,
}
)
},
extra=vol.ALLOW_EXTRA,
)
integrations.append(
mock_integration(
hass,
MockModule(domain, config_schema=adr_0007_config_schema),
)
)
return integrations
@pytest.fixture
async def mock_adr_0007_integrations_with_docs(
hass: HomeAssistant,
) -> list[Integration]:
"""Mock ADR-0007 compliant integrations."""
integrations = []
for domain in (
"adr_0007_1",
"adr_0007_2",
"adr_0007_3",
"adr_0007_4",
"adr_0007_5",
):
adr_0007_config_schema = vol.Schema(
{
domain: vol.Schema(
{
vol.Required("host"): str,
vol.Optional("port", default=8080): int,
}
)
},
extra=vol.ALLOW_EXTRA,
)
integrations.append(
mock_integration(
hass,
MockModule(
domain,
config_schema=adr_0007_config_schema,
partial_manifest={
"documentation": f"https://www.home-assistant.io/integrations/{domain}"
},
),
)
)
return integrations
@pytest.fixture
async def mock_custom_validator_integrations(hass: HomeAssistant) -> list[Integration]:
"""Mock integrations with custom validator."""
integrations = []
for domain in ("custom_validator_ok_1", "custom_validator_ok_2"):
def gen_async_validate_config(domain):
schema = vol.Schema(
{
domain: vol.Schema(
{
vol.Required("host"): str,
vol.Optional("port", default=8080): int,
}
)
},
extra=vol.ALLOW_EXTRA,
)
async def async_validate_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return schema(config)
return async_validate_config
integrations.append(mock_integration(hass, MockModule(domain)))
mock_platform(
hass,
f"{domain}.config",
Mock(async_validate_config=gen_async_validate_config(domain)),
)
for domain, exception in (
("custom_validator_bad_1", HomeAssistantError("broken")),
("custom_validator_bad_2", ValueError("broken")),
):
integrations.append(mock_integration(hass, MockModule(domain)))
mock_platform(
hass,
f"{domain}.config",
Mock(async_validate_config=AsyncMock(side_effect=exception)),
)
@pytest.fixture
async def mock_custom_validator_integrations_with_docs(
hass: HomeAssistant,
) -> list[Integration]:
"""Mock integrations with custom validator."""
integrations = []
for domain in ("custom_validator_ok_1", "custom_validator_ok_2"):
def gen_async_validate_config(domain):
schema = vol.Schema(
{
domain: vol.Schema(
{
vol.Required("host"): str,
vol.Optional("port", default=8080): int,
}
)
},
extra=vol.ALLOW_EXTRA,
)
async def async_validate_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return schema(config)
return async_validate_config
integrations.append(
mock_integration(
hass,
MockModule(
domain,
partial_manifest={
"documentation": f"https://www.home-assistant.io/integrations/{domain}"
},
),
)
)
mock_platform(
hass,
f"{domain}.config",
Mock(async_validate_config=gen_async_validate_config(domain)),
)
for domain, exception in (
("custom_validator_bad_1", HomeAssistantError("broken")),
("custom_validator_bad_2", ValueError("broken")),
):
integrations.append(
mock_integration(
hass,
MockModule(
domain,
partial_manifest={
"documentation": f"https://www.home-assistant.io/integrations/{domain}"
},
),
)
)
mock_platform(
hass,
f"{domain}.config",
Mock(async_validate_config=AsyncMock(side_effect=exception)),
)
class ConfigTestClass(NodeDictClass):
"""Test class for config with wrapper."""
__line__ = 140
__config_file__ = "configuration.yaml"
async def test_create_default_config(hass: HomeAssistant) -> None:
"""Test creation of default config."""
assert not os.path.isfile(YAML_PATH)
assert not os.path.isfile(SECRET_PATH)
assert not os.path.isfile(VERSION_PATH)
assert not os.path.isfile(AUTOMATIONS_PATH)
await config_util.async_create_default_config(hass)
assert os.path.isfile(YAML_PATH)
assert os.path.isfile(SECRET_PATH)
assert os.path.isfile(VERSION_PATH)
assert os.path.isfile(AUTOMATIONS_PATH)
async def test_ensure_config_exists_creates_config(hass: HomeAssistant) -> None:
"""Test that calling ensure_config_exists.
If not creates a new config file.
"""
assert not os.path.isfile(YAML_PATH)
with patch("builtins.print") as mock_print:
await config_util.async_ensure_config_exists(hass)
assert os.path.isfile(YAML_PATH)
assert mock_print.called
async def test_ensure_config_exists_uses_existing_config(hass: HomeAssistant) -> None:
"""Test that calling ensure_config_exists uses existing config."""
await hass.async_add_executor_job(create_file, YAML_PATH)
await config_util.async_ensure_config_exists(hass)
content = await hass.async_add_executor_job(Path(YAML_PATH).read_text)
# File created with create_file are empty
assert content == ""
async def test_ensure_existing_files_is_not_overwritten(hass: HomeAssistant) -> None:
"""Test that calling async_create_default_config does not overwrite existing files."""
await hass.async_add_executor_job(create_file, SECRET_PATH)
await config_util.async_create_default_config(hass)
content = await hass.async_add_executor_job(Path(SECRET_PATH).read_text)
# File created with create_file are empty
assert content == ""
def test_load_yaml_config_converts_empty_files_to_dict() -> None:
"""Test that loading an empty file returns an empty dict."""
create_file(YAML_PATH)
assert isinstance(config_util.load_yaml_config_file(YAML_PATH), dict)
def test_load_yaml_config_raises_error_if_not_dict() -> None:
"""Test error raised when YAML file is not a dict."""
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("5")
with pytest.raises(HomeAssistantError):
config_util.load_yaml_config_file(YAML_PATH)
def test_load_yaml_config_raises_error_if_malformed_yaml() -> None:
"""Test error raised if invalid YAML."""
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write(":-")
with pytest.raises(HomeAssistantError):
config_util.load_yaml_config_file(YAML_PATH)
def test_load_yaml_config_raises_error_if_unsafe_yaml() -> None:
"""Test error raised if unsafe YAML."""
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("- !!python/object/apply:os.system []")
with (
patch.object(os, "system") as system_mock,
contextlib.suppress(HomeAssistantError),
):
config_util.load_yaml_config_file(YAML_PATH)
assert len(system_mock.mock_calls) == 0
# Here we validate that the test above is a good test
# since previously the syntax was not valid
with (
open(YAML_PATH, encoding="utf8") as fp,
patch.object(os, "system") as system_mock,
):
list(yaml.unsafe_load_all(fp))
assert len(system_mock.mock_calls) == 1
def test_load_yaml_config_preserves_key_order() -> None:
"""Test removal of library."""
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("hello: 2\n")
fp.write("world: 1\n")
assert list(config_util.load_yaml_config_file(YAML_PATH).items()) == [
("hello", 2),
("world", 1),
]
async def test_create_default_config_returns_none_if_write_error(
hass: HomeAssistant,
) -> None:
"""Test the writing of a default configuration.
Non existing folder returns None.
"""
hass.config.config_dir = os.path.join(CONFIG_DIR, "non_existing_dir/")
with patch("builtins.print") as mock_print:
assert await config_util.async_create_default_config(hass) is False
assert mock_print.called
@patch("homeassistant.config.shutil")
@patch("homeassistant.config.os")
@patch("homeassistant.config.is_docker_env", return_value=False)
def test_remove_lib_on_upgrade(
mock_docker, mock_os, mock_shutil, hass: HomeAssistant
) -> None:
"""Test removal of library on upgrade from before 0.50."""
ha_version = "0.49.0"
mock_os.path.isdir = mock.Mock(return_value=True)
mock_open = mock.mock_open()
with patch("homeassistant.config.open", mock_open, create=True):
opened_file = mock_open.return_value
opened_file.readline.return_value = ha_version
hass.config.path = mock.Mock()
config_util.process_ha_config_upgrade(hass)
hass_path = hass.config.path.return_value
assert mock_os.path.isdir.call_count == 1
assert mock_os.path.isdir.call_args == mock.call(hass_path)
assert mock_shutil.rmtree.call_count == 1
assert mock_shutil.rmtree.call_args == mock.call(hass_path)
@patch("homeassistant.config.shutil")
@patch("homeassistant.config.os")
@patch("homeassistant.config.is_docker_env", return_value=True)
def test_remove_lib_on_upgrade_94(
mock_docker, mock_os, mock_shutil, hass: HomeAssistant
) -> None:
"""Test removal of library on upgrade from before 0.94 and in Docker."""
ha_version = "0.93.0.dev0"
mock_os.path.isdir = mock.Mock(return_value=True)
mock_open = mock.mock_open()
with patch("homeassistant.config.open", mock_open, create=True):
opened_file = mock_open.return_value
opened_file.readline.return_value = ha_version
hass.config.path = mock.Mock()
config_util.process_ha_config_upgrade(hass)
hass_path = hass.config.path.return_value
assert mock_os.path.isdir.call_count == 1
assert mock_os.path.isdir.call_args == mock.call(hass_path)
assert mock_shutil.rmtree.call_count == 1
assert mock_shutil.rmtree.call_args == mock.call(hass_path)
def test_process_config_upgrade(hass: HomeAssistant) -> None:
"""Test update of version on upgrade."""
ha_version = "0.92.0"
mock_open = mock.mock_open()
with (
patch("homeassistant.config.open", mock_open, create=True),
patch.object(config_util, "__version__", "0.91.0"),
):
opened_file = mock_open.return_value
opened_file.readline.return_value = ha_version
config_util.process_ha_config_upgrade(hass)
assert opened_file.write.call_count == 1
assert opened_file.write.call_args == mock.call("0.91.0")
def test_config_upgrade_same_version(hass: HomeAssistant) -> None:
"""Test no update of version on no upgrade."""
ha_version = __version__
mock_open = mock.mock_open()
with patch("homeassistant.config.open", mock_open, create=True):
opened_file = mock_open.return_value
opened_file.readline.return_value = ha_version
config_util.process_ha_config_upgrade(hass)
assert opened_file.write.call_count == 0
def test_config_upgrade_no_file(hass: HomeAssistant) -> None:
"""Test update of version on upgrade, with no version file."""
mock_open = mock.mock_open()
mock_open.side_effect = [FileNotFoundError(), mock.DEFAULT, mock.DEFAULT]
with patch("homeassistant.config.open", mock_open, create=True):
opened_file = mock_open.return_value
config_util.process_ha_config_upgrade(hass)
assert opened_file.write.call_count == 1
assert opened_file.write.call_args == mock.call(__version__)
@patch("homeassistant.helpers.check_config.async_check_ha_config_file")
async def test_check_ha_config_file_correct(mock_check, hass: HomeAssistant) -> None:
"""Check that restart propagates to stop."""
mock_check.return_value = check_config.HomeAssistantConfig()
assert await config_util.async_check_ha_config_file(hass) is None
@patch("homeassistant.helpers.check_config.async_check_ha_config_file")
async def test_check_ha_config_file_wrong(mock_check, hass: HomeAssistant) -> None:
"""Check that restart with a bad config doesn't propagate to stop."""
mock_check.return_value = check_config.HomeAssistantConfig()
mock_check.return_value.add_error("bad")
assert await config_util.async_check_ha_config_file(hass) == "bad"
@pytest.mark.parametrize(
"hass_config",
[
{
HOMEASSISTANT_DOMAIN: {
CONF_PACKAGES: {"pack_dict": {"input_boolean": {"ib1": None}}}
},
"input_boolean": {"ib2": None},
"light": {"platform": "test"},
}
],
)
@pytest.mark.usefixtures("mock_hass_config")
async def test_async_hass_config_yaml_merge(
merge_log_err: MagicMock, hass: HomeAssistant
) -> None:
"""Test merge during async config reload."""
conf = await config_util.async_hass_config_yaml(hass)
assert merge_log_err.call_count == 0
assert conf[HOMEASSISTANT_DOMAIN].get(CONF_PACKAGES) is not None
assert len(conf) == 3
assert len(conf["input_boolean"]) == 2
assert len(conf["light"]) == 1
@pytest.fixture
def merge_log_err() -> Generator[MagicMock]:
"""Patch _merge_log_error from packages."""
with patch("homeassistant.config._LOGGER.error") as logerr:
yield logerr
async def test_merge(merge_log_err: MagicMock, hass: HomeAssistant) -> None:
"""Test if we can merge packages."""
packages = {
"pack_dict": {"input_boolean": {"ib1": None}},
"pack_11": {"input_select": {"is1": None}},
"pack_list": {"light": {"platform": "test"}},
"pack_list2": {"light": [{"platform": "test"}]},
"pack_none": {"wake_on_lan": None},
"pack_special": {
"automation": [{"some": "yay"}],
"script": {"a_script": "yay"},
"template": [{"some": "yay"}],
},
}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"input_boolean": {"ib2": None},
"light": {"platform": "test"},
"automation": [],
"script": {},
"template": [],
}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 0
assert len(config) == 8
assert len(config["input_boolean"]) == 2
assert len(config["input_select"]) == 1
assert len(config["light"]) == 3
assert len(config["automation"]) == 1
assert len(config["script"]) == 1
assert len(config["template"]) == 1
assert isinstance(config["wake_on_lan"], OrderedDict)
async def test_merge_try_falsy(merge_log_err: MagicMock, hass: HomeAssistant) -> None:
"""Ensure we don't add falsy items like empty OrderedDict() to list."""
packages = {
"pack_falsy_to_lst": {"automation": OrderedDict()},
"pack_list2": {"light": OrderedDict()},
}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"automation": {"do": "something"},
"light": {"some": "light"},
}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 0
assert len(config) == 3
assert len(config["automation"]) == 1
assert len(config["light"]) == 1
async def test_merge_new(merge_log_err: MagicMock, hass: HomeAssistant) -> None:
"""Test adding new components to outer scope."""
packages = {
"pack_1": {"light": [{"platform": "one"}]},
"pack_11": {"input_select": {"ib1": None}},
"pack_2": {
"light": {"platform": "one"},
"panel_custom": {"pan1": None},
"api": {},
},
}
config = {HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages}}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 0
assert "api" in config
assert len(config) == 5
assert len(config["light"]) == 2
assert len(config["panel_custom"]) == 1
async def test_merge_type_mismatch(
merge_log_err: MagicMock, hass: HomeAssistant
) -> None:
"""Test if we have a type mismatch for packages."""
packages = {
"pack_1": {"input_boolean": [{"ib1": None}]},
"pack_11": {"input_select": {"ib1": None}},
"pack_2": {"light": {"ib1": None}}, # light gets merged - ensure_list
}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"input_boolean": {"ib2": None},
"input_select": [{"ib2": None}],
"light": [{"platform": "two"}],
}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 2
assert len(config) == 4
assert len(config["input_boolean"]) == 1
assert len(config["light"]) == 2
async def test_merge_once_only_keys(
merge_log_err: MagicMock, hass: HomeAssistant
) -> None:
"""Test if we have a merge for a comp that may occur only once. Keys."""
packages = {"pack_2": {"api": None}}
config = {HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages}, "api": None}
await config_util.merge_packages_config(hass, config, packages)
assert config["api"] == OrderedDict()
packages = {"pack_2": {"api": {"key_3": 3}}}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"api": {"key_1": 1, "key_2": 2},
}
await config_util.merge_packages_config(hass, config, packages)
assert config["api"] == {"key_1": 1, "key_2": 2, "key_3": 3}
# Duplicate keys error
packages = {"pack_2": {"api": {"key": 2}}}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"api": {"key": 1},
}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 1
async def test_merge_once_only_lists(hass: HomeAssistant) -> None:
"""Test if we have a merge for a comp that may occur only once. Lists."""
packages = {
"pack_2": {
"api": {"list_1": ["item_2", "item_3"], "list_2": ["item_4"], "list_3": []}
}
}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"api": {"list_1": ["item_1"]},
}
await config_util.merge_packages_config(hass, config, packages)
assert config["api"] == {
"list_1": ["item_1", "item_2", "item_3"],
"list_2": ["item_4"],
"list_3": [],
}
async def test_merge_once_only_dictionaries(hass: HomeAssistant) -> None:
"""Test if we have a merge for a comp that may occur only once. Dicts."""
packages = {
"pack_2": {
"api": {
"dict_1": {"key_2": 2, "dict_1.1": {"key_1.2": 1.2}},
"dict_2": {"key_1": 1},
"dict_3": {},
}
}
}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"api": {"dict_1": {"key_1": 1, "dict_1.1": {"key_1.1": 1.1}}},
}
await config_util.merge_packages_config(hass, config, packages)
assert config["api"] == {
"dict_1": {
"key_1": 1,
"key_2": 2,
"dict_1.1": {"key_1.1": 1.1, "key_1.2": 1.2},
},
"dict_2": {"key_1": 1},
}
async def test_merge_id_schema(hass: HomeAssistant) -> None:
"""Test if we identify the config schemas correctly."""
types = {
"panel_custom": "list",
"group": "dict",
"input_boolean": "dict",
"shell_command": "dict",
"qwikswitch": "dict",
}
for domain, expected_type in types.items():
integration = await async_get_integration(hass, domain)
module = integration.get_component()
typ = config_util._identify_config_schema(module)
assert typ == expected_type, f"{domain} expected {expected_type}, got {typ}"
async def test_merge_duplicate_keys(
merge_log_err: MagicMock, hass: HomeAssistant
) -> None:
"""Test if keys in dicts are duplicates."""
packages = {"pack_1": {"input_select": {"ib1": None}}}
config = {
HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages},
"input_select": {"ib1": 1},
}
await config_util.merge_packages_config(hass, config, packages)
assert merge_log_err.call_count == 1
assert len(config) == 2
assert len(config["input_select"]) == 1
async def test_merge_split_component_definition(hass: HomeAssistant) -> None:
"""Test components with trailing description in packages are merged."""
packages = {
"pack_1": {"light one": {"l1": None}},
"pack_2": {"light two": {"l2": None}, "light three": {"l3": None}},
}
config = {HOMEASSISTANT_DOMAIN: {CONF_PACKAGES: packages}}
await config_util.merge_packages_config(hass, config, packages)
assert len(config) == 4
assert len(config["light one"]) == 1
assert len(config["light two"]) == 1
assert len(config["light three"]) == 1
async def test_component_config_exceptions(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unexpected exceptions validating component config."""
# Create test config with embedded info
test_config = ConfigTestClass({"test_domain": {}})
test_platform_config = ConfigTestClass(
{"test_domain": {"platform": "test_platform"}}
)
test_multi_platform_config = ConfigTestClass(
{
"test_domain": [
{"platform": "test_platform1"},
{"platform": "test_platform2"},
]
},
)
# Make sure the exception translation cache is loaded
await async_setup_component(hass, "homeassistant", {})
test_integration = Mock(
domain="test_domain",
async_get_component=AsyncMock(),
async_get_platform=AsyncMock(
return_value=Mock(
async_validate_config=AsyncMock(side_effect=ValueError("broken"))
)
),
)
assert (
await config_util.async_process_component_and_handle_errors(
hass, test_config, integration=test_integration
)
is None
)
assert "ValueError: broken" in caplog.text
assert "Unknown error calling test_domain config validator" in caplog.text
caplog.clear()
with pytest.raises(HomeAssistantError) as ex:
await config_util.async_process_component_and_handle_errors(
hass, test_config, integration=test_integration, raise_on_failure=True
)
assert "ValueError: broken" in caplog.text
assert "Unknown error calling test_domain config validator" in caplog.text
assert (
str(ex.value) == "Unknown error calling test_domain config validator - broken"
)
test_integration = Mock(
domain="test_domain",
async_get_platform=AsyncMock(
return_value=Mock(
async_validate_config=AsyncMock(
side_effect=HomeAssistantError("broken")
)
)
),
async_get_component=AsyncMock(return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])),
)
caplog.clear()
assert (
await config_util.async_process_component_and_handle_errors(
hass, test_config, integration=test_integration, raise_on_failure=False
)
is None
)
assert (
"Invalid config for 'test_domain' at ../../configuration.yaml, "
"line 140: broken, please check the docs at" in caplog.text
)
with pytest.raises(HomeAssistantError) as ex:
await config_util.async_process_component_and_handle_errors(
hass, test_config, integration=test_integration, raise_on_failure=True
)
assert (
str(ex.value)
== "Invalid config for integration test_domain at configuration.yaml, "
"line 140: broken"
)
# component.CONFIG_SCHEMA
caplog.clear()
test_integration = Mock(
domain="test_domain",
async_get_platform=AsyncMock(return_value=None),
async_get_component=AsyncMock(
return_value=Mock(CONFIG_SCHEMA=Mock(side_effect=ValueError("broken")))
),
)
assert (
await config_util.async_process_component_and_handle_errors(
hass,
test_config,
integration=test_integration,
raise_on_failure=False,
)
is None
)
assert "Unknown error calling test_domain CONFIG_SCHEMA" in caplog.text
caplog.clear()
with pytest.raises(HomeAssistantError) as ex:
await config_util.async_process_component_and_handle_errors(
hass,
test_config,
integration=test_integration,
raise_on_failure=True,
)
assert "Unknown error calling test_domain CONFIG_SCHEMA" in caplog.text
assert str(ex.value) == "Unknown error calling test_domain CONFIG_SCHEMA - broken"
# component.PLATFORM_SCHEMA
caplog.clear()
test_integration = Mock(
domain="test_domain",
async_get_platform=AsyncMock(return_value=None),
async_get_component=AsyncMock(
return_value=Mock(
spec=["PLATFORM_SCHEMA_BASE"],
PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")),
)
),
)
assert await config_util.async_process_component_and_handle_errors(
hass,
test_platform_config,
integration=test_integration,
raise_on_failure=False,
) == {"test_domain": []}
assert "ValueError: broken" in caplog.text
assert (
"Unknown error when validating config for test_domain "
"from integration test_platform - broken"
) in caplog.text
caplog.clear()
with pytest.raises(HomeAssistantError) as ex:
await config_util.async_process_component_and_handle_errors(
hass,
test_platform_config,
integration=test_integration,
raise_on_failure=True,
)
assert (
"Unknown error when validating config for test_domain "
"from integration test_platform - broken"
) in caplog.text
assert str(ex.value) == (
"Unknown error when validating config for test_domain "
"from integration test_platform - broken"
)
# platform.PLATFORM_SCHEMA
caplog.clear()
test_integration = Mock(
domain="test_domain",
async_get_platform=AsyncMock(return_value=None),
async_get_component=AsyncMock(return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])),
)
with patch(
"homeassistant.config.async_get_integration_with_requirements",
return_value=Mock( # integration that owns platform
async_get_platform=AsyncMock(
return_value=Mock( # platform
PLATFORM_SCHEMA=Mock(side_effect=ValueError("broken"))
)
)