python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. kasa/__init__.py +90 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +414 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +16 -9
  8. kasa/discover.py +100 -81
  9. kasa/emeterstatus.py +7 -5
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +201 -0
  12. kasa/httpclient.py +21 -14
  13. kasa/interfaces/__init__.py +16 -0
  14. kasa/interfaces/fan.py +20 -0
  15. kasa/interfaces/led.py +38 -0
  16. kasa/interfaces/light.py +138 -0
  17. kasa/interfaces/lighteffect.py +80 -0
  18. kasa/interfaces/lightpreset.py +76 -0
  19. kasa/iot/__init__.py +18 -0
  20. kasa/{effects.py → iot/effects.py} +4 -2
  21. kasa/{smartbulb.py → iot/iotbulb.py} +103 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +176 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +45 -33
  24. kasa/iot/iotlightstrip.py +71 -0
  25. kasa/{modules/module.py → iot/iotmodule.py} +22 -42
  26. kasa/iot/iotplug.py +94 -0
  27. kasa/{smartstrip.py → iot/iotstrip.py} +57 -75
  28. kasa/{modules → iot/modules}/__init__.py +10 -2
  29. kasa/{modules → iot/modules}/ambientlight.py +31 -3
  30. kasa/{modules → iot/modules}/antitheft.py +1 -0
  31. kasa/{modules → iot/modules}/cloud.py +25 -6
  32. kasa/{modules → iot/modules}/countdown.py +1 -0
  33. kasa/iot/modules/emeter.py +210 -0
  34. kasa/iot/modules/led.py +32 -0
  35. kasa/iot/modules/light.py +263 -0
  36. kasa/iot/modules/lighteffect.py +122 -0
  37. kasa/iot/modules/lightpreset.py +151 -0
  38. kasa/{modules → iot/modules}/motion.py +8 -8
  39. kasa/{modules → iot/modules}/rulemodule.py +11 -12
  40. kasa/{modules → iot/modules}/schedule.py +1 -0
  41. kasa/{modules → iot/modules}/time.py +5 -4
  42. kasa/{modules → iot/modules}/usage.py +10 -8
  43. kasa/iotprotocol.py +22 -20
  44. kasa/klaptransport.py +25 -15
  45. kasa/module.py +136 -0
  46. kasa/modulemapping.py +25 -0
  47. kasa/modulemapping.pyi +96 -0
  48. kasa/protocol.py +6 -4
  49. kasa/smart/__init__.py +6 -0
  50. kasa/smart/effects.py +429 -0
  51. kasa/smart/modules/__init__.py +57 -0
  52. kasa/smart/modules/alarm.py +142 -0
  53. kasa/smart/modules/autooff.py +96 -0
  54. kasa/smart/modules/batterysensor.py +54 -0
  55. kasa/smart/modules/brightness.py +66 -0
  56. kasa/smart/modules/childdevice.py +10 -0
  57. kasa/smart/modules/cloud.py +42 -0
  58. kasa/smart/modules/color.py +96 -0
  59. kasa/smart/modules/colortemperature.py +78 -0
  60. kasa/smart/modules/contactsensor.py +42 -0
  61. kasa/smart/modules/devicemodule.py +22 -0
  62. kasa/smart/modules/energy.py +101 -0
  63. kasa/smart/modules/fan.py +80 -0
  64. kasa/smart/modules/firmware.py +216 -0
  65. kasa/smart/modules/frostprotection.py +59 -0
  66. kasa/smart/modules/humiditysensor.py +55 -0
  67. kasa/smart/modules/led.py +49 -0
  68. kasa/smart/modules/light.py +166 -0
  69. kasa/smart/modules/lighteffect.py +115 -0
  70. kasa/smart/modules/lightpreset.py +142 -0
  71. kasa/smart/modules/lightstripeffect.py +135 -0
  72. kasa/smart/modules/lighttransition.py +183 -0
  73. kasa/smart/modules/reportmode.py +36 -0
  74. kasa/smart/modules/temperaturecontrol.py +177 -0
  75. kasa/smart/modules/temperaturesensor.py +77 -0
  76. kasa/smart/modules/time.py +57 -0
  77. kasa/smart/modules/waterleaksensor.py +66 -0
  78. kasa/smart/smartchilddevice.py +65 -0
  79. kasa/smart/smartdevice.py +653 -0
  80. kasa/smart/smartmodule.py +112 -0
  81. kasa/smartprotocol.py +107 -41
  82. kasa/tests/conftest.py +27 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  87. kasa/tests/fixtureinfo.py +154 -0
  88. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  89. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  90. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  91. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  92. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  93. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  94. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  95. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  96. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  97. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  98. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +116 -86
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +242 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +42 -33
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev1.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/entry_points.txt +0 -0
@@ -1,337 +1,229 @@
1
- import inspect
2
- import re
3
- from datetime import datetime
4
- from unittest.mock import Mock, patch
5
-
6
- import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342
7
- from voluptuous import (
8
- REMOVE_EXTRA,
9
- All,
10
- Any,
11
- Boolean,
12
- In,
13
- Invalid,
14
- Optional,
15
- Range,
16
- Schema,
17
- )
1
+ """Tests for SMART devices."""
18
2
 
19
- import kasa
20
- from kasa import Credentials, DeviceConfig, SmartDevice, SmartDeviceException
3
+ from __future__ import annotations
21
4
 
22
- from .conftest import device_iot, handle_turn_on, has_emeter_iot, no_emeter_iot, turn_on
23
- from .fakeprotocol_iot import FakeIotProtocol
5
+ import logging
6
+ from typing import Any
7
+ from unittest.mock import patch
24
8
 
25
- # List of all SmartXXX classes including the SmartDevice base class
26
- smart_device_classes = [
27
- dc
28
- for (mn, dc) in inspect.getmembers(
29
- kasa,
30
- lambda member: inspect.isclass(member)
31
- and (member == SmartDevice or issubclass(member, SmartDevice)),
32
- )
33
- ]
9
+ import pytest
10
+ from pytest_mock import MockerFixture
34
11
 
12
+ from kasa import KasaException, Module
13
+ from kasa.exceptions import SmartErrorCode
14
+ from kasa.smart import SmartDevice
35
15
 
36
- @device_iot
37
- async def test_state_info(dev):
38
- assert isinstance(dev.state_information, dict)
16
+ from .conftest import (
17
+ device_smart,
18
+ get_device_for_fixture_protocol,
19
+ )
39
20
 
40
21
 
41
- @pytest.mark.requires_dummy
42
- @device_iot
43
- async def test_invalid_connection(dev):
44
- with patch.object(
45
- FakeIotProtocol, "query", side_effect=SmartDeviceException
46
- ), pytest.raises(SmartDeviceException):
22
+ @device_smart
23
+ async def test_try_get_response(dev: SmartDevice, caplog):
24
+ mock_response: dict = {
25
+ "get_device_info": SmartErrorCode.PARAMS_ERROR,
26
+ }
27
+ caplog.set_level(logging.DEBUG)
28
+ dev._try_get_response(mock_response, "get_device_info", {})
29
+ msg = "Error PARAMS_ERROR(-1008) getting request get_device_info for device 127.0.0.123"
30
+ assert msg in caplog.text
31
+
32
+
33
+ @device_smart
34
+ async def test_update_no_device_info(dev: SmartDevice, mocker: MockerFixture):
35
+ mock_response: dict = {
36
+ "get_device_usage": {},
37
+ "get_device_time": {},
38
+ }
39
+ msg = f"get_device_info not found in {mock_response} for device 127.0.0.123"
40
+ with mocker.patch.object(
41
+ dev.protocol, "query", return_value=mock_response
42
+ ), pytest.raises(KasaException, match=msg):
47
43
  await dev.update()
48
44
 
49
45
 
50
- @has_emeter_iot
51
- async def test_initial_update_emeter(dev, mocker):
52
- """Test that the initial update performs second query if emeter is available."""
53
- dev._last_update = None
54
- dev._features = set()
55
- spy = mocker.spy(dev.protocol, "query")
56
- await dev.update()
57
- # Devices with small buffers may require 3 queries
58
- expected_queries = 2 if dev.max_device_response_size > 4096 else 3
59
- assert spy.call_count == expected_queries + len(dev.children)
46
+ @device_smart
47
+ async def test_initial_update(dev: SmartDevice, mocker: MockerFixture):
48
+ """Test the initial update cycle."""
49
+ # As the fixture data is already initialized, we reset the state for testing
50
+ dev._components_raw = None
51
+ dev._components = {}
52
+ dev._modules = {}
53
+ dev._features = {}
54
+ dev._children = {}
60
55
 
56
+ negotiate = mocker.spy(dev, "_negotiate")
57
+ initialize_modules = mocker.spy(dev, "_initialize_modules")
58
+ initialize_features = mocker.spy(dev, "_initialize_features")
61
59
 
62
- @no_emeter_iot
63
- async def test_initial_update_no_emeter(dev, mocker):
64
- """Test that the initial update performs second query if emeter is available."""
65
- dev._last_update = None
66
- dev._features = set()
67
- spy = mocker.spy(dev.protocol, "query")
60
+ # Perform two updates and verify that initialization is only done once
68
61
  await dev.update()
69
- # 2 calls are necessary as some devices crash on unexpected modules
70
- # See #105, #120, #161
71
- assert spy.call_count == 2
72
-
73
-
74
- @device_iot
75
- async def test_query_helper(dev):
76
- with pytest.raises(SmartDeviceException):
77
- await dev._query_helper("test", "testcmd", {})
78
- # TODO check for unwrapping?
79
-
80
-
81
- @device_iot
82
- @turn_on
83
- async def test_state(dev, turn_on):
84
- await handle_turn_on(dev, turn_on)
85
- orig_state = dev.is_on
86
- if orig_state:
87
- await dev.turn_off()
88
- await dev.update()
89
- assert not dev.is_on
90
- assert dev.is_off
91
-
92
- await dev.turn_on()
93
- await dev.update()
94
- assert dev.is_on
95
- assert not dev.is_off
96
- else:
97
- await dev.turn_on()
98
- await dev.update()
99
- assert dev.is_on
100
- assert not dev.is_off
101
-
102
- await dev.turn_off()
103
- await dev.update()
104
- assert not dev.is_on
105
- assert dev.is_off
106
-
107
-
108
- @device_iot
109
- async def test_alias(dev):
110
- test_alias = "TEST1234"
111
- original = dev.alias
112
-
113
- assert isinstance(original, str)
114
- await dev.set_alias(test_alias)
115
- await dev.update()
116
- assert dev.alias == test_alias
117
-
118
- await dev.set_alias(original)
119
62
  await dev.update()
120
- assert dev.alias == original
121
-
122
-
123
- @device_iot
124
- @turn_on
125
- async def test_on_since(dev, turn_on):
126
- await handle_turn_on(dev, turn_on)
127
- orig_state = dev.is_on
128
- if "on_time" not in dev.sys_info and not dev.is_strip:
129
- assert dev.on_since is None
130
- elif orig_state:
131
- assert isinstance(dev.on_since, datetime)
132
- else:
133
- assert dev.on_since is None
134
-
135
-
136
- @device_iot
137
- async def test_time(dev):
138
- assert isinstance(await dev.get_time(), datetime)
139
-
140
-
141
- @device_iot
142
- async def test_timezone(dev):
143
- TZ_SCHEMA(await dev.get_timezone())
144
-
145
-
146
- @device_iot
147
- async def test_hw_info(dev):
148
- SYSINFO_SCHEMA(dev.hw_info)
149
-
150
-
151
- @device_iot
152
- async def test_location(dev):
153
- SYSINFO_SCHEMA(dev.location)
154
-
155
-
156
- @device_iot
157
- async def test_rssi(dev):
158
- SYSINFO_SCHEMA({"rssi": dev.rssi}) # wrapping for vol
159
-
160
-
161
- @device_iot
162
- async def test_mac(dev):
163
- SYSINFO_SCHEMA({"mac": dev.mac}) # wrapping for val
164
-
165
-
166
- @device_iot
167
- async def test_representation(dev):
168
- import re
169
-
170
- pattern = re.compile("<.* model .* at .* (.*), is_on: .* - dev specific: .*>")
171
- assert pattern.match(str(dev))
172
-
173
-
174
- @device_iot
175
- async def test_childrens(dev):
176
- """Make sure that children property is exposed by every device."""
177
- if dev.is_strip:
178
- assert len(dev.children) > 0
179
- else:
180
- assert len(dev.children) == 0
181
-
182
-
183
- @device_iot
184
- async def test_children(dev):
185
- """Make sure that children property is exposed by every device."""
186
- if dev.is_strip:
187
- assert len(dev.children) > 0
188
- assert dev.has_children is True
189
- else:
190
- assert len(dev.children) == 0
191
- assert dev.has_children is False
192
-
193
-
194
- @device_iot
195
- async def test_internal_state(dev):
196
- """Make sure the internal state returns the last update results."""
197
- assert dev.internal_state == dev._last_update
198
-
199
-
200
- @device_iot
201
- async def test_features(dev):
202
- """Make sure features is always accessible."""
203
- sysinfo = dev._last_update["system"]["get_sysinfo"]
204
- if "feature" in sysinfo:
205
- assert dev.features == set(sysinfo["feature"].split(":"))
206
- else:
207
- assert dev.features == set()
208
-
209
-
210
- @device_iot
211
- async def test_max_device_response_size(dev):
212
- """Make sure every device return has a set max response size."""
213
- assert dev.max_device_response_size > 0
214
-
215
-
216
- @device_iot
217
- async def test_estimated_response_sizes(dev):
218
- """Make sure every module has an estimated response size set."""
219
- for mod in dev.modules.values():
220
- assert mod.estimated_query_response_size > 0
221
-
222
-
223
- @pytest.mark.parametrize("device_class", smart_device_classes)
224
- def test_device_class_ctors(device_class):
225
- """Make sure constructor api not broken for new and existing SmartDevices."""
226
- host = "127.0.0.2"
227
- port = 1234
228
- credentials = Credentials("foo", "bar")
229
- config = DeviceConfig(host, port_override=port, credentials=credentials)
230
- dev = device_class(host, config=config)
231
- assert dev.host == host
232
- assert dev.port == port
233
- assert dev.credentials == credentials
234
63
 
64
+ negotiate.assert_called_once()
65
+ assert dev._components_raw is not None
66
+ initialize_modules.assert_called_once()
67
+ assert dev.modules
68
+ initialize_features.assert_called_once()
69
+ assert dev.features
70
+
71
+
72
+ @device_smart
73
+ async def test_negotiate(dev: SmartDevice, mocker: MockerFixture):
74
+ """Test that the initial negotiation performs expected steps."""
75
+ # As the fixture data is already initialized, we reset the state for testing
76
+ dev._components_raw = None
77
+ dev._children = {}
78
+
79
+ query = mocker.spy(dev.protocol, "query")
80
+ initialize_children = mocker.spy(dev, "_initialize_children")
81
+ await dev._negotiate()
82
+
83
+ # Check that we got the initial negotiation call
84
+ query.assert_any_call(
85
+ {
86
+ "component_nego": None,
87
+ "get_device_info": None,
88
+ "get_connect_cloud_state": None,
89
+ }
90
+ )
91
+ assert dev._components_raw
92
+
93
+ # Check the children are created, if device supports them
94
+ if "child_device" in dev._components:
95
+ initialize_children.assert_called_once()
96
+ query.assert_any_call(
97
+ {
98
+ "get_child_device_component_list": None,
99
+ "get_child_device_list": None,
100
+ }
101
+ )
102
+ assert len(dev._children) == dev.internal_state["get_child_device_list"]["sum"]
103
+
104
+
105
+ @device_smart
106
+ async def test_update_module_queries(dev: SmartDevice, mocker: MockerFixture):
107
+ """Test that the regular update uses queries from all supported modules."""
108
+ # We need to have some modules initialized by now
109
+ assert dev._modules
110
+
111
+ device_queries: dict[SmartDevice, dict[str, Any]] = {}
112
+ for mod in dev._modules.values():
113
+ device_queries.setdefault(mod._device, {}).update(mod.query())
114
+
115
+ spies = {}
116
+ for device in device_queries:
117
+ spies[device] = mocker.spy(device.protocol, "query")
235
118
 
236
- @device_iot
237
- async def test_modules_preserved(dev: SmartDevice):
238
- """Make modules that are not being updated are preserved between updates."""
239
- dev._last_update["some_module_not_being_updated"] = "should_be_kept"
240
119
  await dev.update()
241
- assert dev._last_update["some_module_not_being_updated"] == "should_be_kept"
242
-
120
+ for device in device_queries:
121
+ if device_queries[device]:
122
+ spies[device].assert_called_with(device_queries[device])
123
+ else:
124
+ spies[device].assert_not_called()
243
125
 
244
- async def test_create_smart_device_with_timeout():
245
- """Make sure timeout is passed to the protocol."""
246
- host = "127.0.0.1"
247
- dev = SmartDevice(host, config=DeviceConfig(host, timeout=100))
248
- assert dev.protocol._transport._timeout == 100
249
126
 
250
-
251
- async def test_create_thin_wrapper():
252
- """Make sure thin wrapper is created with the correct device type."""
253
- mock = Mock()
254
- config = DeviceConfig(
255
- host="test_host",
256
- port_override=1234,
257
- timeout=100,
258
- credentials=Credentials("username", "password"),
127
+ async def test_get_modules():
128
+ """Test getting modules for child and parent modules."""
129
+ dummy_device = await get_device_for_fixture_protocol(
130
+ "KS240(US)_1.0_1.0.5.json", "SMART"
259
131
  )
260
- with patch("kasa.device_factory.connect", return_value=mock) as connect:
261
- dev = await SmartDevice.connect(config=config)
262
- assert dev is mock
263
-
264
- connect.assert_called_once_with(
265
- host=None,
266
- config=config,
132
+ from kasa.smart.modules import Cloud
133
+
134
+ # Modules on device
135
+ module = dummy_device.modules.get("Cloud")
136
+ assert module
137
+ assert module._device == dummy_device
138
+ assert isinstance(module, Cloud)
139
+
140
+ module = dummy_device.modules.get(Module.Cloud)
141
+ assert module
142
+ assert module._device == dummy_device
143
+ assert isinstance(module, Cloud)
144
+
145
+ # Modules on child
146
+ module = dummy_device.modules.get("Fan")
147
+ assert module
148
+ assert module._device != dummy_device
149
+ assert module._device._parent == dummy_device
150
+
151
+ module = dummy_device.modules.get(Module.Fan)
152
+ assert module
153
+ assert module._device != dummy_device
154
+ assert module._device._parent == dummy_device
155
+
156
+ # Invalid modules
157
+ module = dummy_device.modules.get("DummyModule")
158
+ assert module is None
159
+
160
+ module = dummy_device.modules.get(Module.IotAmbientLight)
161
+ assert module is None
162
+
163
+
164
+ @device_smart
165
+ async def test_smartdevice_cloud_connection(dev: SmartDevice, mocker: MockerFixture):
166
+ """Test is_cloud_connected property."""
167
+ assert isinstance(dev, SmartDevice)
168
+ assert "cloud_connect" in dev._components
169
+
170
+ is_connected = (
171
+ (cc := dev._last_update.get("get_connect_cloud_state"))
172
+ and not isinstance(cc, SmartErrorCode)
173
+ and cc["status"] == 0
267
174
  )
268
175
 
176
+ assert dev.is_cloud_connected == is_connected
177
+ last_update = dev._last_update
269
178
 
270
- @device_iot
271
- async def test_modules_not_supported(dev: SmartDevice):
272
- """Test that unsupported modules do not break the device."""
273
- for module in dev.modules.values():
274
- assert module.is_supported is not None
275
- await dev.update()
276
- for module in dev.modules.values():
277
- assert module.is_supported is not None
278
-
279
-
280
- def check_mac(x):
281
- if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
282
- return x
283
- raise Invalid(x)
284
-
179
+ last_update["get_connect_cloud_state"] = {"status": 0}
180
+ with patch.object(dev.protocol, "query", return_value=last_update):
181
+ await dev.update()
182
+ assert dev.is_cloud_connected is True
285
183
 
286
- TZ_SCHEMA = Schema(
287
- {"zone_str": str, "dst_offset": int, "index": All(int, Range(min=0)), "tz_str": str}
288
- )
184
+ last_update["get_connect_cloud_state"] = {"status": 1}
185
+ with patch.object(dev.protocol, "query", return_value=last_update):
186
+ await dev.update()
187
+ assert dev.is_cloud_connected is False
289
188
 
189
+ last_update["get_connect_cloud_state"] = SmartErrorCode.UNKNOWN_METHOD_ERROR
190
+ with patch.object(dev.protocol, "query", return_value=last_update):
191
+ await dev.update()
192
+ assert dev.is_cloud_connected is False
193
+
194
+ # Test for no cloud_connect component during device initialisation
195
+ component_list = [
196
+ val
197
+ for val in dev._components_raw["component_list"]
198
+ if val["id"] not in {"cloud_connect"}
199
+ ]
200
+ initial_response = {
201
+ "component_nego": {"component_list": component_list},
202
+ "get_connect_cloud_state": last_update["get_connect_cloud_state"],
203
+ "get_device_info": last_update["get_device_info"],
204
+ }
205
+ # Child component list is not stored on the device
206
+ if "get_child_device_list" in last_update:
207
+ child_component_list = await dev.protocol.query(
208
+ "get_child_device_component_list"
209
+ )
210
+ last_update["get_child_device_component_list"] = child_component_list[
211
+ "get_child_device_component_list"
212
+ ]
213
+ new_dev = SmartDevice("127.0.0.1", protocol=dev.protocol)
214
+
215
+ first_call = True
216
+
217
+ def side_effect_func(*_, **__):
218
+ nonlocal first_call
219
+ resp = initial_response if first_call else last_update
220
+ first_call = False
221
+ return resp
290
222
 
291
- SYSINFO_SCHEMA = Schema(
292
- {
293
- "active_mode": In(["schedule", "none", "count_down"]),
294
- "alias": str,
295
- "dev_name": str,
296
- "deviceId": str,
297
- "feature": str,
298
- "fwId": str,
299
- "hwId": str,
300
- "hw_ver": str,
301
- "icon_hash": str,
302
- "led_off": Boolean,
303
- "latitude": Any(All(float, Range(min=-90, max=90)), 0, None),
304
- "latitude_i": Any(
305
- All(int, Range(min=-900000, max=900000)),
306
- All(float, Range(min=-900000, max=900000)),
307
- 0,
308
- None,
309
- ),
310
- "longitude": Any(All(float, Range(min=-180, max=180)), 0, None),
311
- "longitude_i": Any(
312
- All(int, Range(min=-18000000, max=18000000)),
313
- All(float, Range(min=-18000000, max=18000000)),
314
- 0,
315
- None,
316
- ),
317
- "mac": check_mac,
318
- "model": str,
319
- "oemId": str,
320
- "on_time": int,
321
- "relay_state": int,
322
- "rssi": Any(int, None), # rssi can also be positive, see #54
323
- "sw_ver": str,
324
- "type": str,
325
- "mic_type": str,
326
- "updating": Boolean,
327
- # these are available on hs220
328
- "brightness": int,
329
- "preferred_state": [
330
- {"brightness": All(int, Range(min=0, max=100)), "index": int}
331
- ],
332
- "next_action": {"type": int},
333
- "child_num": Optional(Any(None, int)),
334
- "children": Optional(list),
335
- },
336
- extra=REMOVE_EXTRA,
337
- )
223
+ with patch.object(
224
+ new_dev.protocol,
225
+ "query",
226
+ side_effect=side_effect_func,
227
+ ):
228
+ await new_dev.update()
229
+ assert new_dev.is_cloud_connected is False