forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_instance_id.py
85 lines (63 loc) · 2.41 KB
/
test_instance_id.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
"""Tests for instance ID helper."""
from json import JSONDecodeError
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.helpers import instance_id
async def test_get_id_empty(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None:
"""Get unique ID."""
uuid = await instance_id.async_get(hass)
assert uuid is not None
# Assert it's stored
assert hass_storage["core.uuid"]["data"]["uuid"] == uuid
async def test_get_id_load_fail(
hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
) -> None:
"""Migrate existing file with error."""
hass_storage["core.uuid"] = None # Invalid, will make store.async_load raise
uuid = await instance_id.async_get(hass)
assert uuid is not None
# Assert it's stored
assert hass_storage["core.uuid"]["data"]["uuid"] == uuid
assert (
"Could not read hass instance ID from 'core.uuid' or '.uuid', a "
"new instance ID will be generated" in caplog.text
)
async def test_get_id_migrate(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Migrate existing file."""
with (
patch("homeassistant.util.json.load_json", return_value={"uuid": "1234"}),
patch("os.path.isfile", return_value=True),
patch("os.remove") as mock_remove,
):
uuid = await instance_id.async_get(hass)
assert uuid == "1234"
# Assert it's stored
assert hass_storage["core.uuid"]["data"]["uuid"] == uuid
# assert old deleted
assert len(mock_remove.mock_calls) == 1
async def test_get_id_migrate_fail(
hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
) -> None:
"""Migrate existing file with error."""
with (
patch(
"homeassistant.util.json.load_json",
side_effect=JSONDecodeError("test_error", "test", 1),
),
patch("os.path.isfile", return_value=True),
patch("os.remove") as mock_remove,
):
uuid = await instance_id.async_get(hass)
assert uuid is not None
# Assert it's stored
assert hass_storage["core.uuid"]["data"]["uuid"] == uuid
# assert old not deleted
assert len(mock_remove.mock_calls) == 0
assert (
"Could not read hass instance ID from 'core.uuid' or '.uuid', a "
"new instance ID will be generated" in caplog.text
)