python-kasa 0.6.2__py3-none-any.whl → 0.7.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. kasa/__init__.py +88 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +406 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +16 -9
  8. kasa/discover.py +100 -81
  9. kasa/emeterstatus.py +12 -7
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +201 -0
  12. kasa/httpclient.py +21 -14
  13. kasa/interfaces/__init__.py +16 -0
  14. kasa/interfaces/fan.py +20 -0
  15. kasa/interfaces/led.py +38 -0
  16. kasa/interfaces/light.py +133 -0
  17. kasa/interfaces/lighteffect.py +80 -0
  18. kasa/interfaces/lightpreset.py +76 -0
  19. kasa/iot/__init__.py +18 -0
  20. kasa/{effects.py → iot/effects.py} +4 -2
  21. kasa/{smartbulb.py → iot/iotbulb.py} +100 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -33
  24. kasa/iot/iotlightstrip.py +71 -0
  25. kasa/{modules/module.py → iot/iotmodule.py} +22 -42
  26. kasa/iot/iotplug.py +94 -0
  27. kasa/{smartstrip.py → iot/iotstrip.py} +57 -75
  28. kasa/{modules → iot/modules}/__init__.py +10 -2
  29. kasa/{modules → iot/modules}/ambientlight.py +31 -3
  30. kasa/{modules → iot/modules}/antitheft.py +1 -0
  31. kasa/{modules → iot/modules}/cloud.py +25 -6
  32. kasa/{modules → iot/modules}/countdown.py +1 -0
  33. kasa/iot/modules/emeter.py +210 -0
  34. kasa/iot/modules/led.py +32 -0
  35. kasa/iot/modules/light.py +221 -0
  36. kasa/iot/modules/lighteffect.py +122 -0
  37. kasa/iot/modules/lightpreset.py +151 -0
  38. kasa/{modules → iot/modules}/motion.py +8 -8
  39. kasa/{modules → iot/modules}/rulemodule.py +11 -12
  40. kasa/{modules → iot/modules}/schedule.py +1 -0
  41. kasa/{modules → iot/modules}/time.py +5 -4
  42. kasa/{modules → iot/modules}/usage.py +10 -8
  43. kasa/iotprotocol.py +22 -20
  44. kasa/klaptransport.py +25 -15
  45. kasa/module.py +136 -0
  46. kasa/modulemapping.py +25 -0
  47. kasa/modulemapping.pyi +96 -0
  48. kasa/protocol.py +6 -4
  49. kasa/smart/__init__.py +6 -0
  50. kasa/smart/effects.py +429 -0
  51. kasa/smart/modules/__init__.py +57 -0
  52. kasa/smart/modules/alarm.py +142 -0
  53. kasa/smart/modules/autooff.py +96 -0
  54. kasa/smart/modules/batterysensor.py +54 -0
  55. kasa/smart/modules/brightness.py +66 -0
  56. kasa/smart/modules/childdevice.py +10 -0
  57. kasa/smart/modules/cloud.py +42 -0
  58. kasa/smart/modules/color.py +96 -0
  59. kasa/smart/modules/colortemperature.py +78 -0
  60. kasa/smart/modules/contactsensor.py +42 -0
  61. kasa/smart/modules/devicemodule.py +22 -0
  62. kasa/smart/modules/energy.py +101 -0
  63. kasa/smart/modules/fan.py +80 -0
  64. kasa/smart/modules/firmware.py +216 -0
  65. kasa/smart/modules/frostprotection.py +59 -0
  66. kasa/smart/modules/humiditysensor.py +55 -0
  67. kasa/smart/modules/led.py +49 -0
  68. kasa/smart/modules/light.py +139 -0
  69. kasa/smart/modules/lighteffect.py +115 -0
  70. kasa/smart/modules/lightpreset.py +142 -0
  71. kasa/smart/modules/lightstripeffect.py +135 -0
  72. kasa/smart/modules/lighttransition.py +183 -0
  73. kasa/smart/modules/reportmode.py +36 -0
  74. kasa/smart/modules/temperaturecontrol.py +177 -0
  75. kasa/smart/modules/temperaturesensor.py +77 -0
  76. kasa/smart/modules/time.py +57 -0
  77. kasa/smart/modules/waterleaksensor.py +66 -0
  78. kasa/smart/smartchilddevice.py +65 -0
  79. kasa/smart/smartdevice.py +653 -0
  80. kasa/smart/smartmodule.py +112 -0
  81. kasa/smartprotocol.py +107 -41
  82. kasa/tests/conftest.py +27 -551
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
  86. kasa/tests/fakeprotocol_smart.py +318 -0
  87. kasa/tests/fixtureinfo.py +154 -0
  88. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  89. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  90. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  91. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  92. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  93. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  94. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  95. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  96. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  97. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  98. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.13.json +13 -23
  99. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  100. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  101. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  102. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  103. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  104. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  105. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  106. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  107. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  108. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  109. kasa/tests/smart/__init__.py +0 -0
  110. kasa/tests/smart/features/__init__.py +0 -0
  111. kasa/tests/smart/features/test_brightness.py +55 -0
  112. kasa/tests/smart/features/test_colortemp.py +30 -0
  113. kasa/tests/smart/modules/__init__.py +0 -0
  114. kasa/tests/smart/modules/test_contact.py +28 -0
  115. kasa/tests/smart/modules/test_fan.py +79 -0
  116. kasa/tests/smart/modules/test_firmware.py +108 -0
  117. kasa/tests/smart/modules/test_humidity.py +28 -0
  118. kasa/tests/smart/modules/test_light_effect.py +41 -0
  119. kasa/tests/smart/modules/test_temperature.py +47 -0
  120. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  121. kasa/tests/smart/modules/test_waterleak.py +42 -0
  122. kasa/tests/test_aestransport.py +115 -25
  123. kasa/tests/test_bulb.py +169 -86
  124. kasa/tests/test_childdevice.py +84 -0
  125. kasa/tests/test_cli.py +452 -100
  126. kasa/tests/test_common_modules.py +216 -0
  127. kasa/tests/test_device.py +268 -0
  128. kasa/tests/test_device_factory.py +61 -41
  129. kasa/tests/test_device_type.py +1 -1
  130. kasa/tests/test_deviceconfig.py +2 -5
  131. kasa/tests/test_dimmer.py +33 -24
  132. kasa/tests/test_discovery.py +112 -69
  133. kasa/tests/test_emeter.py +39 -12
  134. kasa/tests/test_feature.py +205 -0
  135. kasa/tests/test_httpclient.py +9 -9
  136. kasa/tests/test_iotdevice.py +286 -0
  137. kasa/tests/test_klapprotocol.py +94 -41
  138. kasa/tests/test_lightstrip.py +24 -19
  139. kasa/tests/test_plug.py +51 -9
  140. kasa/tests/test_protocol.py +8 -12
  141. kasa/tests/test_readme_examples.py +86 -27
  142. kasa/tests/test_smartdevice.py +211 -247
  143. kasa/tests/test_smartprotocol.py +129 -26
  144. kasa/tests/test_strip.py +15 -6
  145. kasa/tests/test_usage.py +1 -3
  146. kasa/xortransport.py +15 -12
  147. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
  148. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  149. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
  150. kasa/modules/emeter.py +0 -111
  151. kasa/smartlightstrip.py +0 -143
  152. kasa/smartplug.py +0 -91
  153. kasa/tapo/__init__.py +0 -7
  154. kasa/tapo/childdevice.py +0 -44
  155. kasa/tapo/tapobulb.py +0 -262
  156. kasa/tapo/tapodevice.py +0 -383
  157. kasa/tapo/tapoplug.py +0 -45
  158. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  159. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  160. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  161. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  162. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  163. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  164. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  165. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  166. python_kasa-0.6.2.dist-info/RECORD +0 -163
  167. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  168. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,216 @@
1
+ import pytest
2
+ from pytest_mock import MockerFixture
3
+
4
+ from kasa import Device, LightState, Module
5
+ from kasa.tests.device_fixtures import (
6
+ bulb_iot,
7
+ dimmable_iot,
8
+ dimmer_iot,
9
+ lightstrip_iot,
10
+ parametrize,
11
+ parametrize_combine,
12
+ plug_iot,
13
+ )
14
+
15
+ led_smart = parametrize(
16
+ "has led smart", component_filter="led", protocol_filter={"SMART"}
17
+ )
18
+ led = parametrize_combine([led_smart, plug_iot])
19
+
20
+ light_effect_smart = parametrize(
21
+ "has light effect smart", component_filter="light_effect", protocol_filter={"SMART"}
22
+ )
23
+ light_strip_effect_smart = parametrize(
24
+ "has light strip effect smart",
25
+ component_filter="light_strip_lighting_effect",
26
+ protocol_filter={"SMART"},
27
+ )
28
+ light_effect = parametrize_combine(
29
+ [light_effect_smart, light_strip_effect_smart, lightstrip_iot]
30
+ )
31
+
32
+ dimmable_smart = parametrize(
33
+ "dimmable smart", component_filter="brightness", protocol_filter={"SMART"}
34
+ )
35
+ dimmable = parametrize_combine([dimmable_smart, dimmer_iot, dimmable_iot])
36
+
37
+ light_preset_smart = parametrize(
38
+ "has light preset smart", component_filter="preset", protocol_filter={"SMART"}
39
+ )
40
+
41
+ light_preset = parametrize_combine([light_preset_smart, bulb_iot])
42
+
43
+
44
+ @led
45
+ async def test_led_module(dev: Device, mocker: MockerFixture):
46
+ """Test fan speed feature."""
47
+ led_module = dev.modules.get(Module.Led)
48
+ assert led_module
49
+ feat = dev.features["led"]
50
+
51
+ call = mocker.spy(led_module, "call")
52
+ await led_module.set_led(True)
53
+ assert call.call_count == 1
54
+ await dev.update()
55
+ assert led_module.led is True
56
+ assert feat.value is True
57
+
58
+ await led_module.set_led(False)
59
+ assert call.call_count == 2
60
+ await dev.update()
61
+ assert led_module.led is False
62
+ assert feat.value is False
63
+
64
+ await feat.set_value(True)
65
+ assert call.call_count == 3
66
+ await dev.update()
67
+ assert feat.value is True
68
+ assert led_module.led is True
69
+
70
+
71
+ @light_effect
72
+ async def test_light_effect_module(dev: Device, mocker: MockerFixture):
73
+ """Test fan speed feature."""
74
+ light_effect_module = dev.modules[Module.LightEffect]
75
+ assert light_effect_module
76
+ feat = dev.features["light_effect"]
77
+
78
+ call = mocker.spy(light_effect_module, "call")
79
+ effect_list = light_effect_module.effect_list
80
+ assert "Off" in effect_list
81
+ assert effect_list.index("Off") == 0
82
+ assert len(effect_list) > 1
83
+ assert effect_list == feat.choices
84
+
85
+ assert light_effect_module.has_custom_effects is not None
86
+
87
+ await light_effect_module.set_effect("Off")
88
+ assert call.call_count == 1
89
+ await dev.update()
90
+ assert light_effect_module.effect == "Off"
91
+ assert feat.value == "Off"
92
+
93
+ second_effect = effect_list[1]
94
+ await light_effect_module.set_effect(second_effect)
95
+ assert call.call_count == 2
96
+ await dev.update()
97
+ assert light_effect_module.effect == second_effect
98
+ assert feat.value == second_effect
99
+
100
+ last_effect = effect_list[len(effect_list) - 1]
101
+ await light_effect_module.set_effect(last_effect)
102
+ assert call.call_count == 3
103
+ await dev.update()
104
+ assert light_effect_module.effect == last_effect
105
+ assert feat.value == last_effect
106
+
107
+ # Test feature set
108
+ await feat.set_value(second_effect)
109
+ assert call.call_count == 4
110
+ await dev.update()
111
+ assert light_effect_module.effect == second_effect
112
+ assert feat.value == second_effect
113
+
114
+ with pytest.raises(ValueError):
115
+ await light_effect_module.set_effect("foobar")
116
+ assert call.call_count == 4
117
+
118
+
119
+ @dimmable
120
+ async def test_light_brightness(dev: Device):
121
+ """Test brightness setter and getter."""
122
+ assert isinstance(dev, Device)
123
+ light = dev.modules.get(Module.Light)
124
+ assert light
125
+
126
+ # Test getting the value
127
+ feature = dev.features["brightness"]
128
+ assert feature.minimum_value == 0
129
+ assert feature.maximum_value == 100
130
+
131
+ await light.set_brightness(10)
132
+ await dev.update()
133
+ assert light.brightness == 10
134
+
135
+ with pytest.raises(ValueError):
136
+ await light.set_brightness(feature.minimum_value - 10)
137
+
138
+ with pytest.raises(ValueError):
139
+ await light.set_brightness(feature.maximum_value + 10)
140
+
141
+
142
+ @light_preset
143
+ async def test_light_preset_module(dev: Device, mocker: MockerFixture):
144
+ """Test light preset module."""
145
+ preset_mod = dev.modules[Module.LightPreset]
146
+ assert preset_mod
147
+ light_mod = dev.modules[Module.Light]
148
+ assert light_mod
149
+ feat = dev.features["light_preset"]
150
+
151
+ call = mocker.spy(light_mod, "set_state")
152
+ preset_list = preset_mod.preset_list
153
+ assert "Not set" in preset_list
154
+ assert preset_list.index("Not set") == 0
155
+ assert preset_list == feat.choices
156
+
157
+ assert preset_mod.has_save_preset is True
158
+
159
+ await light_mod.set_brightness(33) # Value that should not be a preset
160
+ assert call.call_count == 0
161
+ await dev.update()
162
+ assert preset_mod.preset == "Not set"
163
+ assert feat.value == "Not set"
164
+
165
+ if len(preset_list) == 1:
166
+ return
167
+
168
+ second_preset = preset_list[1]
169
+ await preset_mod.set_preset(second_preset)
170
+ assert call.call_count == 1
171
+ await dev.update()
172
+ assert preset_mod.preset == second_preset
173
+ assert feat.value == second_preset
174
+
175
+ last_preset = preset_list[len(preset_list) - 1]
176
+ await preset_mod.set_preset(last_preset)
177
+ assert call.call_count == 2
178
+ await dev.update()
179
+ assert preset_mod.preset == last_preset
180
+ assert feat.value == last_preset
181
+
182
+ # Test feature set
183
+ await feat.set_value(second_preset)
184
+ assert call.call_count == 3
185
+ await dev.update()
186
+ assert preset_mod.preset == second_preset
187
+ assert feat.value == second_preset
188
+
189
+ with pytest.raises(ValueError):
190
+ await preset_mod.set_preset("foobar")
191
+ assert call.call_count == 3
192
+
193
+
194
+ @light_preset
195
+ async def test_light_preset_save(dev: Device, mocker: MockerFixture):
196
+ """Test saving a new preset value."""
197
+ preset_mod = dev.modules[Module.LightPreset]
198
+ assert preset_mod
199
+ preset_list = preset_mod.preset_list
200
+ if len(preset_list) == 1:
201
+ return
202
+
203
+ second_preset = preset_list[1]
204
+ if preset_mod.preset_states_list[0].hue is None:
205
+ new_preset = LightState(brightness=52)
206
+ else:
207
+ new_preset = LightState(brightness=52, color_temp=3000, hue=20, saturation=30)
208
+ await preset_mod.save_preset(second_preset, new_preset)
209
+ await dev.update()
210
+ new_preset_state = preset_mod.preset_states_list[0]
211
+ assert (
212
+ new_preset_state.brightness == new_preset.brightness
213
+ and new_preset_state.hue == new_preset.hue
214
+ and new_preset_state.saturation == new_preset.saturation
215
+ and new_preset_state.color_temp == new_preset.color_temp
216
+ )
@@ -0,0 +1,268 @@
1
+ """Tests for all devices."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import inspect
7
+ import pkgutil
8
+ import sys
9
+ from unittest.mock import Mock, patch
10
+
11
+ import pytest
12
+
13
+ import kasa
14
+ from kasa import Credentials, Device, DeviceConfig, DeviceType, KasaException, Module
15
+ from kasa.iot import IotDevice
16
+ from kasa.iot.modules import IotLightPreset
17
+ from kasa.smart import SmartChildDevice, SmartDevice
18
+
19
+
20
+ def _get_subclasses(of_class):
21
+ package = sys.modules["kasa"]
22
+ subclasses = set()
23
+ for _, modname, _ in pkgutil.iter_modules(package.__path__):
24
+ importlib.import_module("." + modname, package="kasa")
25
+ module = sys.modules["kasa." + modname]
26
+ for name, obj in inspect.getmembers(module):
27
+ if (
28
+ inspect.isclass(obj)
29
+ and issubclass(obj, of_class)
30
+ and module.__package__ != "kasa"
31
+ and module.__package__ != "kasa.interfaces"
32
+ ):
33
+ subclasses.add((module.__package__ + "." + name, obj))
34
+ return subclasses
35
+
36
+
37
+ device_classes = pytest.mark.parametrize(
38
+ "device_class_name_obj", _get_subclasses(Device), ids=lambda t: t[0]
39
+ )
40
+
41
+
42
+ async def test_alias(dev):
43
+ test_alias = "TEST1234"
44
+ original = dev.alias
45
+
46
+ assert isinstance(original, str)
47
+ await dev.set_alias(test_alias)
48
+ await dev.update()
49
+ assert dev.alias == test_alias
50
+
51
+ await dev.set_alias(original)
52
+ await dev.update()
53
+ assert dev.alias == original
54
+
55
+
56
+ @device_classes
57
+ async def test_device_class_ctors(device_class_name_obj):
58
+ """Make sure constructor api not broken for new and existing SmartDevices."""
59
+ host = "127.0.0.2"
60
+ port = 1234
61
+ credentials = Credentials("foo", "bar")
62
+ config = DeviceConfig(host, port_override=port, credentials=credentials)
63
+ klass = device_class_name_obj[1]
64
+ if issubclass(klass, SmartChildDevice):
65
+ parent = SmartDevice(host, config=config)
66
+ dev = klass(
67
+ parent, {"dummy": "info", "device_id": "dummy"}, {"dummy": "components"}
68
+ )
69
+ else:
70
+ dev = klass(host, config=config)
71
+ assert dev.host == host
72
+ assert dev.port == port
73
+ assert dev.credentials == credentials
74
+
75
+
76
+ async def test_create_device_with_timeout():
77
+ """Make sure timeout is passed to the protocol."""
78
+ host = "127.0.0.1"
79
+ dev = IotDevice(host, config=DeviceConfig(host, timeout=100))
80
+ assert dev.protocol._transport._timeout == 100
81
+ dev = SmartDevice(host, config=DeviceConfig(host, timeout=100))
82
+ assert dev.protocol._transport._timeout == 100
83
+
84
+
85
+ async def test_create_thin_wrapper():
86
+ """Make sure thin wrapper is created with the correct device type."""
87
+ mock = Mock()
88
+ config = DeviceConfig(
89
+ host="test_host",
90
+ port_override=1234,
91
+ timeout=100,
92
+ credentials=Credentials("username", "password"),
93
+ )
94
+ with patch("kasa.device_factory.connect", return_value=mock) as connect:
95
+ dev = await Device.connect(config=config)
96
+ assert dev is mock
97
+
98
+ connect.assert_called_once_with(
99
+ host=None,
100
+ config=config,
101
+ )
102
+
103
+
104
+ @pytest.mark.parametrize(
105
+ "device_class, use_class", kasa.deprecated_smart_devices.items()
106
+ )
107
+ def test_deprecated_devices(device_class, use_class):
108
+ package_name = ".".join(use_class.__module__.split(".")[:-1])
109
+ msg = f"{device_class} is deprecated, use {use_class.__name__} from package {package_name} instead"
110
+ with pytest.deprecated_call(match=msg):
111
+ getattr(kasa, device_class)
112
+ packages = package_name.split(".")
113
+ module = __import__(packages[0])
114
+ for _ in packages[1:]:
115
+ module = importlib.import_module(package_name, package=module.__name__)
116
+ getattr(module, use_class.__name__)
117
+
118
+
119
+ @pytest.mark.parametrize(
120
+ "exceptions_class, use_class", kasa.deprecated_exceptions.items()
121
+ )
122
+ def test_deprecated_exceptions(exceptions_class, use_class):
123
+ msg = f"{exceptions_class} is deprecated, use {use_class.__name__} instead"
124
+ with pytest.deprecated_call(match=msg):
125
+ getattr(kasa, exceptions_class)
126
+ getattr(kasa, use_class.__name__)
127
+
128
+
129
+ deprecated_is_device_type = {
130
+ "is_bulb": DeviceType.Bulb,
131
+ "is_plug": DeviceType.Plug,
132
+ "is_dimmer": DeviceType.Dimmer,
133
+ "is_light_strip": DeviceType.LightStrip,
134
+ "is_wallswitch": DeviceType.WallSwitch,
135
+ "is_strip": DeviceType.Strip,
136
+ "is_strip_socket": DeviceType.StripSocket,
137
+ }
138
+ deprecated_is_light_function_smart_module = {
139
+ "is_color": "Color",
140
+ "is_dimmable": "Brightness",
141
+ "is_variable_color_temp": "ColorTemperature",
142
+ }
143
+
144
+
145
+ def test_deprecated_device_type_attributes(dev: SmartDevice):
146
+ """Test deprecated attributes on all devices."""
147
+
148
+ def _test_attr(attribute):
149
+ msg = f"{attribute} is deprecated"
150
+ if module := Device._deprecated_device_type_attributes[attribute][0]:
151
+ msg += f", use: {module} in device.modules instead"
152
+ with pytest.deprecated_call(match=msg):
153
+ val = getattr(dev, attribute)
154
+ return val
155
+
156
+ for attribute in deprecated_is_device_type:
157
+ val = _test_attr(attribute)
158
+ expected_val = dev.device_type == deprecated_is_device_type[attribute]
159
+ assert val == expected_val
160
+
161
+
162
+ async def _test_attribute(
163
+ dev: Device, attribute_name, is_expected, module_name, *args, will_raise=False
164
+ ):
165
+ if is_expected and will_raise:
166
+ ctx = pytest.raises(will_raise)
167
+ elif is_expected:
168
+ ctx = pytest.deprecated_call(
169
+ match=(
170
+ f"{attribute_name} is deprecated, use: Module."
171
+ + f"{module_name} in device.modules instead"
172
+ )
173
+ )
174
+ else:
175
+ ctx = pytest.raises(
176
+ AttributeError, match=f"Device has no attribute '{attribute_name}'"
177
+ )
178
+
179
+ with ctx:
180
+ if args:
181
+ await getattr(dev, attribute_name)(*args)
182
+ else:
183
+ attribute_val = getattr(dev, attribute_name)
184
+ assert attribute_val is not None
185
+
186
+
187
+ async def test_deprecated_light_effect_attributes(dev: Device):
188
+ light_effect = dev.modules.get(Module.LightEffect)
189
+
190
+ await _test_attribute(dev, "effect", bool(light_effect), "LightEffect")
191
+ await _test_attribute(dev, "effect_list", bool(light_effect), "LightEffect")
192
+ await _test_attribute(dev, "set_effect", bool(light_effect), "LightEffect", "Off")
193
+ exc = (
194
+ NotImplementedError
195
+ if light_effect and not light_effect.has_custom_effects
196
+ else None
197
+ )
198
+ await _test_attribute(
199
+ dev,
200
+ "set_custom_effect",
201
+ bool(light_effect),
202
+ "LightEffect",
203
+ {"enable": 0, "name": "foo", "id": "bar"},
204
+ will_raise=exc,
205
+ )
206
+
207
+
208
+ async def test_deprecated_light_attributes(dev: Device):
209
+ light = dev.modules.get(Module.Light)
210
+
211
+ await _test_attribute(dev, "is_dimmable", bool(light), "Light")
212
+ await _test_attribute(dev, "is_color", bool(light), "Light")
213
+ await _test_attribute(dev, "is_variable_color_temp", bool(light), "Light")
214
+
215
+ exc = KasaException if light and not light.is_dimmable else None
216
+ await _test_attribute(dev, "brightness", bool(light), "Light", will_raise=exc)
217
+ await _test_attribute(
218
+ dev, "set_brightness", bool(light), "Light", 50, will_raise=exc
219
+ )
220
+
221
+ exc = KasaException if light and not light.is_color else None
222
+ await _test_attribute(dev, "hsv", bool(light), "Light", will_raise=exc)
223
+ await _test_attribute(
224
+ dev, "set_hsv", bool(light), "Light", 50, 50, 50, will_raise=exc
225
+ )
226
+
227
+ exc = KasaException if light and not light.is_variable_color_temp else None
228
+ await _test_attribute(dev, "color_temp", bool(light), "Light", will_raise=exc)
229
+ await _test_attribute(
230
+ dev, "set_color_temp", bool(light), "Light", 2700, will_raise=exc
231
+ )
232
+ await _test_attribute(
233
+ dev, "valid_temperature_range", bool(light), "Light", will_raise=exc
234
+ )
235
+
236
+ await _test_attribute(dev, "has_effects", bool(light), "Light")
237
+
238
+
239
+ async def test_deprecated_other_attributes(dev: Device):
240
+ led_module = dev.modules.get(Module.Led)
241
+
242
+ await _test_attribute(dev, "led", bool(led_module), "Led")
243
+ await _test_attribute(dev, "set_led", bool(led_module), "Led", True)
244
+
245
+
246
+ async def test_deprecated_light_preset_attributes(dev: Device):
247
+ preset = dev.modules.get(Module.LightPreset)
248
+
249
+ exc: type[AttributeError] | type[KasaException] | None = (
250
+ AttributeError if not preset else None
251
+ )
252
+ await _test_attribute(dev, "presets", bool(preset), "LightPreset", will_raise=exc)
253
+
254
+ exc = None
255
+ # deprecated save_preset not implemented for smart devices as it's unlikely anyone
256
+ # has an existing reliance on this for the newer devices.
257
+ if not preset or isinstance(dev, SmartDevice):
258
+ exc = AttributeError
259
+ elif len(preset.preset_states_list) == 0:
260
+ exc = KasaException
261
+ await _test_attribute(
262
+ dev,
263
+ "save_preset",
264
+ bool(preset),
265
+ "LightPreset",
266
+ IotLightPreset(index=0, hue=100, brightness=100, saturation=0, color_temp=0), # type: ignore[call-arg]
267
+ will_raise=exc,
268
+ )
@@ -1,22 +1,21 @@
1
1
  # type: ignore
2
2
  import logging
3
- from typing import Type
4
3
 
5
4
  import aiohttp
6
5
  import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342
7
6
 
8
7
  from kasa import (
9
8
  Credentials,
10
- DeviceType,
9
+ Device,
11
10
  Discover,
12
- SmartBulb,
13
- SmartDevice,
14
- SmartDeviceException,
15
- SmartDimmer,
16
- SmartLightStrip,
17
- SmartPlug,
11
+ KasaException,
12
+ )
13
+ from kasa.device_factory import (
14
+ _get_device_type_from_sys_info,
15
+ connect,
16
+ get_device_class_from_family,
17
+ get_protocol,
18
18
  )
19
- from kasa.device_factory import connect, get_protocol
20
19
  from kasa.deviceconfig import (
21
20
  ConnectionType,
22
21
  DeviceConfig,
@@ -24,11 +23,11 @@ from kasa.deviceconfig import (
24
23
  EncryptType,
25
24
  )
26
25
  from kasa.discover import DiscoveryResult
26
+ from kasa.smart.smartdevice import SmartDevice
27
27
 
28
28
 
29
- def _get_connection_type_device_class(the_fixture_data):
30
- if "discovery_result" in the_fixture_data:
31
- discovery_info = {"result": the_fixture_data["discovery_result"]}
29
+ def _get_connection_type_device_class(discovery_info):
30
+ if "result" in discovery_info:
32
31
  device_class = Discover._get_device_class(discovery_info)
33
32
  dr = DiscoveryResult(**discovery_info["result"])
34
33
 
@@ -39,27 +38,24 @@ def _get_connection_type_device_class(the_fixture_data):
39
38
  connection_type = ConnectionType.from_values(
40
39
  DeviceFamilyType.IotSmartPlugSwitch.value, EncryptType.Xor.value
41
40
  )
42
- device_class = Discover._get_device_class(the_fixture_data)
41
+ device_class = Discover._get_device_class(discovery_info)
43
42
 
44
43
  return connection_type, device_class
45
44
 
46
45
 
47
46
  async def test_connect(
48
- all_fixture_data: dict,
47
+ discovery_data,
49
48
  mocker,
50
49
  ):
51
50
  """Test that if the protocol is passed in it gets set correctly."""
52
51
  host = "127.0.0.1"
53
- ctype, device_class = _get_connection_type_device_class(all_fixture_data)
54
-
55
- mocker.patch("kasa.IotProtocol.query", return_value=all_fixture_data)
56
- mocker.patch("kasa.SmartProtocol.query", return_value=all_fixture_data)
52
+ ctype, device_class = _get_connection_type_device_class(discovery_data)
57
53
 
58
54
  config = DeviceConfig(
59
55
  host=host, credentials=Credentials("foor", "bar"), connection_type=ctype
60
56
  )
61
57
  protocol_class = get_protocol(config).__class__
62
-
58
+ close_mock = mocker.patch.object(protocol_class, "close")
63
59
  dev = await connect(
64
60
  config=config,
65
61
  )
@@ -67,39 +63,38 @@ async def test_connect(
67
63
  assert isinstance(dev.protocol, protocol_class)
68
64
 
69
65
  assert dev.config == config
70
-
66
+ assert close_mock.call_count == 0
71
67
  await dev.disconnect()
68
+ assert close_mock.call_count == 1
72
69
 
73
70
 
74
71
  @pytest.mark.parametrize("custom_port", [123, None])
75
- async def test_connect_custom_port(all_fixture_data: dict, mocker, custom_port):
72
+ async def test_connect_custom_port(discovery_data: dict, mocker, custom_port):
76
73
  """Make sure that connect returns an initialized SmartDevice instance."""
77
74
  host = "127.0.0.1"
78
75
 
79
- ctype, _ = _get_connection_type_device_class(all_fixture_data)
76
+ ctype, _ = _get_connection_type_device_class(discovery_data)
80
77
  config = DeviceConfig(
81
78
  host=host,
82
79
  port_override=custom_port,
83
80
  connection_type=ctype,
84
81
  credentials=Credentials("dummy_user", "dummy_password"),
85
82
  )
86
- default_port = 80 if "discovery_result" in all_fixture_data else 9999
83
+ default_port = 80 if "result" in discovery_data else 9999
84
+
85
+ ctype, _ = _get_connection_type_device_class(discovery_data)
87
86
 
88
- ctype, _ = _get_connection_type_device_class(all_fixture_data)
89
- mocker.patch("kasa.IotProtocol.query", return_value=all_fixture_data)
90
- mocker.patch("kasa.SmartProtocol.query", return_value=all_fixture_data)
91
87
  dev = await connect(config=config)
92
- assert issubclass(dev.__class__, SmartDevice)
88
+ assert issubclass(dev.__class__, Device)
93
89
  assert dev.port == custom_port or dev.port == default_port
94
90
 
95
91
 
96
92
  async def test_connect_logs_connect_time(
97
- all_fixture_data: dict, caplog: pytest.LogCaptureFixture, mocker
93
+ discovery_data: dict,
94
+ caplog: pytest.LogCaptureFixture,
98
95
  ):
99
96
  """Test that the connect time is logged when debug logging is enabled."""
100
- ctype, _ = _get_connection_type_device_class(all_fixture_data)
101
- mocker.patch("kasa.IotProtocol.query", return_value=all_fixture_data)
102
- mocker.patch("kasa.SmartProtocol.query", return_value=all_fixture_data)
97
+ ctype, _ = _get_connection_type_device_class(discovery_data)
103
98
 
104
99
  host = "127.0.0.1"
105
100
  config = DeviceConfig(
@@ -112,28 +107,29 @@ async def test_connect_logs_connect_time(
112
107
  assert "seconds to update" in caplog.text
113
108
 
114
109
 
115
- async def test_connect_query_fails(all_fixture_data: dict, mocker):
110
+ async def test_connect_query_fails(discovery_data, mocker):
116
111
  """Make sure that connect fails when query fails."""
117
112
  host = "127.0.0.1"
118
- mocker.patch("kasa.IotProtocol.query", side_effect=SmartDeviceException)
119
- mocker.patch("kasa.SmartProtocol.query", side_effect=SmartDeviceException)
113
+ mocker.patch("kasa.IotProtocol.query", side_effect=KasaException)
114
+ mocker.patch("kasa.SmartProtocol.query", side_effect=KasaException)
120
115
 
121
- ctype, _ = _get_connection_type_device_class(all_fixture_data)
116
+ ctype, _ = _get_connection_type_device_class(discovery_data)
122
117
  config = DeviceConfig(
123
118
  host=host, credentials=Credentials("foor", "bar"), connection_type=ctype
124
119
  )
125
- with pytest.raises(SmartDeviceException):
120
+ protocol_class = get_protocol(config).__class__
121
+ close_mock = mocker.patch.object(protocol_class, "close")
122
+ assert close_mock.call_count == 0
123
+ with pytest.raises(KasaException):
126
124
  await connect(config=config)
125
+ assert close_mock.call_count == 1
127
126
 
128
127
 
129
- async def test_connect_http_client(all_fixture_data, mocker):
128
+ async def test_connect_http_client(discovery_data, mocker):
130
129
  """Make sure that discover_single returns an initialized SmartDevice instance."""
131
130
  host = "127.0.0.1"
132
131
 
133
- ctype, _ = _get_connection_type_device_class(all_fixture_data)
134
-
135
- mocker.patch("kasa.IotProtocol.query", return_value=all_fixture_data)
136
- mocker.patch("kasa.SmartProtocol.query", return_value=all_fixture_data)
132
+ ctype, _ = _get_connection_type_device_class(discovery_data)
137
133
 
138
134
  http_client = aiohttp.ClientSession()
139
135
 
@@ -143,6 +139,7 @@ async def test_connect_http_client(all_fixture_data, mocker):
143
139
  dev = await connect(config=config)
144
140
  if ctype.encryption_type != EncryptType.Xor:
145
141
  assert dev.protocol._transport._http_client.client != http_client
142
+ await dev.disconnect()
146
143
 
147
144
  config = DeviceConfig(
148
145
  host=host,
@@ -153,3 +150,26 @@ async def test_connect_http_client(all_fixture_data, mocker):
153
150
  dev = await connect(config=config)
154
151
  if ctype.encryption_type != EncryptType.Xor:
155
152
  assert dev.protocol._transport._http_client.client == http_client
153
+ await dev.disconnect()
154
+ await http_client.close()
155
+
156
+
157
+ async def test_device_types(dev: Device):
158
+ await dev.update()
159
+ if isinstance(dev, SmartDevice):
160
+ device_type = dev._discovery_info["result"]["device_type"]
161
+ res = SmartDevice._get_device_type_from_components(
162
+ dev._components.keys(), device_type
163
+ )
164
+ else:
165
+ res = _get_device_type_from_sys_info(dev._last_update)
166
+
167
+ assert dev.device_type == res
168
+
169
+
170
+ async def test_device_class_from_unknown_family(caplog):
171
+ """Verify that unknown SMART devices yield a warning and fallback to SmartDevice."""
172
+ dummy_name = "SMART.foo"
173
+ with caplog.at_level(logging.WARNING):
174
+ assert get_device_class_from_family(dummy_name) == SmartDevice
175
+ assert f"Unknown SMART device with {dummy_name}" in caplog.text
@@ -1,4 +1,4 @@
1
- from kasa.smartdevice import DeviceType
1
+ from kasa.device_type import DeviceType
2
2
 
3
3
 
4
4
  async def test_device_type_from_value():