python-kasa 0.7.0.dev5__py3-none-any.whl → 0.7.0.2__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 (64) hide show
  1. kasa/aestransport.py +13 -4
  2. kasa/cli.py +60 -45
  3. kasa/device.py +110 -2
  4. kasa/discover.py +2 -1
  5. kasa/exceptions.py +10 -0
  6. kasa/feature.py +88 -11
  7. kasa/httpclient.py +1 -1
  8. kasa/interfaces/energy.py +6 -0
  9. kasa/interfaces/light.py +61 -1
  10. kasa/interfaces/lighteffect.py +41 -1
  11. kasa/interfaces/lightpreset.py +70 -2
  12. kasa/iot/iotdevice.py +6 -1
  13. kasa/iot/iotstrip.py +23 -8
  14. kasa/iot/modules/lightpreset.py +2 -1
  15. kasa/module.py +42 -1
  16. kasa/smart/effects.py +25 -0
  17. kasa/smart/modules/__init__.py +2 -0
  18. kasa/smart/modules/alarm.py +1 -0
  19. kasa/smart/modules/autooff.py +3 -1
  20. kasa/smart/modules/brightness.py +14 -1
  21. kasa/smart/modules/childdevice.py +39 -1
  22. kasa/smart/modules/firmware.py +4 -1
  23. kasa/smart/modules/frostprotection.py +0 -22
  24. kasa/smart/modules/humiditysensor.py +1 -0
  25. kasa/smart/modules/led.py +1 -1
  26. kasa/smart/modules/lighteffect.py +70 -6
  27. kasa/smart/modules/lightpreset.py +2 -1
  28. kasa/smart/modules/lightstripeffect.py +38 -8
  29. kasa/smart/modules/lighttransition.py +101 -55
  30. kasa/smart/modules/reportmode.py +2 -0
  31. kasa/smart/modules/temperaturecontrol.py +3 -2
  32. kasa/smart/modules/temperaturesensor.py +3 -2
  33. kasa/smart/modules/time.py +3 -2
  34. kasa/smart/modules/waterleaksensor.py +2 -0
  35. kasa/smart/smartdevice.py +10 -5
  36. kasa/smartprotocol.py +42 -6
  37. kasa/tests/device_fixtures.py +9 -3
  38. kasa/tests/discovery_fixtures.py +6 -2
  39. kasa/tests/fakeprotocol_smart.py +73 -4
  40. kasa/tests/fixtureinfo.py +21 -3
  41. kasa/tests/smart/modules/test_firmware.py +12 -1
  42. kasa/tests/smart/modules/test_light_effect.py +42 -0
  43. kasa/tests/smart/modules/test_light_strip_effect.py +101 -0
  44. kasa/tests/smart/modules/test_lighttransition.py +80 -0
  45. kasa/tests/test_aestransport.py +27 -0
  46. kasa/tests/test_childdevice.py +21 -1
  47. kasa/tests/test_cli.py +18 -3
  48. kasa/tests/test_common_modules.py +9 -5
  49. kasa/tests/test_device.py +2 -1
  50. kasa/tests/test_device_factory.py +35 -17
  51. kasa/tests/test_emeter.py +8 -8
  52. kasa/tests/test_feature.py +6 -2
  53. kasa/tests/test_httpclient.py +2 -2
  54. kasa/tests/test_iotdevice.py +5 -4
  55. kasa/tests/test_readme_examples.py +59 -0
  56. kasa/tests/test_smartdevice.py +4 -3
  57. kasa/tests/test_smartprotocol.py +109 -7
  58. kasa/tests/test_strip.py +15 -2
  59. kasa/xortransport.py +3 -3
  60. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/METADATA +102 -129
  61. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/RECORD +64 -62
  62. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/LICENSE +0 -0
  63. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/WHEEL +0 -0
  64. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/entry_points.txt +0 -0
kasa/smartprotocol.py CHANGED
@@ -47,6 +47,9 @@ class SmartProtocol(BaseProtocol):
47
47
  self._terminal_uuid: str = base64.b64encode(md5(uuid.uuid4().bytes)).decode()
48
48
  self._request_id_generator = SnowflakeId(1, 1)
49
49
  self._query_lock = asyncio.Lock()
50
+ self._multi_request_batch_size = (
51
+ self._transport._config.batch_size or self.DEFAULT_MULTI_REQUEST_BATCH_SIZE
52
+ )
50
53
 
51
54
  def get_smart_request(self, method, params=None) -> str:
52
55
  """Get a request message as a string."""
@@ -117,9 +120,16 @@ class SmartProtocol(BaseProtocol):
117
120
 
118
121
  end = len(multi_requests)
119
122
  # Break the requests down as there can be a size limit
120
- step = (
121
- self._transport._config.batch_size or self.DEFAULT_MULTI_REQUEST_BATCH_SIZE
122
- )
123
+ step = self._multi_request_batch_size
124
+ if step == 1:
125
+ # If step is 1 do not send request batches
126
+ for request in multi_requests:
127
+ method = request["method"]
128
+ req = self.get_smart_request(method, request["params"])
129
+ resp = await self._transport.send(req)
130
+ self._handle_response_error_code(resp, method, raise_on_error=False)
131
+ multi_result[method] = resp["result"]
132
+ return multi_result
123
133
  for i in range(0, end, step):
124
134
  requests_step = multi_requests[i : i + step]
125
135
 
@@ -141,7 +151,25 @@ class SmartProtocol(BaseProtocol):
141
151
  batch_name,
142
152
  pf(response_step),
143
153
  )
144
- self._handle_response_error_code(response_step, batch_name)
154
+ try:
155
+ self._handle_response_error_code(response_step, batch_name)
156
+ except DeviceError as ex:
157
+ # P100 sometimes raises JSON_DECODE_FAIL_ERROR or INTERNAL_UNKNOWN_ERROR
158
+ # on batched request so disable batching
159
+ if (
160
+ ex.error_code
161
+ in {
162
+ SmartErrorCode.JSON_DECODE_FAIL_ERROR,
163
+ SmartErrorCode.INTERNAL_UNKNOWN_ERROR,
164
+ }
165
+ and self._multi_request_batch_size != 1
166
+ ):
167
+ self._multi_request_batch_size = 1
168
+ raise _RetryableError(
169
+ "JSON Decode failure, multi requests disabled"
170
+ ) from ex
171
+ raise ex
172
+
145
173
  responses = response_step["result"]["responses"]
146
174
  for response in responses:
147
175
  method = response["method"]
@@ -239,12 +267,20 @@ class SmartProtocol(BaseProtocol):
239
267
  response_result[response_list_name].extend(next_batch[response_list_name])
240
268
 
241
269
  def _handle_response_error_code(self, resp_dict: dict, method, raise_on_error=True):
242
- error_code = SmartErrorCode(resp_dict.get("error_code")) # type: ignore[arg-type]
243
- if error_code == SmartErrorCode.SUCCESS:
270
+ error_code_raw = resp_dict.get("error_code")
271
+ try:
272
+ error_code = SmartErrorCode.from_int(error_code_raw)
273
+ except ValueError:
274
+ _LOGGER.warning("Received unknown error code: %s", error_code_raw)
275
+ error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR
276
+
277
+ if error_code is SmartErrorCode.SUCCESS:
244
278
  return
279
+
245
280
  if not raise_on_error:
246
281
  resp_dict["result"] = error_code
247
282
  return
283
+
248
284
  msg = (
249
285
  f"Error querying device: {self._host}: "
250
286
  + f"{error_code.name}({error_code.value})"
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import AsyncGenerator
3
+ from collections.abc import AsyncGenerator
4
4
 
5
5
  import pytest
6
6
 
@@ -15,7 +15,13 @@ from kasa.smart import SmartDevice
15
15
 
16
16
  from .fakeprotocol_iot import FakeIotProtocol
17
17
  from .fakeprotocol_smart import FakeSmartProtocol
18
- from .fixtureinfo import FIXTURE_DATA, FixtureInfo, filter_fixtures, idgenerator
18
+ from .fixtureinfo import (
19
+ FIXTURE_DATA,
20
+ ComponentFilter,
21
+ FixtureInfo,
22
+ filter_fixtures,
23
+ idgenerator,
24
+ )
19
25
 
20
26
  # Tapo bulbs
21
27
  BULBS_SMART_VARIABLE_TEMP = {"L530E", "L930-5"}
@@ -175,7 +181,7 @@ def parametrize(
175
181
  *,
176
182
  model_filter=None,
177
183
  protocol_filter=None,
178
- component_filter=None,
184
+ component_filter: str | ComponentFilter | None = None,
179
185
  data_root_filter=None,
180
186
  device_type_filter=None,
181
187
  ids=None,
@@ -12,6 +12,8 @@ from .fakeprotocol_iot import FakeIotProtocol
12
12
  from .fakeprotocol_smart import FakeSmartProtocol, FakeSmartTransport
13
13
  from .fixtureinfo import FixtureInfo, filter_fixtures, idgenerator
14
14
 
15
+ DISCOVERY_MOCK_IP = "127.0.0.123"
16
+
15
17
 
16
18
  def _make_unsupported(device_family, encrypt_type):
17
19
  return {
@@ -73,7 +75,7 @@ new_discovery = parametrize_discovery(
73
75
  async def discovery_mock(request, mocker):
74
76
  """Mock discovery and patch protocol queries to use Fake protocols."""
75
77
  fixture_info: FixtureInfo = request.param
76
- yield patch_discovery({"127.0.0.123": fixture_info}, mocker)
78
+ yield patch_discovery({DISCOVERY_MOCK_IP: fixture_info}, mocker)
77
79
 
78
80
 
79
81
  def create_discovery_mock(ip: str, fixture_data: dict):
@@ -231,7 +233,9 @@ def discovery_data(request, mocker):
231
233
  return {"system": {"get_sysinfo": fixture_data["system"]["get_sysinfo"]}}
232
234
 
233
235
 
234
- @pytest.fixture(params=UNSUPPORTED_DEVICES.values(), ids=UNSUPPORTED_DEVICES.keys())
236
+ @pytest.fixture(
237
+ params=UNSUPPORTED_DEVICES.values(), ids=list(UNSUPPORTED_DEVICES.keys())
238
+ )
235
239
  def unsupported_device_info(request, mocker):
236
240
  """Return unsupported devices for cli and discovery tests."""
237
241
  discovery_data = request.param
@@ -78,7 +78,6 @@ class FakeSmartTransport(BaseTransport):
78
78
  },
79
79
  },
80
80
  ),
81
- "get_on_off_gradually_info": ("on_off_gradually", {"enable": True}),
82
81
  "get_latest_fw": (
83
82
  "firmware",
84
83
  {
@@ -164,6 +163,8 @@ class FakeSmartTransport(BaseTransport):
164
163
  return {"error_code": 0}
165
164
  elif child_method == "set_preset_rules":
166
165
  return self._set_child_preset_rules(info, child_params)
166
+ elif child_method == "set_on_off_gradually_info":
167
+ return self._set_on_off_gradually_info(info, child_params)
167
168
  elif child_method in child_device_calls:
168
169
  result = copy.deepcopy(child_device_calls[child_method])
169
170
  return {"result": result, "error_code": 0}
@@ -200,24 +201,80 @@ class FakeSmartTransport(BaseTransport):
200
201
  "Method %s not implemented for children" % child_method
201
202
  )
202
203
 
204
+ def _get_on_off_gradually_info(self, info, params):
205
+ if self.components["on_off_gradually"] == 1:
206
+ info["get_on_off_gradually_info"] = {"enable": True}
207
+ else:
208
+ info["get_on_off_gradually_info"] = {
209
+ "off_state": {"duration": 5, "enable": False, "max_duration": 60},
210
+ "on_state": {"duration": 5, "enable": False, "max_duration": 60},
211
+ }
212
+ return copy.deepcopy(info["get_on_off_gradually_info"])
213
+
214
+ def _set_on_off_gradually_info(self, info, params):
215
+ # Child devices can have the required properties directly in info
216
+
217
+ if self.components["on_off_gradually"] == 1:
218
+ info["get_on_off_gradually_info"] = {"enable": params["enable"]}
219
+ elif on_state := params.get("on_state"):
220
+ if "fade_on_time" in info and "gradually_on_mode" in info:
221
+ info["gradually_on_mode"] = 1 if on_state["enable"] else 0
222
+ if "duration" in on_state:
223
+ info["fade_on_time"] = on_state["duration"]
224
+ else:
225
+ info["get_on_off_gradually_info"]["on_state"]["enable"] = on_state[
226
+ "enable"
227
+ ]
228
+ if "duration" in on_state:
229
+ info["get_on_off_gradually_info"]["on_state"]["duration"] = (
230
+ on_state["duration"]
231
+ )
232
+ elif off_state := params.get("off_state"):
233
+ if "fade_off_time" in info and "gradually_off_mode" in info:
234
+ info["gradually_off_mode"] = 1 if off_state["enable"] else 0
235
+ if "duration" in off_state:
236
+ info["fade_off_time"] = off_state["duration"]
237
+ else:
238
+ info["get_on_off_gradually_info"]["off_state"]["enable"] = off_state[
239
+ "enable"
240
+ ]
241
+ if "duration" in off_state:
242
+ info["get_on_off_gradually_info"]["off_state"]["duration"] = (
243
+ off_state["duration"]
244
+ )
245
+ return {"error_code": 0}
246
+
203
247
  def _set_dynamic_light_effect(self, info, params):
204
248
  """Set or remove values as per the device behaviour."""
205
249
  info["get_device_info"]["dynamic_light_effect_enable"] = params["enable"]
206
250
  info["get_dynamic_light_effect_rules"]["enable"] = params["enable"]
207
251
  if params["enable"]:
208
252
  info["get_device_info"]["dynamic_light_effect_id"] = params["id"]
209
- info["get_dynamic_light_effect_rules"]["current_rule_id"] = params["enable"]
253
+ info["get_dynamic_light_effect_rules"]["current_rule_id"] = params["id"]
210
254
  else:
211
255
  if "dynamic_light_effect_id" in info["get_device_info"]:
212
256
  del info["get_device_info"]["dynamic_light_effect_id"]
213
257
  if "current_rule_id" in info["get_dynamic_light_effect_rules"]:
214
258
  del info["get_dynamic_light_effect_rules"]["current_rule_id"]
215
259
 
260
+ def _set_edit_dynamic_light_effect_rule(self, info, params):
261
+ """Edit dynamic light effect rule."""
262
+ rules = info["get_dynamic_light_effect_rules"]["rule_list"]
263
+ for rule in rules:
264
+ if rule["id"] == params["id"]:
265
+ rule.update(params)
266
+ return
267
+
268
+ raise Exception("Unable to find rule with id")
269
+
216
270
  def _set_light_strip_effect(self, info, params):
217
271
  """Set or remove values as per the device behaviour."""
218
272
  info["get_device_info"]["lighting_effect"]["enable"] = params["enable"]
219
273
  info["get_device_info"]["lighting_effect"]["name"] = params["name"]
220
274
  info["get_device_info"]["lighting_effect"]["id"] = params["id"]
275
+ # Brightness is not always available
276
+ if (brightness := params.get("brightness")) is not None:
277
+ info["get_device_info"]["lighting_effect"]["brightness"] = brightness
221
278
  info["get_lighting_effect"] = copy.deepcopy(params)
222
279
 
223
280
  def _set_led_info(self, info, params):
@@ -276,7 +333,7 @@ class FakeSmartTransport(BaseTransport):
276
333
  ):
277
334
  result["sum"] = len(result[list_key])
278
335
  if self.warn_fixture_missing_methods:
279
- pytest.fixtures_missing_methods.setdefault(
336
+ pytest.fixtures_missing_methods.setdefault( # type: ignore[attr-defined]
280
337
  self.fixture_name, set()
281
338
  ).add(f"{method} (incomplete '{list_key}' list)")
282
339
 
@@ -294,6 +351,13 @@ class FakeSmartTransport(BaseTransport):
294
351
  info[method] = copy.deepcopy(missing_result[1])
295
352
  result = copy.deepcopy(info[method])
296
353
  retval = {"result": result, "error_code": 0}
354
+ elif (
355
+ method == "get_on_off_gradually_info"
356
+ and "on_off_gradually" in self.components
357
+ ):
358
+ # Need to call a method here to determine which version schema to return
359
+ result = self._get_on_off_gradually_info(info, params)
360
+ return {"result": result, "error_code": 0}
297
361
  else:
298
362
  # PARAMS error returned for KS240 when get_device_usage called
299
363
  # on parent device. Could be any error code though.
@@ -305,7 +369,7 @@ class FakeSmartTransport(BaseTransport):
305
369
  }
306
370
  # Reduce warning spam by consolidating and reporting at the end of the run
307
371
  if self.warn_fixture_missing_methods:
308
- pytest.fixtures_missing_methods.setdefault(
372
+ pytest.fixtures_missing_methods.setdefault( # type: ignore[attr-defined]
309
373
  self.fixture_name, set()
310
374
  ).add(method)
311
375
  return retval
@@ -314,6 +378,9 @@ class FakeSmartTransport(BaseTransport):
314
378
  elif method == "set_dynamic_light_effect_rule_enable":
315
379
  self._set_dynamic_light_effect(info, params)
316
380
  return {"error_code": 0}
381
+ elif method == "edit_dynamic_light_effect_rule":
382
+ self._set_edit_dynamic_light_effect_rule(info, params)
383
+ return {"error_code": 0}
317
384
  elif method == "set_lighting_effect":
318
385
  self._set_light_strip_effect(info, params)
319
386
  return {"error_code": 0}
@@ -324,6 +391,8 @@ class FakeSmartTransport(BaseTransport):
324
391
  return self._set_preset_rules(info, params)
325
392
  elif method == "edit_preset_rules":
326
393
  return self._edit_preset_rules(info, params)
394
+ elif method == "set_on_off_gradually_info":
395
+ return self._set_on_off_gradually_info(info, params)
327
396
  elif method[:4] == "set_":
328
397
  target_method = f"get_{method[4:]}"
329
398
  info[target_method].update(params)
kasa/tests/fixtureinfo.py CHANGED
@@ -17,6 +17,12 @@ class FixtureInfo(NamedTuple):
17
17
  data: dict
18
18
 
19
19
 
20
+ class ComponentFilter(NamedTuple):
21
+ component_name: str
22
+ minimum_version: int = 0
23
+ maximum_version: int | None = None
24
+
25
+
20
26
  FixtureInfo.__hash__ = lambda self: hash((self.name, self.protocol)) # type: ignore[attr-defined, method-assign]
21
27
  FixtureInfo.__eq__ = lambda x, y: hash(x) == hash(y) # type: ignore[method-assign]
22
28
 
@@ -88,7 +94,7 @@ def filter_fixtures(
88
94
  data_root_filter: str | None = None,
89
95
  protocol_filter: set[str] | None = None,
90
96
  model_filter: set[str] | None = None,
91
- component_filter: str | None = None,
97
+ component_filter: str | ComponentFilter | None = None,
92
98
  device_type_filter: list[DeviceType] | None = None,
93
99
  ):
94
100
  """Filter the fixtures based on supplied parameters.
@@ -106,14 +112,26 @@ def filter_fixtures(
106
112
  file_model = file_model_region.split("(")[0]
107
113
  return file_model in model_filter
108
114
 
109
- def _component_match(fixture_data: FixtureInfo, component_filter):
115
+ def _component_match(
116
+ fixture_data: FixtureInfo, component_filter: str | ComponentFilter
117
+ ):
110
118
  if (component_nego := fixture_data.data.get("component_nego")) is None:
111
119
  return False
112
120
  components = {
113
121
  component["id"]: component["ver_code"]
114
122
  for component in component_nego["component_list"]
115
123
  }
116
- return component_filter in components
124
+ if isinstance(component_filter, str):
125
+ return component_filter in components
126
+ else:
127
+ return (
128
+ (ver_code := components.get(component_filter.component_name))
129
+ and ver_code >= component_filter.minimum_version
130
+ and (
131
+ component_filter.maximum_version is None
132
+ or ver_code <= component_filter.maximum_version
133
+ )
134
+ )
117
135
 
118
136
  def _device_type_match(fixture_data: FixtureInfo, device_type):
119
137
  if (component_nego := fixture_data.data.get("component_nego")) is None:
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import logging
5
+ from typing import TypedDict
5
6
 
6
7
  import pytest
7
8
  from pytest_mock import MockerFixture
@@ -71,7 +72,17 @@ async def test_firmware_update(
71
72
  assert fw
72
73
 
73
74
  upgrade_time = 5
74
- extras = {"reboot_time": 5, "upgrade_time": upgrade_time, "auto_upgrade": False}
75
+
76
+ class Extras(TypedDict):
77
+ reboot_time: int
78
+ upgrade_time: int
79
+ auto_upgrade: bool
80
+
81
+ extras: Extras = {
82
+ "reboot_time": 5,
83
+ "upgrade_time": upgrade_time,
84
+ "auto_upgrade": False,
85
+ }
75
86
  update_states = [
76
87
  # Unknown 1
77
88
  DownloadState(status=1, download_progress=0, **extras),
@@ -39,3 +39,45 @@ async def test_light_effect(dev: Device, mocker: MockerFixture):
39
39
 
40
40
  with pytest.raises(ValueError):
41
41
  await light_effect.set_effect("foobar")
42
+
43
+
44
+ @light_effect
45
+ @pytest.mark.parametrize("effect_active", [True, False])
46
+ async def test_light_effect_brightness(
47
+ dev: Device, effect_active: bool, mocker: MockerFixture
48
+ ):
49
+ """Test that light module uses light_effect for brightness when active."""
50
+ light_module = dev.modules[Module.Light]
51
+
52
+ light_effect = dev.modules[Module.SmartLightEffect]
53
+ light_effect_set_brightness = mocker.spy(light_effect, "set_brightness")
54
+ mock_light_effect_call = mocker.patch.object(light_effect, "call")
55
+
56
+ brightness = dev.modules[Module.Brightness]
57
+ brightness_set_brightness = mocker.spy(brightness, "set_brightness")
58
+ mock_brightness_call = mocker.patch.object(brightness, "call")
59
+
60
+ mocker.patch.object(
61
+ type(light_effect),
62
+ "is_active",
63
+ new_callable=mocker.PropertyMock,
64
+ return_value=effect_active,
65
+ )
66
+ if effect_active: # Set the rule L1 active for testing
67
+ light_effect.data["current_rule_id"] = "L1"
68
+
69
+ await light_module.set_brightness(10)
70
+
71
+ if effect_active:
72
+ assert light_effect.is_active
73
+ assert light_effect.brightness == dev.brightness
74
+
75
+ light_effect_set_brightness.assert_called_with(10)
76
+ mock_light_effect_call.assert_called_with(
77
+ "edit_dynamic_light_effect_rule", mocker.ANY
78
+ )
79
+ else:
80
+ assert not light_effect.is_active
81
+
82
+ brightness_set_brightness.assert_called_with(10)
83
+ mock_brightness_call.assert_called_with("set_device_info", {"brightness": 10})
@@ -0,0 +1,101 @@
1
+ from __future__ import annotations
2
+
3
+ from itertools import chain
4
+
5
+ import pytest
6
+ from pytest_mock import MockerFixture
7
+
8
+ from kasa import Device, Feature, Module
9
+ from kasa.smart.modules import LightEffect, LightStripEffect
10
+ from kasa.tests.device_fixtures import parametrize
11
+
12
+ light_strip_effect = parametrize(
13
+ "has light strip effect",
14
+ component_filter="light_strip_lighting_effect",
15
+ protocol_filter={"SMART"},
16
+ )
17
+
18
+
19
+ @light_strip_effect
20
+ async def test_light_strip_effect(dev: Device, mocker: MockerFixture):
21
+ """Test light strip effect."""
22
+ light_effect = dev.modules.get(Module.LightEffect)
23
+
24
+ assert isinstance(light_effect, LightStripEffect)
25
+
26
+ brightness = dev.modules[Module.Brightness]
27
+
28
+ feature = dev.features["light_effect"]
29
+ assert feature.type == Feature.Type.Choice
30
+
31
+ call = mocker.spy(light_effect, "call")
32
+
33
+ light = dev.modules[Module.Light]
34
+ light_call = mocker.spy(light, "call")
35
+
36
+ assert feature.choices == light_effect.effect_list
37
+ assert feature.choices
38
+ for effect in chain(reversed(feature.choices), feature.choices):
39
+ await light_effect.set_effect(effect)
40
+
41
+ if effect == LightEffect.LIGHT_EFFECTS_OFF:
42
+ light_call.assert_called()
43
+ continue
44
+
45
+ # Start with the current effect data
46
+ params = light_effect.data["lighting_effect"]
47
+ enable = effect != LightEffect.LIGHT_EFFECTS_OFF
48
+ params["enable"] = enable
49
+ if enable:
50
+ params = light_effect._effect_mapping[effect]
51
+ params["enable"] = enable
52
+ params["brightness"] = brightness.brightness # use the existing brightness
53
+
54
+ call.assert_called_with("set_lighting_effect", params)
55
+
56
+ await dev.update()
57
+ assert light_effect.effect == effect
58
+ assert feature.value == effect
59
+
60
+ with pytest.raises(ValueError):
61
+ await light_effect.set_effect("foobar")
62
+
63
+
64
+ @light_strip_effect
65
+ @pytest.mark.parametrize("effect_active", [True, False])
66
+ async def test_light_effect_brightness(
67
+ dev: Device, effect_active: bool, mocker: MockerFixture
68
+ ):
69
+ """Test that light module uses light_effect for brightness when active."""
70
+ light_module = dev.modules[Module.Light]
71
+
72
+ light_effect = dev.modules[Module.SmartLightEffect]
73
+ light_effect_set_brightness = mocker.spy(light_effect, "set_brightness")
74
+ mock_light_effect_call = mocker.patch.object(light_effect, "call")
75
+
76
+ brightness = dev.modules[Module.Brightness]
77
+ brightness_set_brightness = mocker.spy(brightness, "set_brightness")
78
+ mock_brightness_call = mocker.patch.object(brightness, "call")
79
+
80
+ mocker.patch.object(
81
+ type(light_effect),
82
+ "is_active",
83
+ new_callable=mocker.PropertyMock,
84
+ return_value=effect_active,
85
+ )
86
+
87
+ await light_module.set_brightness(10)
88
+
89
+ if effect_active:
90
+ assert light_effect.is_active
91
+ assert light_effect.brightness == dev.brightness
92
+
93
+ light_effect_set_brightness.assert_called_with(10)
94
+ mock_light_effect_call.assert_called_with(
95
+ "set_lighting_effect", {"brightness": 10, "bAdjusted": True}
96
+ )
97
+ else:
98
+ assert not light_effect.is_active
99
+
100
+ brightness_set_brightness.assert_called_with(10)
101
+ mock_brightness_call.assert_called_with("set_device_info", {"brightness": 10})
@@ -0,0 +1,80 @@
1
+ from pytest_mock import MockerFixture
2
+
3
+ from kasa import Feature, Module
4
+ from kasa.smart import SmartDevice
5
+ from kasa.tests.device_fixtures import get_parent_and_child_modules, parametrize
6
+ from kasa.tests.fixtureinfo import ComponentFilter
7
+
8
+ light_transition_v1 = parametrize(
9
+ "has light transition",
10
+ component_filter=ComponentFilter(
11
+ component_name="on_off_gradually", maximum_version=1
12
+ ),
13
+ protocol_filter={"SMART"},
14
+ )
15
+ light_transition_gt_v1 = parametrize(
16
+ "has light transition",
17
+ component_filter=ComponentFilter(
18
+ component_name="on_off_gradually", minimum_version=2
19
+ ),
20
+ protocol_filter={"SMART"},
21
+ )
22
+
23
+
24
+ @light_transition_v1
25
+ async def test_module_v1(dev: SmartDevice, mocker: MockerFixture):
26
+ """Test light transition module."""
27
+ assert isinstance(dev, SmartDevice)
28
+ light_transition = next(get_parent_and_child_modules(dev, Module.LightTransition))
29
+ assert light_transition
30
+ assert "smooth_transitions" in light_transition._module_features
31
+ assert "smooth_transition_on" not in light_transition._module_features
32
+ assert "smooth_transition_off" not in light_transition._module_features
33
+
34
+ await light_transition.set_enabled(True)
35
+ await dev.update()
36
+ assert light_transition.enabled is True
37
+
38
+ await light_transition.set_enabled(False)
39
+ await dev.update()
40
+ assert light_transition.enabled is False
41
+
42
+
43
+ @light_transition_gt_v1
44
+ async def test_module_gt_v1(dev: SmartDevice, mocker: MockerFixture):
45
+ """Test light transition module."""
46
+ assert isinstance(dev, SmartDevice)
47
+ light_transition = next(get_parent_and_child_modules(dev, Module.LightTransition))
48
+ assert light_transition
49
+ assert "smooth_transitions" not in light_transition._module_features
50
+ assert "smooth_transition_on" in light_transition._module_features
51
+ assert "smooth_transition_off" in light_transition._module_features
52
+
53
+ await light_transition.set_enabled(True)
54
+ await dev.update()
55
+ assert light_transition.enabled is True
56
+
57
+ await light_transition.set_enabled(False)
58
+ await dev.update()
59
+ assert light_transition.enabled is False
60
+
61
+ await light_transition.set_turn_on_transition(5)
62
+ await dev.update()
63
+ assert light_transition.turn_on_transition == 5
64
+ # enabled is true if either on or off is enabled
65
+ assert light_transition.enabled is True
66
+
67
+ await light_transition.set_turn_off_transition(10)
68
+ await dev.update()
69
+ assert light_transition.turn_off_transition == 10
70
+ assert light_transition.enabled is True
71
+
72
+ max_on = light_transition._module_features["smooth_transition_on"].maximum_value
73
+ assert max_on < Feature.DEFAULT_MAX
74
+ max_off = light_transition._module_features["smooth_transition_off"].maximum_value
75
+ assert max_off < Feature.DEFAULT_MAX
76
+
77
+ await light_transition.set_turn_on_transition(0)
78
+ await light_transition.set_turn_off_transition(0)
79
+ await dev.update()
80
+ assert light_transition.enabled is False
@@ -276,6 +276,33 @@ async def test_passthrough_errors(mocker, error_code):
276
276
  await transport.send(json_dumps(request))
277
277
 
278
278
 
279
+ @pytest.mark.parametrize("error_code", [-13333, 13333])
280
+ async def test_unknown_errors(mocker, error_code):
281
+ host = "127.0.0.1"
282
+ mock_aes_device = MockAesDevice(host, 200, error_code, 0)
283
+ mocker.patch.object(aiohttp.ClientSession, "post", side_effect=mock_aes_device.post)
284
+
285
+ config = DeviceConfig(host, credentials=Credentials("foo", "bar"))
286
+ transport = AesTransport(config=config)
287
+ transport._handshake_done = True
288
+ transport._session_expire_at = time.time() + 86400
289
+ transport._encryption_session = mock_aes_device.encryption_session
290
+ transport._token_url = transport._app_url.with_query(
291
+ f"token={mock_aes_device.token}"
292
+ )
293
+
294
+ request = {
295
+ "method": "get_device_info",
296
+ "params": None,
297
+ "request_time_milis": round(time.time() * 1000),
298
+ "requestID": 1,
299
+ "terminal_uuid": "foobar",
300
+ }
301
+ with pytest.raises(KasaException):
302
+ res = await transport.send(json_dumps(request))
303
+ assert res is SmartErrorCode.INTERNAL_UNKNOWN_ERROR
304
+
305
+
279
306
  async def test_port_override():
280
307
  """Test that port override sets the app_url."""
281
308
  host = "127.0.0.1"
@@ -3,12 +3,19 @@ import sys
3
3
 
4
4
  import pytest
5
5
 
6
+ from kasa import Device
6
7
  from kasa.device_type import DeviceType
7
8
  from kasa.smart.smartchilddevice import SmartChildDevice
8
9
  from kasa.smart.smartdevice import NON_HUB_PARENT_ONLY_MODULES
9
10
  from kasa.smartprotocol import _ChildProtocolWrapper
10
11
 
11
- from .conftest import parametrize, parametrize_subtract, strip_smart
12
+ from .conftest import (
13
+ parametrize,
14
+ parametrize_combine,
15
+ parametrize_subtract,
16
+ strip_iot,
17
+ strip_smart,
18
+ )
12
19
 
13
20
  has_children_smart = parametrize(
14
21
  "has children", component_filter="control_child", protocol_filter={"SMART"}
@@ -18,6 +25,8 @@ hub_smart = parametrize(
18
25
  )
19
26
  non_hub_parent_smart = parametrize_subtract(has_children_smart, hub_smart)
20
27
 
28
+ has_children = parametrize_combine([has_children_smart, strip_iot])
29
+
21
30
 
22
31
  @strip_smart
23
32
  def test_childdevice_init(dev, dummy_protocol, mocker):
@@ -100,3 +109,14 @@ async def test_parent_only_modules(dev, dummy_protocol, mocker):
100
109
  for child in dev.children:
101
110
  for module in NON_HUB_PARENT_ONLY_MODULES:
102
111
  assert module not in [type(module) for module in child.modules.values()]
112
+
113
+
114
+ @has_children
115
+ async def test_parent_property(dev: Device):
116
+ """Test a child device exposes it's parent."""
117
+ if not dev.children:
118
+ pytest.skip(f"Device {dev} fixture does not have any children")
119
+
120
+ assert dev.parent is None
121
+ for child in dev.children:
122
+ assert child.parent == dev