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/tests/test_cli.py CHANGED
@@ -57,7 +57,15 @@ def runner():
57
57
  return runner
58
58
 
59
59
 
60
- async def test_update_called_by_cli(dev, mocker, runner):
60
+ @pytest.mark.parametrize(
61
+ ("device_family", "encrypt_type"),
62
+ [
63
+ pytest.param(None, None, id="No connect params"),
64
+ pytest.param("SMART.TAPOPLUG", None, id="Only device_family"),
65
+ pytest.param(None, "KLAP", id="Only encrypt_type"),
66
+ ],
67
+ )
68
+ async def test_update_called_by_cli(dev, mocker, runner, device_family, encrypt_type):
61
69
  """Test that device update is called on main."""
62
70
  update = mocker.patch.object(dev, "update")
63
71
 
@@ -76,6 +84,10 @@ async def test_update_called_by_cli(dev, mocker, runner):
76
84
  "foo",
77
85
  "--password",
78
86
  "bar",
87
+ "--device-family",
88
+ device_family,
89
+ "--encrypt-type",
90
+ encrypt_type,
79
91
  ],
80
92
  catch_exceptions=False,
81
93
  )
@@ -827,7 +839,10 @@ async def test_features_all(discovery_mock, mocker, runner):
827
839
  ["--host", "127.0.0.123", "--debug", "feature"],
828
840
  catch_exceptions=False,
829
841
  )
830
- assert "== Features ==" in res.output
842
+ assert "== Primary features ==" in res.output
843
+ assert "== Information ==" in res.output
844
+ assert "== Configuration ==" in res.output
845
+ assert "== Debug ==" in res.output
831
846
  assert res.exit_code == 0
832
847
 
833
848
 
@@ -878,7 +893,7 @@ async def test_feature_set(mocker, runner):
878
893
  )
879
894
 
880
895
  led_setter.assert_called_with(True)
881
- assert "Changing led from False to True" in res.output
896
+ assert "Changing led from True to True" in res.output
882
897
  assert res.exit_code == 0
883
898
 
884
899
 
@@ -89,35 +89,39 @@ async def test_light_effect_module(dev: Device, mocker: MockerFixture):
89
89
  assert light_effect_module.has_custom_effects is not None
90
90
 
91
91
  await light_effect_module.set_effect("Off")
92
- assert call.call_count == 1
92
+ call.assert_called()
93
93
  await dev.update()
94
94
  assert light_effect_module.effect == "Off"
95
95
  assert feat.value == "Off"
96
+ call.reset_mock()
96
97
 
97
98
  second_effect = effect_list[1]
98
99
  await light_effect_module.set_effect(second_effect)
99
- assert call.call_count == 2
100
+ call.assert_called()
100
101
  await dev.update()
101
102
  assert light_effect_module.effect == second_effect
102
103
  assert feat.value == second_effect
104
+ call.reset_mock()
103
105
 
104
106
  last_effect = effect_list[len(effect_list) - 1]
105
107
  await light_effect_module.set_effect(last_effect)
106
- assert call.call_count == 3
108
+ call.assert_called()
107
109
  await dev.update()
108
110
  assert light_effect_module.effect == last_effect
109
111
  assert feat.value == last_effect
112
+ call.reset_mock()
110
113
 
111
114
  # Test feature set
112
115
  await feat.set_value(second_effect)
113
- assert call.call_count == 4
116
+ call.assert_called()
114
117
  await dev.update()
115
118
  assert light_effect_module.effect == second_effect
116
119
  assert feat.value == second_effect
120
+ call.reset_mock()
117
121
 
118
122
  with pytest.raises(ValueError):
119
123
  await light_effect_module.set_effect("foobar")
120
- assert call.call_count == 4
124
+ call.assert_not_called()
121
125
 
122
126
 
123
127
  @dimmable
kasa/tests/test_device.py CHANGED
@@ -6,6 +6,7 @@ import importlib
6
6
  import inspect
7
7
  import pkgutil
8
8
  import sys
9
+ from contextlib import AbstractContextManager
9
10
  from unittest.mock import Mock, patch
10
11
 
11
12
  import pytest
@@ -161,7 +162,7 @@ async def _test_attribute(
161
162
  dev: Device, attribute_name, is_expected, module_name, *args, will_raise=False
162
163
  ):
163
164
  if is_expected and will_raise:
164
- ctx = pytest.raises(will_raise)
165
+ ctx: AbstractContextManager = pytest.raises(will_raise)
165
166
  elif is_expected:
166
167
  ctx = pytest.deprecated_call(match=(f"{attribute_name} is deprecated, use:"))
167
168
  else:
@@ -1,16 +1,25 @@
1
- # type: ignore
1
+ """Module for testing device factory.
2
+
3
+ As this module tests the factory with discovery data and expects update to be
4
+ called on devices it uses the discovery_mock handles all the patching of the
5
+ query methods without actually replacing the device protocol class with one of
6
+ the testing fake protocols.
7
+ """
8
+
2
9
  import logging
10
+ from typing import cast
3
11
 
4
12
  import aiohttp
5
13
  import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342
6
14
 
7
15
  from kasa import (
8
16
  Credentials,
9
- Device,
10
17
  Discover,
11
18
  KasaException,
12
19
  )
13
20
  from kasa.device_factory import (
21
+ Device,
22
+ SmartDevice,
14
23
  _get_device_type_from_sys_info,
15
24
  connect,
16
25
  get_device_class_from_family,
@@ -23,7 +32,8 @@ from kasa.deviceconfig import (
23
32
  DeviceFamily,
24
33
  )
25
34
  from kasa.discover import DiscoveryResult
26
- from kasa.smart.smartdevice import SmartDevice
35
+
36
+ from .conftest import DISCOVERY_MOCK_IP
27
37
 
28
38
 
29
39
  def _get_connection_type_device_class(discovery_info):
@@ -44,18 +54,22 @@ def _get_connection_type_device_class(discovery_info):
44
54
 
45
55
 
46
56
  async def test_connect(
47
- discovery_data,
57
+ discovery_mock,
48
58
  mocker,
49
59
  ):
50
60
  """Test that if the protocol is passed in it gets set correctly."""
51
- host = "127.0.0.1"
52
- ctype, device_class = _get_connection_type_device_class(discovery_data)
61
+ host = DISCOVERY_MOCK_IP
62
+ ctype, device_class = _get_connection_type_device_class(
63
+ discovery_mock.discovery_data
64
+ )
53
65
 
54
66
  config = DeviceConfig(
55
67
  host=host, credentials=Credentials("foor", "bar"), connection_type=ctype
56
68
  )
57
69
  protocol_class = get_protocol(config).__class__
58
70
  close_mock = mocker.patch.object(protocol_class, "close")
71
+ # mocker.patch.object(SmartDevice, "update")
72
+ # mocker.patch.object(Device, "update")
59
73
  dev = await connect(
60
74
  config=config,
61
75
  )
@@ -69,10 +83,11 @@ async def test_connect(
69
83
 
70
84
 
71
85
  @pytest.mark.parametrize("custom_port", [123, None])
72
- async def test_connect_custom_port(discovery_data: dict, mocker, custom_port):
86
+ async def test_connect_custom_port(discovery_mock, mocker, custom_port):
73
87
  """Make sure that connect returns an initialized SmartDevice instance."""
74
- host = "127.0.0.1"
88
+ host = DISCOVERY_MOCK_IP
75
89
 
90
+ discovery_data = discovery_mock.discovery_data
76
91
  ctype, _ = _get_connection_type_device_class(discovery_data)
77
92
  config = DeviceConfig(
78
93
  host=host,
@@ -90,13 +105,14 @@ async def test_connect_custom_port(discovery_data: dict, mocker, custom_port):
90
105
 
91
106
 
92
107
  async def test_connect_logs_connect_time(
93
- discovery_data: dict,
108
+ discovery_mock,
94
109
  caplog: pytest.LogCaptureFixture,
95
110
  ):
96
111
  """Test that the connect time is logged when debug logging is enabled."""
112
+ discovery_data = discovery_mock.discovery_data
97
113
  ctype, _ = _get_connection_type_device_class(discovery_data)
98
114
 
99
- host = "127.0.0.1"
115
+ host = DISCOVERY_MOCK_IP
100
116
  config = DeviceConfig(
101
117
  host=host, credentials=Credentials("foor", "bar"), connection_type=ctype
102
118
  )
@@ -107,9 +123,10 @@ async def test_connect_logs_connect_time(
107
123
  assert "seconds to update" in caplog.text
108
124
 
109
125
 
110
- async def test_connect_query_fails(discovery_data, mocker):
126
+ async def test_connect_query_fails(discovery_mock, mocker):
111
127
  """Make sure that connect fails when query fails."""
112
- host = "127.0.0.1"
128
+ host = DISCOVERY_MOCK_IP
129
+ discovery_data = discovery_mock.discovery_data
113
130
  mocker.patch("kasa.IotProtocol.query", side_effect=KasaException)
114
131
  mocker.patch("kasa.SmartProtocol.query", side_effect=KasaException)
115
132
 
@@ -125,10 +142,10 @@ async def test_connect_query_fails(discovery_data, mocker):
125
142
  assert close_mock.call_count == 1
126
143
 
127
144
 
128
- async def test_connect_http_client(discovery_data, mocker):
145
+ async def test_connect_http_client(discovery_mock, mocker):
129
146
  """Make sure that discover_single returns an initialized SmartDevice instance."""
130
- host = "127.0.0.1"
131
-
147
+ host = DISCOVERY_MOCK_IP
148
+ discovery_data = discovery_mock.discovery_data
132
149
  ctype, _ = _get_connection_type_device_class(discovery_data)
133
150
 
134
151
  http_client = aiohttp.ClientSession()
@@ -157,9 +174,10 @@ async def test_connect_http_client(discovery_data, mocker):
157
174
  async def test_device_types(dev: Device):
158
175
  await dev.update()
159
176
  if isinstance(dev, SmartDevice):
160
- device_type = dev._discovery_info["result"]["device_type"]
177
+ assert dev._discovery_info
178
+ device_type = cast(str, dev._discovery_info["result"]["device_type"])
161
179
  res = SmartDevice._get_device_type_from_components(
162
- dev._components.keys(), device_type
180
+ list(dev._components.keys()), device_type
163
181
  )
164
182
  else:
165
183
  res = _get_device_type_from_sys_info(dev._last_update)
kasa/tests/test_emeter.py CHANGED
@@ -5,7 +5,7 @@ import pytest
5
5
  from voluptuous import (
6
6
  All,
7
7
  Any,
8
- Coerce, # type: ignore
8
+ Coerce,
9
9
  Range,
10
10
  Schema,
11
11
  )
@@ -21,14 +21,14 @@ CURRENT_CONSUMPTION_SCHEMA = Schema(
21
21
  Any(
22
22
  {
23
23
  "voltage": Any(All(float, Range(min=0, max=300)), None),
24
- "power": Any(Coerce(float, Range(min=0)), None),
25
- "total": Any(Coerce(float, Range(min=0)), None),
26
- "current": Any(All(float, Range(min=0)), None),
24
+ "power": Any(Coerce(float), None),
25
+ "total": Any(Coerce(float), None),
26
+ "current": Any(All(float), None),
27
27
  "voltage_mv": Any(All(float, Range(min=0, max=300000)), int, None),
28
- "power_mw": Any(Coerce(float, Range(min=0)), None),
29
- "total_wh": Any(Coerce(float, Range(min=0)), None),
30
- "current_ma": Any(All(float, Range(min=0)), int, None),
31
- "slot_id": Any(Coerce(int, Range(min=0)), None),
28
+ "power_mw": Any(Coerce(float), None),
29
+ "total_wh": Any(Coerce(float), None),
30
+ "current_ma": Any(All(float), int, None),
31
+ "slot_id": Any(Coerce(int), None),
32
32
  },
33
33
  None,
34
34
  )
@@ -44,8 +44,11 @@ def test_feature_api(dummy_feature: Feature):
44
44
  assert dummy_feature.unit == "dummyunit"
45
45
 
46
46
 
47
- def test_feature_missing_type():
48
- """Test that creating a feature with a setter but without type causes an error."""
47
+ @pytest.mark.parametrize(
48
+ "read_only_type", [Feature.Type.Sensor, Feature.Type.BinarySensor]
49
+ )
50
+ def test_feature_setter_on_sensor(read_only_type):
51
+ """Test that creating a sensor feature with a setter causes an error."""
49
52
  with pytest.raises(ValueError):
50
53
  Feature(
51
54
  device=DummyDevice(), # type: ignore[arg-type]
@@ -53,6 +56,7 @@ def test_feature_missing_type():
53
56
  name="dummy error",
54
57
  attribute_getter="dummygetter",
55
58
  attribute_setter="dummysetter",
59
+ type=read_only_type,
56
60
  )
57
61
 
58
62
 
@@ -38,7 +38,7 @@ from ..httpclient import HttpClient
38
38
  ),
39
39
  (Exception(), KasaException, "Unable to query the device: "),
40
40
  (
41
- aiohttp.ServerFingerprintMismatch("exp", "got", "host", 1),
41
+ aiohttp.ServerFingerprintMismatch(b"exp", b"got", "host", 1),
42
42
  KasaException,
43
43
  "Unable to query the device: ",
44
44
  ),
@@ -84,7 +84,7 @@ async def test_httpclient_errors(mocker, error, error_raises, error_message, moc
84
84
  client = HttpClient(DeviceConfig(host))
85
85
  # Exceptions with parameters print with double quotes, without use single quotes
86
86
  full_msg = (
87
- "\(" # type: ignore
87
+ re.escape("(")
88
88
  + "['\"]"
89
89
  + re.escape(f"{error_message}{host}: {error}")
90
90
  + "['\"]"
@@ -91,9 +91,10 @@ async def test_state_info(dev):
91
91
  @pytest.mark.requires_dummy
92
92
  @device_iot
93
93
  async def test_invalid_connection(mocker, dev):
94
- with mocker.patch.object(
95
- FakeIotProtocol, "query", side_effect=KasaException
96
- ), pytest.raises(KasaException):
94
+ with (
95
+ mocker.patch.object(FakeIotProtocol, "query", side_effect=KasaException),
96
+ pytest.raises(KasaException),
97
+ ):
97
98
  await dev.update()
98
99
 
99
100
 
@@ -207,7 +208,7 @@ async def test_mac(dev):
207
208
 
208
209
  @device_iot
209
210
  async def test_representation(dev):
210
- pattern = re.compile("<DeviceType\..+ at .+? - .*? \(.+?\)>")
211
+ pattern = re.compile(r"<DeviceType\..+ at .+? - .*? \(.+?\)>")
211
212
  assert pattern.match(str(dev))
212
213
 
213
214
 
@@ -69,6 +69,7 @@ def test_discovery_examples(readmes_mock):
69
69
  """Test discovery examples."""
70
70
  res = xdoctest.doctest_module("kasa.discover", "all")
71
71
  assert res["n_passed"] > 0
72
+ assert res["n_warned"] == 0
72
73
  assert not res["failed"]
73
74
 
74
75
 
@@ -76,6 +77,63 @@ def test_deviceconfig_examples(readmes_mock):
76
77
  """Test discovery examples."""
77
78
  res = xdoctest.doctest_module("kasa.deviceconfig", "all")
78
79
  assert res["n_passed"] > 0
80
+ assert res["n_warned"] == 0
81
+ assert not res["failed"]
82
+
83
+
84
+ def test_device_examples(readmes_mock):
85
+ """Test device examples."""
86
+ res = xdoctest.doctest_module("kasa.device", "all")
87
+ assert res["n_passed"] > 0
88
+ assert res["n_warned"] == 0
89
+ assert not res["failed"]
90
+
91
+
92
+ def test_light_examples(readmes_mock):
93
+ """Test device examples."""
94
+ res = xdoctest.doctest_module("kasa.interfaces.light", "all")
95
+ assert res["n_passed"] > 0
96
+ assert res["n_warned"] == 0
97
+ assert not res["failed"]
98
+
99
+
100
+ def test_light_preset_examples(readmes_mock):
101
+ """Test device examples."""
102
+ res = xdoctest.doctest_module("kasa.interfaces.lightpreset", "all")
103
+ assert res["n_passed"] > 0
104
+ assert res["n_warned"] == 0
105
+ assert not res["failed"]
106
+
107
+
108
+ def test_light_effect_examples(readmes_mock):
109
+ """Test device examples."""
110
+ res = xdoctest.doctest_module("kasa.interfaces.lighteffect", "all")
111
+ assert res["n_passed"] > 0
112
+ assert res["n_warned"] == 0
113
+ assert not res["failed"]
114
+
115
+
116
+ def test_child_examples(readmes_mock):
117
+ """Test device examples."""
118
+ res = xdoctest.doctest_module("kasa.smart.modules.childdevice", "all")
119
+ assert res["n_passed"] > 0
120
+ assert res["n_warned"] == 0
121
+ assert not res["failed"]
122
+
123
+
124
+ def test_module_examples(readmes_mock):
125
+ """Test device examples."""
126
+ res = xdoctest.doctest_module("kasa.module", "all")
127
+ assert res["n_passed"] > 0
128
+ assert res["n_warned"] == 0
129
+ assert not res["failed"]
130
+
131
+
132
+ def test_feature_examples(readmes_mock):
133
+ """Test device examples."""
134
+ res = xdoctest.doctest_module("kasa.feature", "all")
135
+ assert res["n_passed"] > 0
136
+ assert res["n_warned"] == 0
79
137
  assert not res["failed"]
80
138
 
81
139
 
@@ -83,6 +141,7 @@ def test_tutorial_examples(readmes_mock):
83
141
  """Test discovery examples."""
84
142
  res = xdoctest.doctest_module("docs/tutorial.py", "all")
85
143
  assert res["n_passed"] > 0
144
+ assert res["n_warned"] == 0
86
145
  assert not res["failed"]
87
146
 
88
147
 
@@ -38,9 +38,10 @@ async def test_update_no_device_info(dev: SmartDevice, mocker: MockerFixture):
38
38
  "get_device_time": {},
39
39
  }
40
40
  msg = f"get_device_info not found in {mock_response} for device 127.0.0.123"
41
- with mocker.patch.object(
42
- dev.protocol, "query", return_value=mock_response
43
- ), pytest.raises(KasaException, match=msg):
41
+ with (
42
+ mocker.patch.object(dev.protocol, "query", return_value=mock_response),
43
+ pytest.raises(KasaException, match=msg),
44
+ ):
44
45
  await dev.update()
45
46
 
46
47
 
@@ -2,10 +2,9 @@ import logging
2
2
 
3
3
  import pytest
4
4
 
5
- from ..credentials import Credentials
6
- from ..deviceconfig import DeviceConfig
7
5
  from ..exceptions import (
8
6
  SMART_RETRYABLE_ERRORS,
7
+ DeviceError,
9
8
  KasaException,
10
9
  SmartErrorCode,
11
10
  )
@@ -35,6 +34,25 @@ async def test_smart_device_errors(dummy_protocol, mocker, error_code):
35
34
  assert send_mock.call_count == expected_calls
36
35
 
37
36
 
37
+ @pytest.mark.parametrize("error_code", [-13333, 13333])
38
+ async def test_smart_device_unknown_errors(
39
+ dummy_protocol, mocker, error_code, caplog: pytest.LogCaptureFixture
40
+ ):
41
+ """Test handling of unknown error codes."""
42
+ mock_response = {"result": {"great": "success"}, "error_code": error_code}
43
+
44
+ send_mock = mocker.patch.object(
45
+ dummy_protocol._transport, "send", return_value=mock_response
46
+ )
47
+
48
+ with pytest.raises(KasaException):
49
+ res = await dummy_protocol.query(DUMMY_QUERY)
50
+ assert res is SmartErrorCode.INTERNAL_UNKNOWN_ERROR
51
+
52
+ send_mock.assert_called_once()
53
+ assert f"Received unknown error code: {error_code}" in caplog.text
54
+
55
+
38
56
  @pytest.mark.parametrize("error_code", ERRORS, ids=lambda e: e.name)
39
57
  async def test_smart_device_errors_in_multiple_request(
40
58
  dummy_protocol, mocker, error_code
@@ -74,7 +92,6 @@ async def test_smart_device_errors_in_multiple_request(
74
92
  async def test_smart_device_multiple_request(
75
93
  dummy_protocol, mocker, request_size, batch_size
76
94
  ):
77
- host = "127.0.0.1"
78
95
  requests = {}
79
96
  mock_response = {
80
97
  "result": {"responses": []},
@@ -90,16 +107,101 @@ async def test_smart_device_multiple_request(
90
107
  send_mock = mocker.patch.object(
91
108
  dummy_protocol._transport, "send", return_value=mock_response
92
109
  )
93
- config = DeviceConfig(
94
- host, credentials=Credentials("foo", "bar"), batch_size=batch_size
95
- )
96
- dummy_protocol._transport._config = config
110
+ dummy_protocol._multi_request_batch_size = batch_size
97
111
 
98
112
  await dummy_protocol.query(requests, retry_count=0)
99
113
  expected_count = int(request_size / batch_size) + (request_size % batch_size > 0)
100
114
  assert send_mock.call_count == expected_count
101
115
 
102
116
 
117
+ async def test_smart_device_multiple_request_json_decode_failure(
118
+ dummy_protocol, mocker
119
+ ):
120
+ """Test the logic to disable multiple requests on JSON_DECODE_FAIL_ERROR."""
121
+ requests = {}
122
+ mock_responses = []
123
+
124
+ mock_json_error = {
125
+ "result": {"responses": []},
126
+ "error_code": SmartErrorCode.JSON_DECODE_FAIL_ERROR.value,
127
+ }
128
+ for i in range(10):
129
+ method = f"get_method_{i}"
130
+ requests[method] = {"foo": "bar", "bar": "foo"}
131
+ mock_responses.append(
132
+ {"method": method, "result": {"great": "success"}, "error_code": 0}
133
+ )
134
+
135
+ send_mock = mocker.patch.object(
136
+ dummy_protocol._transport,
137
+ "send",
138
+ side_effect=[mock_json_error, *mock_responses],
139
+ )
140
+ dummy_protocol._multi_request_batch_size = 5
141
+ assert dummy_protocol._multi_request_batch_size == 5
142
+ await dummy_protocol.query(requests, retry_count=1)
143
+ assert dummy_protocol._multi_request_batch_size == 1
144
+ # Call count should be the first error + number of requests
145
+ assert send_mock.call_count == len(requests) + 1
146
+
147
+
148
+ async def test_smart_device_multiple_request_json_decode_failure_twice(
149
+ dummy_protocol, mocker
150
+ ):
151
+ """Test the logic to disable multiple requests on JSON_DECODE_FAIL_ERROR."""
152
+ requests = {}
153
+
154
+ mock_json_error = {
155
+ "result": {"responses": []},
156
+ "error_code": SmartErrorCode.JSON_DECODE_FAIL_ERROR.value,
157
+ }
158
+ for i in range(10):
159
+ method = f"get_method_{i}"
160
+ requests[method] = {"foo": "bar", "bar": "foo"}
161
+
162
+ send_mock = mocker.patch.object(
163
+ dummy_protocol._transport,
164
+ "send",
165
+ side_effect=[mock_json_error, KasaException],
166
+ )
167
+ dummy_protocol._multi_request_batch_size = 5
168
+ with pytest.raises(KasaException):
169
+ await dummy_protocol.query(requests, retry_count=1)
170
+ assert dummy_protocol._multi_request_batch_size == 1
171
+
172
+ assert send_mock.call_count == 2
173
+
174
+
175
+ async def test_smart_device_multiple_request_non_json_decode_failure(
176
+ dummy_protocol, mocker
177
+ ):
178
+ """Test the logic to disable multiple requests on JSON_DECODE_FAIL_ERROR.
179
+
180
+ Ensure other exception types behave as expected.
181
+ """
182
+ requests = {}
183
+
184
+ mock_json_error = {
185
+ "result": {"responses": []},
186
+ "error_code": SmartErrorCode.UNKNOWN_METHOD_ERROR.value,
187
+ }
188
+ for i in range(10):
189
+ method = f"get_method_{i}"
190
+ requests[method] = {"foo": "bar", "bar": "foo"}
191
+
192
+ send_mock = mocker.patch.object(
193
+ dummy_protocol._transport,
194
+ "send",
195
+ side_effect=[mock_json_error, KasaException],
196
+ )
197
+ dummy_protocol._multi_request_batch_size = 5
198
+ with pytest.raises(DeviceError):
199
+ await dummy_protocol.query(requests, retry_count=1)
200
+ assert dummy_protocol._multi_request_batch_size == 5
201
+
202
+ assert send_mock.call_count == 1
203
+
204
+
103
205
  async def test_childdevicewrapper_unwrapping(dummy_protocol, mocker):
104
206
  """Test that responseData gets unwrapped correctly."""
105
207
  wrapped_protocol = _ChildProtocolWrapper("dummyid", dummy_protocol)
kasa/tests/test_strip.py CHANGED
@@ -2,10 +2,10 @@ from datetime import datetime
2
2
 
3
3
  import pytest
4
4
 
5
- from kasa import KasaException
5
+ from kasa import Device, KasaException, Module
6
6
  from kasa.iot import IotStrip
7
7
 
8
- from .conftest import handle_turn_on, strip, turn_on
8
+ from .conftest import handle_turn_on, strip, strip_iot, turn_on
9
9
 
10
10
 
11
11
  @strip
@@ -147,3 +147,16 @@ def test_children_api(dev):
147
147
  first = dev.children[0]
148
148
  first_by_get_child_device = dev.get_child_device(first.device_id)
149
149
  assert first == first_by_get_child_device
150
+
151
+
152
+ @strip_iot
153
+ async def test_children_energy(dev: Device):
154
+ if Module.Energy not in dev.modules:
155
+ pytest.skip(f"skipping device {dev.model} does not support energy")
156
+
157
+ for plug in dev.children:
158
+ # For now all known strips with energy support these
159
+ energy = plug.modules[Module.Energy]
160
+ assert "voltage" in energy._module_features
161
+ assert "current" in energy._module_features
162
+ assert "current_consumption" in energy._module_features
kasa/xortransport.py CHANGED
@@ -18,8 +18,8 @@ import errno
18
18
  import logging
19
19
  import socket
20
20
  import struct
21
+ from collections.abc import Generator
21
22
  from pprint import pformat as pf
22
- from typing import Generator
23
23
 
24
24
  # When support for cpython older than 3.11 is dropped
25
25
  # async_timeout can be replaced with asyncio.timeout
@@ -229,7 +229,7 @@ class XorEncryption:
229
229
  try:
230
230
  from kasa_crypt import decrypt, encrypt
231
231
 
232
- XorEncryption.decrypt = decrypt # type: ignore[method-assign]
233
- XorEncryption.encrypt = encrypt # type: ignore[method-assign]
232
+ XorEncryption.decrypt = decrypt # type: ignore[assignment]
233
+ XorEncryption.encrypt = encrypt # type: ignore[assignment]
234
234
  except ImportError:
235
235
  pass