python-kasa 0.6.2__py3-none-any.whl → 0.7.0.dev0__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 (168) hide show
  1. kasa/__init__.py +88 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +406 -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 +12 -7
  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 +133 -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} +100 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -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 +221 -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 +139 -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 -551
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
  86. kasa/tests/fakeprotocol_smart.py +318 -0
  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/P300(EU)_1.0_1.0.13.json +13 -23
  99. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  100. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  101. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  102. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  103. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  104. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  105. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  106. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  107. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  108. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  109. kasa/tests/smart/__init__.py +0 -0
  110. kasa/tests/smart/features/__init__.py +0 -0
  111. kasa/tests/smart/features/test_brightness.py +55 -0
  112. kasa/tests/smart/features/test_colortemp.py +30 -0
  113. kasa/tests/smart/modules/__init__.py +0 -0
  114. kasa/tests/smart/modules/test_contact.py +28 -0
  115. kasa/tests/smart/modules/test_fan.py +79 -0
  116. kasa/tests/smart/modules/test_firmware.py +108 -0
  117. kasa/tests/smart/modules/test_humidity.py +28 -0
  118. kasa/tests/smart/modules/test_light_effect.py +41 -0
  119. kasa/tests/smart/modules/test_temperature.py +47 -0
  120. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  121. kasa/tests/smart/modules/test_waterleak.py +42 -0
  122. kasa/tests/test_aestransport.py +115 -25
  123. kasa/tests/test_bulb.py +169 -86
  124. kasa/tests/test_childdevice.py +84 -0
  125. kasa/tests/test_cli.py +452 -100
  126. kasa/tests/test_common_modules.py +216 -0
  127. kasa/tests/test_device.py +268 -0
  128. kasa/tests/test_device_factory.py +61 -41
  129. kasa/tests/test_device_type.py +1 -1
  130. kasa/tests/test_deviceconfig.py +2 -5
  131. kasa/tests/test_dimmer.py +33 -24
  132. kasa/tests/test_discovery.py +112 -69
  133. kasa/tests/test_emeter.py +39 -12
  134. kasa/tests/test_feature.py +205 -0
  135. kasa/tests/test_httpclient.py +9 -9
  136. kasa/tests/test_iotdevice.py +286 -0
  137. kasa/tests/test_klapprotocol.py +94 -41
  138. kasa/tests/test_lightstrip.py +24 -19
  139. kasa/tests/test_plug.py +51 -9
  140. kasa/tests/test_protocol.py +8 -12
  141. kasa/tests/test_readme_examples.py +86 -27
  142. kasa/tests/test_smartdevice.py +211 -247
  143. kasa/tests/test_smartprotocol.py +129 -26
  144. kasa/tests/test_strip.py +15 -6
  145. kasa/tests/test_usage.py +1 -3
  146. kasa/xortransport.py +15 -12
  147. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
  148. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  149. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
  150. kasa/modules/emeter.py +0 -111
  151. kasa/smartlightstrip.py +0 -143
  152. kasa/smartplug.py +0 -91
  153. kasa/tapo/__init__.py +0 -7
  154. kasa/tapo/childdevice.py +0 -44
  155. kasa/tapo/tapobulb.py +0 -262
  156. kasa/tapo/tapodevice.py +0 -383
  157. kasa/tapo/tapoplug.py +0 -45
  158. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  159. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  160. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  161. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  162. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  163. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  164. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  165. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  166. python_kasa-0.6.2.dist-info/RECORD +0 -163
  167. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  168. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,205 @@
1
+ import logging
2
+ import sys
3
+ from unittest.mock import patch
4
+
5
+ import pytest
6
+ from pytest_mock import MockerFixture
7
+
8
+ from kasa import Device, Feature, KasaException
9
+
10
+ _LOGGER = logging.getLogger(__name__)
11
+
12
+
13
+ class DummyDevice:
14
+ pass
15
+
16
+
17
+ @pytest.fixture
18
+ def dummy_feature() -> Feature:
19
+ # create_autospec for device slows tests way too much, so we use a dummy here
20
+
21
+ feat = Feature(
22
+ device=DummyDevice(), # type: ignore[arg-type]
23
+ id="dummy_feature",
24
+ name="dummy_feature",
25
+ attribute_getter="dummygetter",
26
+ attribute_setter="dummysetter",
27
+ container=None,
28
+ icon="mdi:dummy",
29
+ type=Feature.Type.Switch,
30
+ unit="dummyunit",
31
+ )
32
+ return feat
33
+
34
+
35
+ def test_feature_api(dummy_feature: Feature):
36
+ """Test all properties of a dummy feature."""
37
+ assert dummy_feature.device is not None
38
+ assert dummy_feature.name == "dummy_feature"
39
+ assert dummy_feature.attribute_getter == "dummygetter"
40
+ assert dummy_feature.attribute_setter == "dummysetter"
41
+ assert dummy_feature.container is None
42
+ assert dummy_feature.icon == "mdi:dummy"
43
+ assert dummy_feature.type == Feature.Type.Switch
44
+ assert dummy_feature.unit == "dummyunit"
45
+
46
+
47
+ def test_feature_missing_type():
48
+ """Test that creating a feature with a setter but without type causes an error."""
49
+ with pytest.raises(ValueError):
50
+ Feature(
51
+ device=DummyDevice(), # type: ignore[arg-type]
52
+ id="dummy_error",
53
+ name="dummy error",
54
+ attribute_getter="dummygetter",
55
+ attribute_setter="dummysetter",
56
+ )
57
+
58
+
59
+ def test_feature_value(dummy_feature: Feature):
60
+ """Verify that property gets accessed on *value* access."""
61
+ dummy_feature.attribute_getter = "test_prop"
62
+ dummy_feature.device.test_prop = "dummy" # type: ignore[attr-defined]
63
+ assert dummy_feature.value == "dummy"
64
+
65
+
66
+ def test_feature_value_container(mocker, dummy_feature: Feature):
67
+ """Test that container's attribute is accessed when expected."""
68
+
69
+ class DummyContainer:
70
+ @property
71
+ def test_prop(self):
72
+ return "dummy"
73
+
74
+ dummy_feature.container = DummyContainer()
75
+ dummy_feature.attribute_getter = "test_prop"
76
+
77
+ mock_dev_prop = mocker.patch.object(
78
+ dummy_feature, "test_prop", new_callable=mocker.PropertyMock, create=True
79
+ )
80
+
81
+ assert dummy_feature.value == "dummy"
82
+ mock_dev_prop.assert_not_called()
83
+
84
+
85
+ def test_feature_value_callable(dev, dummy_feature: Feature):
86
+ """Verify that callables work as *attribute_getter*."""
87
+ dummy_feature.attribute_getter = lambda x: "dummy value"
88
+ assert dummy_feature.value == "dummy value"
89
+
90
+
91
+ async def test_feature_setter(dev, mocker, dummy_feature: Feature):
92
+ """Verify that *set_value* calls the defined method."""
93
+ mock_set_dummy = mocker.patch.object(dummy_feature.device, "set_dummy", create=True)
94
+ dummy_feature.attribute_setter = "set_dummy"
95
+ await dummy_feature.set_value("dummy value")
96
+ mock_set_dummy.assert_called_with("dummy value")
97
+
98
+
99
+ async def test_feature_setter_read_only(dummy_feature):
100
+ """Verify that read-only feature raises an exception when trying to change it."""
101
+ dummy_feature.attribute_setter = None
102
+ with pytest.raises(ValueError):
103
+ await dummy_feature.set_value("value for read only feature")
104
+
105
+
106
+ async def test_feature_action(mocker):
107
+ """Test that setting value on button calls the setter."""
108
+ feat = Feature(
109
+ device=DummyDevice(), # type: ignore[arg-type]
110
+ id="dummy_feature",
111
+ name="dummy_feature",
112
+ attribute_setter="call_action",
113
+ container=None,
114
+ icon="mdi:dummy",
115
+ type=Feature.Type.Action,
116
+ )
117
+ mock_call_action = mocker.patch.object(feat.device, "call_action", create=True)
118
+ assert feat.value == "<Action>"
119
+ await feat.set_value(1234)
120
+ mock_call_action.assert_called()
121
+
122
+
123
+ async def test_feature_choice_list(dummy_feature, caplog, mocker: MockerFixture):
124
+ """Test the choice feature type."""
125
+ dummy_feature.type = Feature.Type.Choice
126
+ dummy_feature.choices = ["first", "second"]
127
+
128
+ mock_setter = mocker.patch.object(dummy_feature.device, "dummysetter", create=True)
129
+ await dummy_feature.set_value("first")
130
+ mock_setter.assert_called_with("first")
131
+ mock_setter.reset_mock()
132
+
133
+ with pytest.raises(ValueError):
134
+ await dummy_feature.set_value("invalid")
135
+ assert "Unexpected value" in caplog.text
136
+
137
+ mock_setter.assert_not_called()
138
+
139
+
140
+ @pytest.mark.parametrize("precision_hint", [1, 2, 3])
141
+ async def test_precision_hint(dummy_feature, precision_hint):
142
+ """Test that precision hint works as expected."""
143
+ dummy_value = 3.141593
144
+ dummy_feature.type = Feature.Type.Sensor
145
+ dummy_feature.precision_hint = precision_hint
146
+
147
+ dummy_feature.attribute_getter = lambda x: dummy_value
148
+ assert dummy_feature.value == dummy_value
149
+ assert f"{round(dummy_value, precision_hint)} dummyunit" in repr(dummy_feature)
150
+
151
+
152
+ @pytest.mark.skipif(
153
+ sys.version_info < (3, 11),
154
+ reason="exceptiongroup requires python3.11+",
155
+ )
156
+ async def test_feature_setters(dev: Device, mocker: MockerFixture):
157
+ """Test that all feature setters query something."""
158
+
159
+ async def _test_feature(feat, query_mock):
160
+ if feat.attribute_setter is None:
161
+ return
162
+
163
+ expecting_call = True
164
+
165
+ if feat.type == Feature.Type.Number:
166
+ await feat.set_value(feat.minimum_value)
167
+ elif feat.type == Feature.Type.Switch:
168
+ await feat.set_value(True)
169
+ elif feat.type == Feature.Type.Action:
170
+ await feat.set_value("dummyvalue")
171
+ elif feat.type == Feature.Type.Choice:
172
+ await feat.set_value(feat.choices[0])
173
+ elif feat.type == Feature.Type.Unknown:
174
+ _LOGGER.warning("Feature '%s' has no type, cannot test the setter", feat)
175
+ expecting_call = False
176
+ else:
177
+ raise NotImplementedError(f"set_value not implemented for {feat.type}")
178
+
179
+ if expecting_call:
180
+ query_mock.assert_called()
181
+
182
+ async def _test_features(dev):
183
+ exceptions = []
184
+ for feat in dev.features.values():
185
+ try:
186
+ with patch.object(feat.device.protocol, "query") as query:
187
+ await _test_feature(feat, query)
188
+ # we allow our own exceptions to avoid mocking valid responses
189
+ except KasaException:
190
+ pass
191
+ except Exception as ex:
192
+ ex.add_note(f"Exception when trying to set {feat} on {dev}")
193
+ exceptions.append(ex)
194
+
195
+ return exceptions
196
+
197
+ exceptions = await _test_features(dev)
198
+
199
+ for child in dev.children:
200
+ exceptions.extend(await _test_features(child))
201
+
202
+ if exceptions:
203
+ raise ExceptionGroup(
204
+ "Got exceptions while testing attribute_setters", exceptions
205
+ )
@@ -6,9 +6,9 @@ import pytest
6
6
 
7
7
  from ..deviceconfig import DeviceConfig
8
8
  from ..exceptions import (
9
- ConnectionException,
10
- SmartDeviceException,
11
- TimeoutException,
9
+ KasaException,
10
+ TimeoutError,
11
+ _ConnectionError,
12
12
  )
13
13
  from ..httpclient import HttpClient
14
14
 
@@ -18,28 +18,28 @@ from ..httpclient import HttpClient
18
18
  [
19
19
  (
20
20
  aiohttp.ServerDisconnectedError(),
21
- ConnectionException,
21
+ _ConnectionError,
22
22
  "Device connection error: ",
23
23
  ),
24
24
  (
25
25
  aiohttp.ClientOSError(),
26
- ConnectionException,
26
+ _ConnectionError,
27
27
  "Device connection error: ",
28
28
  ),
29
29
  (
30
30
  aiohttp.ServerTimeoutError(),
31
- TimeoutException,
31
+ TimeoutError,
32
32
  "Unable to query the device, timed out: ",
33
33
  ),
34
34
  (
35
35
  asyncio.TimeoutError(),
36
- TimeoutException,
36
+ TimeoutError,
37
37
  "Unable to query the device, timed out: ",
38
38
  ),
39
- (Exception(), SmartDeviceException, "Unable to query the device: "),
39
+ (Exception(), KasaException, "Unable to query the device: "),
40
40
  (
41
41
  aiohttp.ServerFingerprintMismatch("exp", "got", "host", 1),
42
- SmartDeviceException,
42
+ KasaException,
43
43
  "Unable to query the device: ",
44
44
  ),
45
45
  ],
@@ -0,0 +1,286 @@
1
+ """Module for common iotdevice tests."""
2
+
3
+ import re
4
+ from datetime import datetime
5
+
6
+ import pytest
7
+ from voluptuous import (
8
+ REMOVE_EXTRA,
9
+ All,
10
+ Any,
11
+ Boolean,
12
+ In,
13
+ Invalid,
14
+ Optional,
15
+ Range,
16
+ Schema,
17
+ )
18
+
19
+ from kasa import KasaException, Module
20
+ from kasa.iot import IotDevice
21
+
22
+ from .conftest import get_device_for_fixture_protocol, handle_turn_on, turn_on
23
+ from .device_fixtures import device_iot, has_emeter_iot, no_emeter_iot
24
+ from .fakeprotocol_iot import FakeIotProtocol
25
+
26
+ TZ_SCHEMA = Schema(
27
+ {"zone_str": str, "dst_offset": int, "index": All(int, Range(min=0)), "tz_str": str}
28
+ )
29
+
30
+
31
+ def check_mac(x):
32
+ if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
33
+ return x
34
+ raise Invalid(x)
35
+
36
+
37
+ SYSINFO_SCHEMA = Schema(
38
+ {
39
+ "active_mode": In(["schedule", "none", "count_down"]),
40
+ "alias": str,
41
+ "dev_name": str,
42
+ "deviceId": str,
43
+ "feature": str,
44
+ "fwId": str,
45
+ "hwId": str,
46
+ "hw_ver": str,
47
+ "icon_hash": str,
48
+ "led_off": Boolean,
49
+ "latitude": Any(All(float, Range(min=-90, max=90)), 0, None),
50
+ "latitude_i": Any(
51
+ All(int, Range(min=-900000, max=900000)),
52
+ All(float, Range(min=-900000, max=900000)),
53
+ 0,
54
+ None,
55
+ ),
56
+ "longitude": Any(All(float, Range(min=-180, max=180)), 0, None),
57
+ "longitude_i": Any(
58
+ All(int, Range(min=-18000000, max=18000000)),
59
+ All(float, Range(min=-18000000, max=18000000)),
60
+ 0,
61
+ None,
62
+ ),
63
+ "mac": check_mac,
64
+ "model": str,
65
+ "oemId": str,
66
+ "on_time": int,
67
+ "relay_state": int,
68
+ "rssi": Any(int, None), # rssi can also be positive, see #54
69
+ "sw_ver": str,
70
+ "type": str,
71
+ "mic_type": str,
72
+ "updating": Boolean,
73
+ # these are available on hs220
74
+ "brightness": int,
75
+ "preferred_state": [
76
+ {"brightness": All(int, Range(min=0, max=100)), "index": int}
77
+ ],
78
+ "next_action": {"type": int},
79
+ "child_num": Optional(Any(None, int)),
80
+ "children": Optional(list),
81
+ },
82
+ extra=REMOVE_EXTRA,
83
+ )
84
+
85
+
86
+ @device_iot
87
+ async def test_state_info(dev):
88
+ assert isinstance(dev.state_information, dict)
89
+
90
+
91
+ @pytest.mark.requires_dummy
92
+ @device_iot
93
+ async def test_invalid_connection(mocker, dev):
94
+ with mocker.patch.object(
95
+ FakeIotProtocol, "query", side_effect=KasaException
96
+ ), pytest.raises(KasaException):
97
+ await dev.update()
98
+
99
+
100
+ @has_emeter_iot
101
+ async def test_initial_update_emeter(dev, mocker):
102
+ """Test that the initial update performs second query if emeter is available."""
103
+ dev._last_update = None
104
+ dev._legacy_features = set()
105
+ spy = mocker.spy(dev.protocol, "query")
106
+ await dev.update()
107
+ # Devices with small buffers may require 3 queries
108
+ expected_queries = 2 if dev.max_device_response_size > 4096 else 3
109
+ assert spy.call_count == expected_queries + len(dev.children)
110
+
111
+
112
+ @no_emeter_iot
113
+ async def test_initial_update_no_emeter(dev, mocker):
114
+ """Test that the initial update performs second query if emeter is available."""
115
+ dev._last_update = None
116
+ dev._legacy_features = set()
117
+ spy = mocker.spy(dev.protocol, "query")
118
+ await dev.update()
119
+ # 2 calls are necessary as some devices crash on unexpected modules
120
+ # See #105, #120, #161
121
+ assert spy.call_count == 2
122
+
123
+
124
+ @device_iot
125
+ async def test_query_helper(dev):
126
+ with pytest.raises(KasaException):
127
+ await dev._query_helper("test", "testcmd", {})
128
+ # TODO check for unwrapping?
129
+
130
+
131
+ @device_iot
132
+ @turn_on
133
+ async def test_state(dev, turn_on):
134
+ await handle_turn_on(dev, turn_on)
135
+ orig_state = dev.is_on
136
+ if orig_state:
137
+ await dev.turn_off()
138
+ await dev.update()
139
+ assert not dev.is_on
140
+ assert dev.is_off
141
+
142
+ await dev.turn_on()
143
+ await dev.update()
144
+ assert dev.is_on
145
+ assert not dev.is_off
146
+ else:
147
+ await dev.turn_on()
148
+ await dev.update()
149
+ assert dev.is_on
150
+ assert not dev.is_off
151
+
152
+ await dev.turn_off()
153
+ await dev.update()
154
+ assert not dev.is_on
155
+ assert dev.is_off
156
+
157
+
158
+ @device_iot
159
+ @turn_on
160
+ async def test_on_since(dev, turn_on):
161
+ await handle_turn_on(dev, turn_on)
162
+ orig_state = dev.is_on
163
+ if "on_time" not in dev.sys_info and not dev.is_strip:
164
+ assert dev.on_since is None
165
+ elif orig_state:
166
+ assert isinstance(dev.on_since, datetime)
167
+ else:
168
+ assert dev.on_since is None
169
+
170
+
171
+ @device_iot
172
+ async def test_time(dev):
173
+ assert isinstance(await dev.get_time(), datetime)
174
+
175
+
176
+ @device_iot
177
+ async def test_timezone(dev):
178
+ TZ_SCHEMA(await dev.get_timezone())
179
+
180
+
181
+ @device_iot
182
+ async def test_hw_info(dev):
183
+ SYSINFO_SCHEMA(dev.hw_info)
184
+
185
+
186
+ @device_iot
187
+ async def test_location(dev):
188
+ SYSINFO_SCHEMA(dev.location)
189
+
190
+
191
+ @device_iot
192
+ async def test_rssi(dev):
193
+ SYSINFO_SCHEMA({"rssi": dev.rssi}) # wrapping for vol
194
+
195
+
196
+ @device_iot
197
+ async def test_mac(dev):
198
+ SYSINFO_SCHEMA({"mac": dev.mac}) # wrapping for val
199
+
200
+
201
+ @device_iot
202
+ async def test_representation(dev):
203
+ pattern = re.compile("<DeviceType\..+ at .+? - .*? \(.+?\)>")
204
+ assert pattern.match(str(dev))
205
+
206
+
207
+ @device_iot
208
+ async def test_children(dev):
209
+ """Make sure that children property is exposed by every device."""
210
+ if dev.is_strip:
211
+ assert len(dev.children) > 0
212
+ else:
213
+ assert len(dev.children) == 0
214
+
215
+
216
+ @device_iot
217
+ async def test_modules_preserved(dev: IotDevice):
218
+ """Make modules that are not being updated are preserved between updates."""
219
+ dev._last_update["some_module_not_being_updated"] = "should_be_kept"
220
+ await dev.update()
221
+ assert dev._last_update["some_module_not_being_updated"] == "should_be_kept"
222
+
223
+
224
+ @device_iot
225
+ async def test_internal_state(dev):
226
+ """Make sure the internal state returns the last update results."""
227
+ assert dev.internal_state == dev._last_update
228
+
229
+
230
+ @device_iot
231
+ async def test_features(dev):
232
+ """Make sure features is always accessible."""
233
+ sysinfo = dev._last_update["system"]["get_sysinfo"]
234
+ if "feature" in sysinfo:
235
+ assert dev._legacy_features == set(sysinfo["feature"].split(":"))
236
+ else:
237
+ assert dev._legacy_features == set()
238
+
239
+
240
+ @device_iot
241
+ async def test_max_device_response_size(dev):
242
+ """Make sure every device return has a set max response size."""
243
+ assert dev.max_device_response_size > 0
244
+
245
+
246
+ @device_iot
247
+ async def test_estimated_response_sizes(dev):
248
+ """Make sure every module has an estimated response size set."""
249
+ for mod in dev.modules.values():
250
+ assert mod.estimated_query_response_size > 0
251
+
252
+
253
+ @device_iot
254
+ async def test_modules_not_supported(dev: IotDevice):
255
+ """Test that unsupported modules do not break the device."""
256
+ for module in dev.modules.values():
257
+ assert module.is_supported is not None
258
+ await dev.update()
259
+ for module in dev.modules.values():
260
+ assert module.is_supported is not None
261
+
262
+
263
+ async def test_get_modules():
264
+ """Test getting modules for child and parent modules."""
265
+ dummy_device = await get_device_for_fixture_protocol(
266
+ "HS100(US)_2.0_1.5.6.json", "IOT"
267
+ )
268
+ from kasa.iot.modules import Cloud
269
+
270
+ # Modules on device
271
+ module = dummy_device.modules.get("cloud")
272
+ assert module
273
+ assert module._device == dummy_device
274
+ assert isinstance(module, Cloud)
275
+
276
+ module = dummy_device.modules.get(Module.IotCloud)
277
+ assert module
278
+ assert module._device == dummy_device
279
+ assert isinstance(module, Cloud)
280
+
281
+ # Invalid modules
282
+ module = dummy_device.modules.get("DummyModule")
283
+ assert module is None
284
+
285
+ module = dummy_device.modules.get(Module.Cloud)
286
+ assert module is None