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
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,37 +7,63 @@ import pytest
6
7
  from asyncclick.testing import CliRunner
7
8
 
8
9
  from kasa import (
9
- AuthenticationException,
10
+ AuthenticationError,
10
11
  Credentials,
12
+ Device,
13
+ DeviceError,
11
14
  EmeterStatus,
12
- SmartDevice,
13
- SmartDeviceException,
14
- UnsupportedDeviceException,
15
+ KasaException,
16
+ Module,
17
+ UnsupportedDeviceError,
15
18
  )
16
19
  from kasa.cli import (
17
20
  TYPE_TO_CLASS,
18
21
  alias,
19
22
  brightness,
20
23
  cli,
24
+ cmd_command,
25
+ effect,
21
26
  emeter,
27
+ hsv,
28
+ led,
22
29
  raw_command,
23
30
  reboot,
24
31
  state,
25
32
  sysinfo,
33
+ temperature,
26
34
  toggle,
27
35
  update_credentials,
28
36
  wifi,
29
37
  )
30
38
  from kasa.discover import Discover, DiscoveryResult
31
- from kasa.smartprotocol import SmartProtocol
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)
32
55
 
33
- from .conftest import device_iot, device_smart, handle_turn_on, new_discovery, turn_on
56
+ return runner
34
57
 
35
58
 
36
- async def test_update_called_by_cli(dev, mocker):
59
+ async def test_update_called_by_cli(dev, mocker, runner):
37
60
  """Test that device update is called on main."""
38
- runner = CliRunner()
39
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
+
40
67
  mocker.patch("kasa.discover.Discover.discover_single", return_value=dev)
41
68
 
42
69
  res = await runner.invoke(
@@ -49,25 +76,23 @@ async def test_update_called_by_cli(dev, mocker):
49
76
  "--password",
50
77
  "bar",
51
78
  ],
79
+ catch_exceptions=False,
52
80
  )
53
81
  assert res.exit_code == 0
54
82
  update.assert_called()
55
83
 
56
84
 
57
- @device_iot
58
- async def test_sysinfo(dev):
59
- runner = CliRunner()
85
+ async def test_sysinfo(dev: Device, runner):
60
86
  res = await runner.invoke(sysinfo, obj=dev)
61
87
  assert "System info" in res.output
62
- assert dev.alias in res.output
88
+ assert dev.model in res.output
63
89
 
64
90
 
65
91
  @turn_on
66
- async def test_state(dev, turn_on):
92
+ async def test_state(dev, turn_on, runner):
67
93
  await handle_turn_on(dev, turn_on)
68
- runner = CliRunner()
69
- res = await runner.invoke(state, obj=dev)
70
94
  await dev.update()
95
+ res = await runner.invoke(state, obj=dev)
71
96
 
72
97
  if dev.is_on:
73
98
  assert "Device state: True" in res.output
@@ -76,21 +101,17 @@ async def test_state(dev, turn_on):
76
101
 
77
102
 
78
103
  @turn_on
79
- async def test_toggle(dev, turn_on, mocker):
104
+ async def test_toggle(dev, turn_on, runner):
80
105
  await handle_turn_on(dev, turn_on)
81
- runner = CliRunner()
82
- await runner.invoke(toggle, obj=dev)
83
-
84
- if turn_on:
85
- assert not dev.is_on
86
- else:
87
- assert dev.is_on
106
+ await dev.update()
107
+ assert dev.is_on == turn_on
88
108
 
109
+ await runner.invoke(toggle, obj=dev)
110
+ await dev.update()
111
+ assert dev.is_on != turn_on
89
112
 
90
- @device_iot
91
- async def test_alias(dev):
92
- runner = CliRunner()
93
113
 
114
+ async def test_alias(dev, runner):
94
115
  res = await runner.invoke(alias, obj=dev)
95
116
  assert f"Alias: {dev.alias}" in res.output
96
117
 
@@ -99,6 +120,7 @@ async def test_alias(dev):
99
120
  new_alias = "new alias"
100
121
  res = await runner.invoke(alias, [new_alias], obj=dev)
101
122
  assert f"Setting alias to {new_alias}" in res.output
123
+ await dev.update()
102
124
 
103
125
  res = await runner.invoke(alias, obj=dev)
104
126
  assert f"Alias: {new_alias}" in res.output
@@ -106,12 +128,11 @@ async def test_alias(dev):
106
128
  await dev.set_alias(old_alias)
107
129
 
108
130
 
109
- async def test_raw_command(dev, mocker):
110
- runner = CliRunner()
131
+ async def test_raw_command(dev, mocker, runner):
111
132
  update = mocker.patch.object(dev, "update")
112
- from kasa.tapo import TapoDevice
133
+ from kasa.smart import SmartDevice
113
134
 
114
- if isinstance(dev, TapoDevice):
135
+ if isinstance(dev, SmartDevice):
115
136
  params = ["na", "get_device_info"]
116
137
  else:
117
138
  params = ["system", "get_sysinfo"]
@@ -129,10 +150,38 @@ async def test_raw_command(dev, mocker):
129
150
  assert "Usage" in res.output
130
151
 
131
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
+
132
182
  @device_smart
133
- async def test_reboot(dev, mocker):
183
+ async def test_reboot(dev, mocker, runner):
134
184
  """Test that reboot works on SMART devices."""
135
- runner = CliRunner()
136
185
  query_mock = mocker.patch.object(dev.protocol, "query")
137
186
 
138
187
  res = await runner.invoke(
@@ -145,17 +194,15 @@ async def test_reboot(dev, mocker):
145
194
 
146
195
 
147
196
  @device_smart
148
- async def test_wifi_scan(dev):
149
- runner = CliRunner()
197
+ async def test_wifi_scan(dev, runner):
150
198
  res = await runner.invoke(wifi, ["scan"], obj=dev)
151
199
 
152
200
  assert res.exit_code == 0
153
- assert re.search(r"Found \d wifi networks!", res.output)
201
+ assert re.search(r"Found [\d]+ wifi networks!", res.output)
154
202
 
155
203
 
156
204
  @device_smart
157
- async def test_wifi_join(dev, mocker):
158
- runner = CliRunner()
205
+ async def test_wifi_join(dev, mocker, runner):
159
206
  update = mocker.patch.object(dev, "update")
160
207
  res = await runner.invoke(
161
208
  wifi,
@@ -172,8 +219,7 @@ async def test_wifi_join(dev, mocker):
172
219
 
173
220
 
174
221
  @device_smart
175
- async def test_wifi_join_no_creds(dev):
176
- runner = CliRunner()
222
+ async def test_wifi_join_no_creds(dev, runner):
177
223
  dev.protocol._transport._credentials = None
178
224
  res = await runner.invoke(
179
225
  wifi,
@@ -182,15 +228,12 @@ async def test_wifi_join_no_creds(dev):
182
228
  )
183
229
 
184
230
  assert res.exit_code != 0
185
- assert isinstance(res.exception, AuthenticationException)
231
+ assert isinstance(res.exception, AuthenticationError)
186
232
 
187
233
 
188
234
  @device_smart
189
- async def test_wifi_join_exception(dev, mocker):
190
- runner = CliRunner()
191
- mocker.patch.object(
192
- dev.protocol, "query", side_effect=SmartDeviceException(error_code=9999)
193
- )
235
+ async def test_wifi_join_exception(dev, mocker, runner):
236
+ mocker.patch.object(dev.protocol, "query", side_effect=DeviceError(error_code=9999))
194
237
  res = await runner.invoke(
195
238
  wifi,
196
239
  ["join", "FOOBAR", "--keytype", "wpa_psk", "--password", "foobar"],
@@ -198,12 +241,11 @@ async def test_wifi_join_exception(dev, mocker):
198
241
  )
199
242
 
200
243
  assert res.exit_code != 0
201
- assert isinstance(res.exception, SmartDeviceException)
244
+ assert isinstance(res.exception, KasaException)
202
245
 
203
246
 
204
247
  @device_smart
205
- async def test_update_credentials(dev):
206
- runner = CliRunner()
248
+ async def test_update_credentials(dev, runner):
207
249
  res = await runner.invoke(
208
250
  update_credentials,
209
251
  ["--username", "foo", "--password", "bar"],
@@ -218,9 +260,7 @@ async def test_update_credentials(dev):
218
260
  )
219
261
 
220
262
 
221
- async def test_emeter(dev: SmartDevice, mocker):
222
- runner = CliRunner()
223
-
263
+ async def test_emeter(dev: Device, mocker, runner):
224
264
  res = await runner.invoke(emeter, obj=dev)
225
265
  if not dev.has_emeter:
226
266
  assert "Device has no emeter" in res.output
@@ -247,57 +287,166 @@ async def test_emeter(dev: SmartDevice, mocker):
247
287
  assert "Voltage: 122.066 V" in res.output
248
288
  assert realtime_emeter.call_count == 2
249
289
 
250
- monthly = mocker.patch.object(dev, "get_emeter_monthly")
251
- 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}
252
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
253
297
  assert "For year" in res.output
254
298
  assert "1, 1234" in res.output
255
299
  monthly.assert_called_with(year=1900)
256
300
 
257
- daily = mocker.patch.object(dev, "get_emeter_daily")
258
- 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}
259
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
260
308
  assert "For month" in res.output
261
309
  assert "1, 1234" in res.output
262
310
  daily.assert_called_with(year=1900, month=12)
263
311
 
264
312
 
265
- @device_iot
266
- async def test_brightness(dev):
267
- runner = CliRunner()
313
+ async def test_brightness(dev: Device, runner):
268
314
  res = await runner.invoke(brightness, obj=dev)
269
- if not dev.is_dimmable:
315
+ if not (light := dev.modules.get(Module.Light)) or not light.is_dimmable:
270
316
  assert "This device does not support brightness." in res.output
271
317
  return
272
318
 
273
319
  res = await runner.invoke(brightness, obj=dev)
274
- assert f"Brightness: {dev.brightness}" in res.output
320
+ assert f"Brightness: {light.brightness}" in res.output
275
321
 
276
322
  res = await runner.invoke(brightness, ["12"], obj=dev)
277
323
  assert "Setting brightness" in res.output
324
+ await dev.update()
278
325
 
279
326
  res = await runner.invoke(brightness, obj=dev)
280
327
  assert "Brightness: 12" in res.output
281
328
 
282
329
 
283
- @device_iot
284
- 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):
285
431
  """Test that the json output produces correct output."""
286
- mocker.patch("kasa.Discover.discover", return_value=[dev])
287
- 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
+
288
437
  res = await runner.invoke(cli, ["--json", "state"], obj=dev)
289
438
  assert res.exit_code == 0
290
439
  assert json.loads(res.output) == dev.internal_state
291
440
 
292
441
 
293
442
  @new_discovery
294
- async def test_credentials(discovery_mock, mocker):
443
+ async def test_credentials(discovery_mock, mocker, runner):
295
444
  """Test credentials are passed correctly from cli to device."""
296
445
  # Patch state to echo username and password
297
- pass_dev = click.make_pass_decorator(SmartDevice)
446
+ pass_dev = click.make_pass_decorator(Device)
298
447
 
299
448
  @pass_dev
300
- async def _state(dev: SmartDevice):
449
+ async def _state(dev: Device):
301
450
  if dev.credentials:
302
451
  click.echo(
303
452
  f"Username:{dev.credentials.username} Password:{dev.credentials.password}"
@@ -305,11 +454,7 @@ async def test_credentials(discovery_mock, mocker):
305
454
 
306
455
  mocker.patch("kasa.cli.state", new=_state)
307
456
 
308
- mocker.patch("kasa.IotProtocol.query", return_value=discovery_mock.query_data)
309
- mocker.patch("kasa.SmartProtocol.query", return_value=discovery_mock.query_data)
310
-
311
457
  dr = DiscoveryResult(**discovery_mock.discovery_data["result"])
312
- runner = CliRunner()
313
458
  res = await runner.invoke(
314
459
  cli,
315
460
  [
@@ -330,11 +475,15 @@ async def test_credentials(discovery_mock, mocker):
330
475
  assert "Username:foo Password:bar\n" in res.output
331
476
 
332
477
 
333
- @device_iot
334
- async def test_without_device_type(dev, mocker):
478
+ async def test_without_device_type(dev, mocker, runner):
335
479
  """Test connecting without the device type."""
336
- runner = CliRunner()
337
- 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
+
338
487
  res = await runner.invoke(
339
488
  cli,
340
489
  [
@@ -344,16 +493,23 @@ async def test_without_device_type(dev, mocker):
344
493
  "foo",
345
494
  "--password",
346
495
  "bar",
496
+ "--discovery-timeout",
497
+ "7",
347
498
  ],
348
499
  )
349
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
+ )
350
508
 
351
509
 
352
510
  @pytest.mark.parametrize("auth_param", ["--username", "--password"])
353
- async def test_invalid_credential_params(auth_param):
511
+ async def test_invalid_credential_params(auth_param, runner):
354
512
  """Test for handling only one of username or password supplied."""
355
- runner = CliRunner()
356
-
357
513
  res = await runner.invoke(
358
514
  cli,
359
515
  [
@@ -372,10 +528,8 @@ async def test_invalid_credential_params(auth_param):
372
528
  )
373
529
 
374
530
 
375
- async def test_duplicate_target_device():
531
+ async def test_duplicate_target_device(runner):
376
532
  """Test that defining both --host or --alias gives an error."""
377
- runner = CliRunner()
378
-
379
533
  res = await runner.invoke(
380
534
  cli,
381
535
  [
@@ -389,9 +543,12 @@ async def test_duplicate_target_device():
389
543
  assert "Error: Use either --alias or --host, not both." in res.output
390
544
 
391
545
 
392
- async def test_discover(discovery_mock, mocker):
546
+ async def test_discover(discovery_mock, mocker, runner):
393
547
  """Test discovery output."""
394
- 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
+
395
552
  res = await runner.invoke(
396
553
  cli,
397
554
  [
@@ -408,9 +565,31 @@ async def test_discover(discovery_mock, mocker):
408
565
  assert res.exit_code == 0
409
566
 
410
567
 
411
- 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):
412
592
  """Test discovery output."""
413
- runner = CliRunner()
414
593
  res = await runner.invoke(
415
594
  cli,
416
595
  [
@@ -429,9 +608,8 @@ async def test_discover_unsupported(unsupported_device_info):
429
608
  assert "== Discovery Result ==" in res.output
430
609
 
431
610
 
432
- async def test_host_unsupported(unsupported_device_info):
611
+ async def test_host_unsupported(unsupported_device_info, runner):
433
612
  """Test discovery output."""
434
- runner = CliRunner()
435
613
  host = "127.0.0.1"
436
614
 
437
615
  res = await runner.invoke(
@@ -443,24 +621,24 @@ async def test_host_unsupported(unsupported_device_info):
443
621
  "foo",
444
622
  "--password",
445
623
  "bar",
624
+ "--debug",
446
625
  ],
447
626
  )
448
627
 
449
628
  assert res.exit_code != 0
450
- assert isinstance(res.exception, UnsupportedDeviceException)
629
+ assert isinstance(res.exception, UnsupportedDeviceError)
451
630
 
452
631
 
453
632
  @new_discovery
454
- async def test_discover_auth_failed(discovery_mock, mocker):
633
+ async def test_discover_auth_failed(discovery_mock, mocker, runner):
455
634
  """Test discovery output."""
456
- runner = CliRunner()
457
635
  host = "127.0.0.1"
458
636
  discovery_mock.ip = host
459
637
  device_class = Discover._get_device_class(discovery_mock.discovery_data)
460
638
  mocker.patch.object(
461
639
  device_class,
462
640
  "update",
463
- side_effect=AuthenticationException("Failed to authenticate"),
641
+ side_effect=AuthenticationError("Failed to authenticate"),
464
642
  )
465
643
  res = await runner.invoke(
466
644
  cli,
@@ -482,16 +660,15 @@ async def test_discover_auth_failed(discovery_mock, mocker):
482
660
 
483
661
 
484
662
  @new_discovery
485
- async def test_host_auth_failed(discovery_mock, mocker):
663
+ async def test_host_auth_failed(discovery_mock, mocker, runner):
486
664
  """Test discovery output."""
487
- runner = CliRunner()
488
665
  host = "127.0.0.1"
489
666
  discovery_mock.ip = host
490
667
  device_class = Discover._get_device_class(discovery_mock.discovery_data)
491
668
  mocker.patch.object(
492
669
  device_class,
493
670
  "update",
494
- side_effect=AuthenticationException("Failed to authenticate"),
671
+ side_effect=AuthenticationError("Failed to authenticate"),
495
672
  )
496
673
  res = await runner.invoke(
497
674
  cli,
@@ -502,23 +679,22 @@ async def test_host_auth_failed(discovery_mock, mocker):
502
679
  "foo",
503
680
  "--password",
504
681
  "bar",
682
+ "--debug",
505
683
  ],
506
684
  )
507
685
 
508
686
  assert res.exit_code != 0
509
- assert isinstance(res.exception, AuthenticationException)
687
+ assert isinstance(res.exception, AuthenticationError)
510
688
 
511
689
 
512
690
  @pytest.mark.parametrize("device_type", list(TYPE_TO_CLASS))
513
- async def test_type_param(device_type, mocker):
691
+ async def test_type_param(device_type, mocker, runner):
514
692
  """Test for handling only one of username or password supplied."""
515
- runner = CliRunner()
516
-
517
693
  result_device = FileNotFoundError
518
- pass_dev = click.make_pass_decorator(SmartDevice)
694
+ pass_dev = click.make_pass_decorator(Device)
519
695
 
520
696
  @pass_dev
521
- async def _state(dev: SmartDevice):
697
+ async def _state(dev: Device):
522
698
  nonlocal result_device
523
699
  result_device = dev
524
700
 
@@ -531,3 +707,179 @@ async def test_type_param(device_type, mocker):
531
707
  )
532
708
  assert res.exit_code == 0
533
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