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
kasa/tests/test_cli.py CHANGED
@@ -1,4 +1,5 @@
1
1
  import json
2
+ import os
2
3
  import re
3
4
 
4
5
  import asyncclick as click
@@ -6,35 +7,63 @@ import pytest
6
7
  from asyncclick.testing import CliRunner
7
8
 
8
9
  from kasa import (
9
- AuthenticationException,
10
+ AuthenticationError,
11
+ Credentials,
12
+ Device,
13
+ DeviceError,
10
14
  EmeterStatus,
11
- SmartDevice,
12
- SmartDeviceException,
13
- UnsupportedDeviceException,
15
+ KasaException,
16
+ Module,
17
+ UnsupportedDeviceError,
14
18
  )
15
19
  from kasa.cli import (
16
20
  TYPE_TO_CLASS,
17
21
  alias,
18
22
  brightness,
19
23
  cli,
24
+ cmd_command,
25
+ effect,
20
26
  emeter,
27
+ hsv,
28
+ led,
21
29
  raw_command,
22
30
  reboot,
23
31
  state,
24
32
  sysinfo,
33
+ temperature,
25
34
  toggle,
26
35
  update_credentials,
27
36
  wifi,
28
37
  )
29
38
  from kasa.discover import Discover, DiscoveryResult
39
+ from kasa.iot import IotDevice
40
+
41
+ from .conftest import (
42
+ device_smart,
43
+ get_device_for_fixture_protocol,
44
+ handle_turn_on,
45
+ new_discovery,
46
+ turn_on,
47
+ )
48
+
49
+
50
+ @pytest.fixture()
51
+ def runner():
52
+ """Runner fixture that unsets the KASA_ environment variables for tests."""
53
+ KASA_VARS = {k: None for k, v in os.environ.items() if k.startswith("KASA_")}
54
+ runner = CliRunner(env=KASA_VARS)
30
55
 
31
- from .conftest import device_iot, device_smart, handle_turn_on, new_discovery, turn_on
56
+ return runner
32
57
 
33
58
 
34
- async def test_update_called_by_cli(dev, mocker):
59
+ async def test_update_called_by_cli(dev, mocker, runner):
35
60
  """Test that device update is called on main."""
36
- runner = CliRunner()
37
61
  update = mocker.patch.object(dev, "update")
62
+
63
+ # These will mock the features to avoid accessing non-existing
64
+ mocker.patch("kasa.device.Device.features", return_value={})
65
+ mocker.patch("kasa.iot.iotdevice.IotDevice.features", return_value={})
66
+
38
67
  mocker.patch("kasa.discover.Discover.discover_single", return_value=dev)
39
68
 
40
69
  res = await runner.invoke(
@@ -47,25 +76,23 @@ async def test_update_called_by_cli(dev, mocker):
47
76
  "--password",
48
77
  "bar",
49
78
  ],
79
+ catch_exceptions=False,
50
80
  )
51
81
  assert res.exit_code == 0
52
82
  update.assert_called()
53
83
 
54
84
 
55
- @device_iot
56
- async def test_sysinfo(dev):
57
- runner = CliRunner()
85
+ async def test_sysinfo(dev: Device, runner):
58
86
  res = await runner.invoke(sysinfo, obj=dev)
59
87
  assert "System info" in res.output
60
- assert dev.alias in res.output
88
+ assert dev.model in res.output
61
89
 
62
90
 
63
91
  @turn_on
64
- async def test_state(dev, turn_on):
92
+ async def test_state(dev, turn_on, runner):
65
93
  await handle_turn_on(dev, turn_on)
66
- runner = CliRunner()
67
- res = await runner.invoke(state, obj=dev)
68
94
  await dev.update()
95
+ res = await runner.invoke(state, obj=dev)
69
96
 
70
97
  if dev.is_on:
71
98
  assert "Device state: True" in res.output
@@ -74,21 +101,17 @@ async def test_state(dev, turn_on):
74
101
 
75
102
 
76
103
  @turn_on
77
- async def test_toggle(dev, turn_on, mocker):
104
+ async def test_toggle(dev, turn_on, runner):
78
105
  await handle_turn_on(dev, turn_on)
79
- runner = CliRunner()
80
- await runner.invoke(toggle, obj=dev)
81
-
82
- if turn_on:
83
- assert not dev.is_on
84
- else:
85
- assert dev.is_on
106
+ await dev.update()
107
+ assert dev.is_on == turn_on
86
108
 
109
+ await runner.invoke(toggle, obj=dev)
110
+ await dev.update()
111
+ assert dev.is_on != turn_on
87
112
 
88
- @device_iot
89
- async def test_alias(dev):
90
- runner = CliRunner()
91
113
 
114
+ async def test_alias(dev, runner):
92
115
  res = await runner.invoke(alias, obj=dev)
93
116
  assert f"Alias: {dev.alias}" in res.output
94
117
 
@@ -97,6 +120,7 @@ async def test_alias(dev):
97
120
  new_alias = "new alias"
98
121
  res = await runner.invoke(alias, [new_alias], obj=dev)
99
122
  assert f"Setting alias to {new_alias}" in res.output
123
+ await dev.update()
100
124
 
101
125
  res = await runner.invoke(alias, obj=dev)
102
126
  assert f"Alias: {new_alias}" in res.output
@@ -104,12 +128,11 @@ async def test_alias(dev):
104
128
  await dev.set_alias(old_alias)
105
129
 
106
130
 
107
- async def test_raw_command(dev, mocker):
108
- runner = CliRunner()
131
+ async def test_raw_command(dev, mocker, runner):
109
132
  update = mocker.patch.object(dev, "update")
110
- from kasa.tapo import TapoDevice
133
+ from kasa.smart import SmartDevice
111
134
 
112
- if isinstance(dev, TapoDevice):
135
+ if isinstance(dev, SmartDevice):
113
136
  params = ["na", "get_device_info"]
114
137
  else:
115
138
  params = ["system", "get_sysinfo"]
@@ -127,10 +150,38 @@ async def test_raw_command(dev, mocker):
127
150
  assert "Usage" in res.output
128
151
 
129
152
 
153
+ async def test_command_with_child(dev, mocker, runner):
154
+ """Test 'command' command with --child."""
155
+ update_mock = mocker.patch.object(dev, "update")
156
+
157
+ # create_autospec for device slows tests way too much, so we use a dummy here
158
+ class DummyDevice(dev.__class__):
159
+ def __init__(self):
160
+ super().__init__("127.0.0.1")
161
+
162
+ async def _query_helper(*_, **__):
163
+ return {"dummy": "response"}
164
+
165
+ dummy_child = DummyDevice()
166
+
167
+ mocker.patch.object(dev, "_children", {"XYZ": dummy_child})
168
+ mocker.patch.object(dev, "get_child_device", return_value=dummy_child)
169
+
170
+ res = await runner.invoke(
171
+ cmd_command,
172
+ ["--child", "XYZ", "command", "'params'"],
173
+ obj=dev,
174
+ catch_exceptions=False,
175
+ )
176
+
177
+ update_mock.assert_called()
178
+ assert '{"dummy": "response"}' in res.output
179
+ assert res.exit_code == 0
180
+
181
+
130
182
  @device_smart
131
- async def test_reboot(dev, mocker):
183
+ async def test_reboot(dev, mocker, runner):
132
184
  """Test that reboot works on SMART devices."""
133
- runner = CliRunner()
134
185
  query_mock = mocker.patch.object(dev.protocol, "query")
135
186
 
136
187
  res = await runner.invoke(
@@ -143,17 +194,15 @@ async def test_reboot(dev, mocker):
143
194
 
144
195
 
145
196
  @device_smart
146
- async def test_wifi_scan(dev):
147
- runner = CliRunner()
197
+ async def test_wifi_scan(dev, runner):
148
198
  res = await runner.invoke(wifi, ["scan"], obj=dev)
149
199
 
150
200
  assert res.exit_code == 0
151
- assert re.search(r"Found \d wifi networks!", res.output)
201
+ assert re.search(r"Found [\d]+ wifi networks!", res.output)
152
202
 
153
203
 
154
204
  @device_smart
155
- async def test_wifi_join(dev, mocker):
156
- runner = CliRunner()
205
+ async def test_wifi_join(dev, mocker, runner):
157
206
  update = mocker.patch.object(dev, "update")
158
207
  res = await runner.invoke(
159
208
  wifi,
@@ -170,8 +219,7 @@ async def test_wifi_join(dev, mocker):
170
219
 
171
220
 
172
221
  @device_smart
173
- async def test_wifi_join_no_creds(dev):
174
- runner = CliRunner()
222
+ async def test_wifi_join_no_creds(dev, runner):
175
223
  dev.protocol._transport._credentials = None
176
224
  res = await runner.invoke(
177
225
  wifi,
@@ -180,15 +228,12 @@ async def test_wifi_join_no_creds(dev):
180
228
  )
181
229
 
182
230
  assert res.exit_code != 0
183
- assert isinstance(res.exception, AuthenticationException)
231
+ assert isinstance(res.exception, AuthenticationError)
184
232
 
185
233
 
186
234
  @device_smart
187
- async def test_wifi_join_exception(dev, mocker):
188
- runner = CliRunner()
189
- mocker.patch.object(
190
- dev.protocol, "query", side_effect=SmartDeviceException(error_code=9999)
191
- )
235
+ async def test_wifi_join_exception(dev, mocker, runner):
236
+ mocker.patch.object(dev.protocol, "query", side_effect=DeviceError(error_code=9999))
192
237
  res = await runner.invoke(
193
238
  wifi,
194
239
  ["join", "FOOBAR", "--keytype", "wpa_psk", "--password", "foobar"],
@@ -196,12 +241,11 @@ async def test_wifi_join_exception(dev, mocker):
196
241
  )
197
242
 
198
243
  assert res.exit_code != 0
199
- assert isinstance(res.exception, SmartDeviceException)
244
+ assert isinstance(res.exception, KasaException)
200
245
 
201
246
 
202
247
  @device_smart
203
- async def test_update_credentials(dev):
204
- runner = CliRunner()
248
+ async def test_update_credentials(dev, runner):
205
249
  res = await runner.invoke(
206
250
  update_credentials,
207
251
  ["--username", "foo", "--password", "bar"],
@@ -216,9 +260,7 @@ async def test_update_credentials(dev):
216
260
  )
217
261
 
218
262
 
219
- async def test_emeter(dev: SmartDevice, mocker):
220
- runner = CliRunner()
221
-
263
+ async def test_emeter(dev: Device, mocker, runner):
222
264
  res = await runner.invoke(emeter, obj=dev)
223
265
  if not dev.has_emeter:
224
266
  assert "Device has no emeter" in res.output
@@ -245,57 +287,166 @@ async def test_emeter(dev: SmartDevice, mocker):
245
287
  assert "Voltage: 122.066 V" in res.output
246
288
  assert realtime_emeter.call_count == 2
247
289
 
248
- monthly = mocker.patch.object(dev, "get_emeter_monthly")
249
- monthly.return_value = {1: 1234}
290
+ if isinstance(dev, IotDevice):
291
+ monthly = mocker.patch.object(dev, "get_emeter_monthly")
292
+ monthly.return_value = {1: 1234}
250
293
  res = await runner.invoke(emeter, ["--year", "1900"], obj=dev)
294
+ if not isinstance(dev, IotDevice):
295
+ assert "Device has no historical statistics" in res.output
296
+ return
251
297
  assert "For year" in res.output
252
298
  assert "1, 1234" in res.output
253
299
  monthly.assert_called_with(year=1900)
254
300
 
255
- daily = mocker.patch.object(dev, "get_emeter_daily")
256
- daily.return_value = {1: 1234}
301
+ if isinstance(dev, IotDevice):
302
+ daily = mocker.patch.object(dev, "get_emeter_daily")
303
+ daily.return_value = {1: 1234}
257
304
  res = await runner.invoke(emeter, ["--month", "1900-12"], obj=dev)
305
+ if not isinstance(dev, IotDevice):
306
+ assert "Device has no historical statistics" in res.output
307
+ return
258
308
  assert "For month" in res.output
259
309
  assert "1, 1234" in res.output
260
310
  daily.assert_called_with(year=1900, month=12)
261
311
 
262
312
 
263
- @device_iot
264
- async def test_brightness(dev):
265
- runner = CliRunner()
313
+ async def test_brightness(dev: Device, runner):
266
314
  res = await runner.invoke(brightness, obj=dev)
267
- if not dev.is_dimmable:
315
+ if not (light := dev.modules.get(Module.Light)) or not light.is_dimmable:
268
316
  assert "This device does not support brightness." in res.output
269
317
  return
270
318
 
271
319
  res = await runner.invoke(brightness, obj=dev)
272
- assert f"Brightness: {dev.brightness}" in res.output
320
+ assert f"Brightness: {light.brightness}" in res.output
273
321
 
274
322
  res = await runner.invoke(brightness, ["12"], obj=dev)
275
323
  assert "Setting brightness" in res.output
324
+ await dev.update()
276
325
 
277
326
  res = await runner.invoke(brightness, obj=dev)
278
327
  assert "Brightness: 12" in res.output
279
328
 
280
329
 
281
- @device_iot
282
- async def test_json_output(dev: SmartDevice, mocker):
330
+ async def test_color_temperature(dev: Device, runner):
331
+ res = await runner.invoke(temperature, obj=dev)
332
+ if not (light := dev.modules.get(Module.Light)) or not light.is_variable_color_temp:
333
+ assert "Device does not support color temperature" in res.output
334
+ return
335
+
336
+ res = await runner.invoke(temperature, obj=dev)
337
+ assert f"Color temperature: {light.color_temp}" in res.output
338
+ valid_range = light.valid_temperature_range
339
+ assert f"(min: {valid_range.min}, max: {valid_range.max})" in res.output
340
+
341
+ val = int((valid_range.min + valid_range.max) / 2)
342
+ res = await runner.invoke(temperature, [str(val)], obj=dev)
343
+ assert "Setting color temperature to " in res.output
344
+ await dev.update()
345
+
346
+ res = await runner.invoke(temperature, obj=dev)
347
+ assert f"Color temperature: {val}" in res.output
348
+ assert res.exit_code == 0
349
+
350
+ invalid_max = valid_range.max + 100
351
+ # Lights that support the maximum range will not get past the click cli range check
352
+ # So can't be tested for the internal range check.
353
+ if invalid_max < 9000:
354
+ res = await runner.invoke(temperature, [str(invalid_max)], obj=dev)
355
+ assert res.exit_code == 1
356
+ assert isinstance(res.exception, ValueError)
357
+
358
+ res = await runner.invoke(temperature, [str(9100)], obj=dev)
359
+ assert res.exit_code == 2
360
+
361
+
362
+ async def test_color_hsv(dev: Device, runner: CliRunner):
363
+ res = await runner.invoke(hsv, obj=dev)
364
+ if not (light := dev.modules.get(Module.Light)) or not light.is_color:
365
+ assert "Device does not support colors" in res.output
366
+ return
367
+
368
+ res = await runner.invoke(hsv, obj=dev)
369
+ assert f"Current HSV: {light.hsv}" in res.output
370
+
371
+ res = await runner.invoke(hsv, ["180", "50", "50"], obj=dev)
372
+ assert "Setting HSV: 180 50 50" in res.output
373
+ assert res.exit_code == 0
374
+ await dev.update()
375
+
376
+ res = await runner.invoke(hsv, ["180", "50"], obj=dev)
377
+ assert "Setting a color requires 3 values." in res.output
378
+ assert res.exit_code == 2
379
+
380
+
381
+ async def test_light_effect(dev: Device, runner: CliRunner):
382
+ res = await runner.invoke(effect, obj=dev)
383
+ if not (light_effect := dev.modules.get(Module.LightEffect)):
384
+ assert "Device does not support effects" in res.output
385
+ return
386
+
387
+ # Start off with a known state of off
388
+ await light_effect.set_effect(light_effect.LIGHT_EFFECTS_OFF)
389
+ await dev.update()
390
+ assert light_effect.effect == light_effect.LIGHT_EFFECTS_OFF
391
+
392
+ res = await runner.invoke(effect, obj=dev)
393
+ assert f"Light effect: {light_effect.effect}" in res.output
394
+ assert res.exit_code == 0
395
+
396
+ res = await runner.invoke(effect, [light_effect.effect_list[1]], obj=dev)
397
+ assert f"Setting Effect: {light_effect.effect_list[1]}" in res.output
398
+ assert res.exit_code == 0
399
+ await dev.update()
400
+ assert light_effect.effect == light_effect.effect_list[1]
401
+
402
+ res = await runner.invoke(effect, ["foobar"], obj=dev)
403
+ assert f"Effect must be one of: {light_effect.effect_list}" in res.output
404
+ assert res.exit_code == 2
405
+
406
+
407
+ async def test_led(dev: Device, runner: CliRunner):
408
+ res = await runner.invoke(led, obj=dev)
409
+ if not (led_module := dev.modules.get(Module.Led)):
410
+ assert "Device does not support led" in res.output
411
+ return
412
+
413
+ res = await runner.invoke(led, obj=dev)
414
+ assert f"LED state: {led_module.led}" in res.output
415
+ assert res.exit_code == 0
416
+
417
+ res = await runner.invoke(led, ["on"], obj=dev)
418
+ assert "Turning led to True" in res.output
419
+ assert res.exit_code == 0
420
+ await dev.update()
421
+ assert led_module.led is True
422
+
423
+ res = await runner.invoke(led, ["off"], obj=dev)
424
+ assert "Turning led to False" in res.output
425
+ assert res.exit_code == 0
426
+ await dev.update()
427
+ assert led_module.led is False
428
+
429
+
430
+ async def test_json_output(dev: Device, mocker, runner):
283
431
  """Test that the json output produces correct output."""
284
- mocker.patch("kasa.Discover.discover", return_value=[dev])
285
- runner = CliRunner()
432
+ mocker.patch("kasa.Discover.discover", return_value={"127.0.0.1": dev})
433
+ # These will mock the features to avoid accessing non-existing
434
+ mocker.patch("kasa.device.Device.features", return_value={})
435
+ mocker.patch("kasa.iot.iotdevice.IotDevice.features", return_value={})
436
+
286
437
  res = await runner.invoke(cli, ["--json", "state"], obj=dev)
287
438
  assert res.exit_code == 0
288
439
  assert json.loads(res.output) == dev.internal_state
289
440
 
290
441
 
291
442
  @new_discovery
292
- async def test_credentials(discovery_mock, mocker):
443
+ async def test_credentials(discovery_mock, mocker, runner):
293
444
  """Test credentials are passed correctly from cli to device."""
294
445
  # Patch state to echo username and password
295
- pass_dev = click.make_pass_decorator(SmartDevice)
446
+ pass_dev = click.make_pass_decorator(Device)
296
447
 
297
448
  @pass_dev
298
- async def _state(dev: SmartDevice):
449
+ async def _state(dev: Device):
299
450
  if dev.credentials:
300
451
  click.echo(
301
452
  f"Username:{dev.credentials.username} Password:{dev.credentials.password}"
@@ -303,11 +454,7 @@ async def test_credentials(discovery_mock, mocker):
303
454
 
304
455
  mocker.patch("kasa.cli.state", new=_state)
305
456
 
306
- mocker.patch("kasa.IotProtocol.query", return_value=discovery_mock.query_data)
307
- mocker.patch("kasa.SmartProtocol.query", return_value=discovery_mock.query_data)
308
-
309
457
  dr = DiscoveryResult(**discovery_mock.discovery_data["result"])
310
- runner = CliRunner()
311
458
  res = await runner.invoke(
312
459
  cli,
313
460
  [
@@ -328,11 +475,15 @@ async def test_credentials(discovery_mock, mocker):
328
475
  assert "Username:foo Password:bar\n" in res.output
329
476
 
330
477
 
331
- @device_iot
332
- async def test_without_device_type(dev, mocker):
478
+ async def test_without_device_type(dev, mocker, runner):
333
479
  """Test connecting without the device type."""
334
- runner = CliRunner()
335
- mocker.patch("kasa.discover.Discover.discover_single", return_value=dev)
480
+ discovery_mock = mocker.patch(
481
+ "kasa.discover.Discover.discover_single", return_value=dev
482
+ )
483
+ # These will mock the features to avoid accessing non-existing
484
+ mocker.patch("kasa.device.Device.features", return_value={})
485
+ mocker.patch("kasa.iot.iotdevice.IotDevice.features", return_value={})
486
+
336
487
  res = await runner.invoke(
337
488
  cli,
338
489
  [
@@ -342,16 +493,23 @@ async def test_without_device_type(dev, mocker):
342
493
  "foo",
343
494
  "--password",
344
495
  "bar",
496
+ "--discovery-timeout",
497
+ "7",
345
498
  ],
346
499
  )
347
500
  assert res.exit_code == 0
501
+ discovery_mock.assert_called_once_with(
502
+ "127.0.0.1",
503
+ port=None,
504
+ credentials=Credentials("foo", "bar"),
505
+ timeout=5,
506
+ discovery_timeout=7,
507
+ )
348
508
 
349
509
 
350
510
  @pytest.mark.parametrize("auth_param", ["--username", "--password"])
351
- async def test_invalid_credential_params(auth_param):
511
+ async def test_invalid_credential_params(auth_param, runner):
352
512
  """Test for handling only one of username or password supplied."""
353
- runner = CliRunner()
354
-
355
513
  res = await runner.invoke(
356
514
  cli,
357
515
  [
@@ -370,10 +528,8 @@ async def test_invalid_credential_params(auth_param):
370
528
  )
371
529
 
372
530
 
373
- async def test_duplicate_target_device():
531
+ async def test_duplicate_target_device(runner):
374
532
  """Test that defining both --host or --alias gives an error."""
375
- runner = CliRunner()
376
-
377
533
  res = await runner.invoke(
378
534
  cli,
379
535
  [
@@ -387,9 +543,12 @@ async def test_duplicate_target_device():
387
543
  assert "Error: Use either --alias or --host, not both." in res.output
388
544
 
389
545
 
390
- async def test_discover(discovery_mock, mocker):
546
+ async def test_discover(discovery_mock, mocker, runner):
391
547
  """Test discovery output."""
392
- runner = CliRunner()
548
+ # These will mock the features to avoid accessing non-existing
549
+ mocker.patch("kasa.device.Device.features", return_value={})
550
+ mocker.patch("kasa.iot.iotdevice.IotDevice.features", return_value={})
551
+
393
552
  res = await runner.invoke(
394
553
  cli,
395
554
  [
@@ -406,9 +565,31 @@ async def test_discover(discovery_mock, mocker):
406
565
  assert res.exit_code == 0
407
566
 
408
567
 
409
- async def test_discover_unsupported(unsupported_device_info):
568
+ async def test_discover_host(discovery_mock, mocker, runner):
569
+ """Test discovery output."""
570
+ # These will mock the features to avoid accessing non-existing
571
+ mocker.patch("kasa.device.Device.features", return_value={})
572
+ mocker.patch("kasa.iot.iotdevice.IotDevice.features", return_value={})
573
+
574
+ res = await runner.invoke(
575
+ cli,
576
+ [
577
+ "--discovery-timeout",
578
+ 0,
579
+ "--host",
580
+ "127.0.0.123",
581
+ "--username",
582
+ "foo",
583
+ "--password",
584
+ "bar",
585
+ "--verbose",
586
+ ],
587
+ )
588
+ assert res.exit_code == 0
589
+
590
+
591
+ async def test_discover_unsupported(unsupported_device_info, runner):
410
592
  """Test discovery output."""
411
- runner = CliRunner()
412
593
  res = await runner.invoke(
413
594
  cli,
414
595
  [
@@ -427,9 +608,8 @@ async def test_discover_unsupported(unsupported_device_info):
427
608
  assert "== Discovery Result ==" in res.output
428
609
 
429
610
 
430
- async def test_host_unsupported(unsupported_device_info):
611
+ async def test_host_unsupported(unsupported_device_info, runner):
431
612
  """Test discovery output."""
432
- runner = CliRunner()
433
613
  host = "127.0.0.1"
434
614
 
435
615
  res = await runner.invoke(
@@ -441,24 +621,24 @@ async def test_host_unsupported(unsupported_device_info):
441
621
  "foo",
442
622
  "--password",
443
623
  "bar",
624
+ "--debug",
444
625
  ],
445
626
  )
446
627
 
447
628
  assert res.exit_code != 0
448
- assert isinstance(res.exception, UnsupportedDeviceException)
629
+ assert isinstance(res.exception, UnsupportedDeviceError)
449
630
 
450
631
 
451
632
  @new_discovery
452
- async def test_discover_auth_failed(discovery_mock, mocker):
633
+ async def test_discover_auth_failed(discovery_mock, mocker, runner):
453
634
  """Test discovery output."""
454
- runner = CliRunner()
455
635
  host = "127.0.0.1"
456
636
  discovery_mock.ip = host
457
637
  device_class = Discover._get_device_class(discovery_mock.discovery_data)
458
638
  mocker.patch.object(
459
639
  device_class,
460
640
  "update",
461
- side_effect=AuthenticationException("Failed to authenticate"),
641
+ side_effect=AuthenticationError("Failed to authenticate"),
462
642
  )
463
643
  res = await runner.invoke(
464
644
  cli,
@@ -480,16 +660,15 @@ async def test_discover_auth_failed(discovery_mock, mocker):
480
660
 
481
661
 
482
662
  @new_discovery
483
- async def test_host_auth_failed(discovery_mock, mocker):
663
+ async def test_host_auth_failed(discovery_mock, mocker, runner):
484
664
  """Test discovery output."""
485
- runner = CliRunner()
486
665
  host = "127.0.0.1"
487
666
  discovery_mock.ip = host
488
667
  device_class = Discover._get_device_class(discovery_mock.discovery_data)
489
668
  mocker.patch.object(
490
669
  device_class,
491
670
  "update",
492
- side_effect=AuthenticationException("Failed to authenticate"),
671
+ side_effect=AuthenticationError("Failed to authenticate"),
493
672
  )
494
673
  res = await runner.invoke(
495
674
  cli,
@@ -500,23 +679,22 @@ async def test_host_auth_failed(discovery_mock, mocker):
500
679
  "foo",
501
680
  "--password",
502
681
  "bar",
682
+ "--debug",
503
683
  ],
504
684
  )
505
685
 
506
686
  assert res.exit_code != 0
507
- assert isinstance(res.exception, AuthenticationException)
687
+ assert isinstance(res.exception, AuthenticationError)
508
688
 
509
689
 
510
690
  @pytest.mark.parametrize("device_type", list(TYPE_TO_CLASS))
511
- async def test_type_param(device_type, mocker):
691
+ async def test_type_param(device_type, mocker, runner):
512
692
  """Test for handling only one of username or password supplied."""
513
- runner = CliRunner()
514
-
515
693
  result_device = FileNotFoundError
516
- pass_dev = click.make_pass_decorator(SmartDevice)
694
+ pass_dev = click.make_pass_decorator(Device)
517
695
 
518
696
  @pass_dev
519
- async def _state(dev: SmartDevice):
697
+ async def _state(dev: Device):
520
698
  nonlocal result_device
521
699
  result_device = dev
522
700
 
@@ -529,3 +707,179 @@ async def test_type_param(device_type, mocker):
529
707
  )
530
708
  assert res.exit_code == 0
531
709
  assert isinstance(result_device, expected_type)
710
+
711
+
712
+ @pytest.mark.skip(
713
+ "Skip until pytest-asyncio supports pytest 8.0, https://github.com/pytest-dev/pytest-asyncio/issues/737"
714
+ )
715
+ async def test_shell(dev: Device, mocker, runner):
716
+ """Test that the shell commands tries to embed a shell."""
717
+ mocker.patch("kasa.Discover.discover", return_value=[dev])
718
+ # repl = mocker.patch("ptpython.repl")
719
+ mocker.patch.dict(
720
+ "sys.modules",
721
+ {"ptpython": mocker.MagicMock(), "ptpython.repl": mocker.MagicMock()},
722
+ )
723
+ embed = mocker.patch("ptpython.repl.embed")
724
+ res = await runner.invoke(cli, ["shell"], obj=dev)
725
+ assert res.exit_code == 0
726
+ embed.assert_called()
727
+
728
+
729
+ async def test_errors(mocker, runner):
730
+ err = KasaException("Foobar")
731
+
732
+ # Test masking
733
+ mocker.patch("kasa.Discover.discover", side_effect=err)
734
+ res = await runner.invoke(
735
+ cli,
736
+ ["--username", "foo", "--password", "bar"],
737
+ )
738
+ assert res.exit_code == 1
739
+ assert "Raised error: Foobar" in res.output
740
+ assert "Run with --debug enabled to see stacktrace" in res.output
741
+ assert isinstance(res.exception, SystemExit)
742
+
743
+ # Test --debug
744
+ res = await runner.invoke(
745
+ cli,
746
+ ["--debug"],
747
+ )
748
+ assert res.exit_code == 1
749
+ assert "Raised error: Foobar" in res.output
750
+ assert res.exception == err
751
+
752
+ # Test no device passed to subcommand
753
+ mocker.patch("kasa.Discover.discover", return_value={})
754
+ res = await runner.invoke(
755
+ cli,
756
+ ["sysinfo"],
757
+ )
758
+ assert res.exit_code == 1
759
+ assert (
760
+ "Raised error: Managed to invoke callback without a context object of type 'Device' existing."
761
+ in res.output.replace("\n", "") # Remove newlines from rich formatting
762
+ )
763
+ assert isinstance(res.exception, SystemExit)
764
+
765
+ # Test click error
766
+ res = await runner.invoke(
767
+ cli,
768
+ ["--foobar"],
769
+ )
770
+ assert res.exit_code == 2
771
+ assert "Raised error:" not in res.output
772
+
773
+
774
+ async def test_feature(mocker, runner):
775
+ """Test feature command."""
776
+ dummy_device = await get_device_for_fixture_protocol(
777
+ "P300(EU)_1.0_1.0.13.json", "SMART"
778
+ )
779
+ mocker.patch("kasa.discover.Discover.discover_single", return_value=dummy_device)
780
+ res = await runner.invoke(
781
+ cli,
782
+ ["--host", "127.0.0.123", "--debug", "feature"],
783
+ catch_exceptions=False,
784
+ )
785
+ assert "LED" in res.output
786
+ assert "== Child " in res.output # child listing
787
+
788
+ assert res.exit_code == 0
789
+
790
+
791
+ async def test_features_all(discovery_mock, mocker, runner):
792
+ """Test feature command on all fixtures."""
793
+ res = await runner.invoke(
794
+ cli,
795
+ ["--host", "127.0.0.123", "--debug", "feature"],
796
+ catch_exceptions=False,
797
+ )
798
+ assert "== Features ==" in res.output
799
+ assert res.exit_code == 0
800
+
801
+
802
+ async def test_feature_single(mocker, runner):
803
+ """Test feature command returning single value."""
804
+ dummy_device = await get_device_for_fixture_protocol(
805
+ "P300(EU)_1.0_1.0.13.json", "SMART"
806
+ )
807
+ mocker.patch("kasa.discover.Discover.discover_single", return_value=dummy_device)
808
+ res = await runner.invoke(
809
+ cli,
810
+ ["--host", "127.0.0.123", "--debug", "feature", "led"],
811
+ catch_exceptions=False,
812
+ )
813
+ assert "LED" in res.output
814
+ assert "== Features ==" not in res.output
815
+ assert res.exit_code == 0
816
+
817
+
818
+ async def test_feature_missing(mocker, runner):
819
+ """Test feature command returning single value."""
820
+ dummy_device = await get_device_for_fixture_protocol(
821
+ "P300(EU)_1.0_1.0.13.json", "SMART"
822
+ )
823
+ mocker.patch("kasa.discover.Discover.discover_single", return_value=dummy_device)
824
+ res = await runner.invoke(
825
+ cli,
826
+ ["--host", "127.0.0.123", "--debug", "feature", "missing"],
827
+ catch_exceptions=False,
828
+ )
829
+ assert "No feature by name 'missing'" in res.output
830
+ assert "== Features ==" not in res.output
831
+ assert res.exit_code == 0
832
+
833
+
834
+ async def test_feature_set(mocker, runner):
835
+ """Test feature command's set value."""
836
+ dummy_device = await get_device_for_fixture_protocol(
837
+ "P300(EU)_1.0_1.0.13.json", "SMART"
838
+ )
839
+ led_setter = mocker.patch("kasa.smart.modules.led.Led.set_led")
840
+ mocker.patch("kasa.discover.Discover.discover_single", return_value=dummy_device)
841
+
842
+ res = await runner.invoke(
843
+ cli,
844
+ ["--host", "127.0.0.123", "--debug", "feature", "led", "True"],
845
+ catch_exceptions=False,
846
+ )
847
+
848
+ led_setter.assert_called_with(True)
849
+ assert "Changing led from False to True" in res.output
850
+ assert res.exit_code == 0
851
+
852
+
853
+ async def test_feature_set_child(mocker, runner):
854
+ """Test feature command's set value."""
855
+ dummy_device = await get_device_for_fixture_protocol(
856
+ "P300(EU)_1.0_1.0.13.json", "SMART"
857
+ )
858
+ setter = mocker.patch("kasa.smart.smartdevice.SmartDevice.set_state")
859
+
860
+ mocker.patch("kasa.discover.Discover.discover_single", return_value=dummy_device)
861
+ get_child_device = mocker.spy(dummy_device, "get_child_device")
862
+
863
+ child_id = "000000000000000000000000000000000000000001"
864
+
865
+ res = await runner.invoke(
866
+ cli,
867
+ [
868
+ "--host",
869
+ "127.0.0.123",
870
+ "--debug",
871
+ "feature",
872
+ "--child",
873
+ child_id,
874
+ "state",
875
+ "True",
876
+ ],
877
+ catch_exceptions=False,
878
+ )
879
+
880
+ get_child_device.assert_called()
881
+ setter.assert_called_with(True)
882
+
883
+ assert f"Targeting child device {child_id}"
884
+ assert "Changing state from False to True" in res.output
885
+ assert res.exit_code == 0