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
@@ -1,12 +1,8 @@
1
- import errno
2
1
  import json
3
2
  import logging
4
3
  import secrets
5
- import struct
6
- import sys
7
4
  import time
8
5
  from contextlib import nullcontext as does_not_raise
9
- from unittest.mock import PropertyMock
10
6
 
11
7
  import aiohttp
12
8
  import pytest
@@ -16,11 +12,11 @@ from ..aestransport import AesTransport
16
12
  from ..credentials import Credentials
17
13
  from ..deviceconfig import DeviceConfig
18
14
  from ..exceptions import (
19
- AuthenticationException,
20
- ConnectionException,
21
- RetryableException,
22
- SmartDeviceException,
23
- TimeoutException,
15
+ AuthenticationError,
16
+ KasaException,
17
+ TimeoutError,
18
+ _ConnectionError,
19
+ _RetryableError,
24
20
  )
25
21
  from ..httpclient import HttpClient
26
22
  from ..iotprotocol import IotProtocol
@@ -72,7 +68,7 @@ async def test_protocol_retries_via_client_session(
72
68
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
73
69
 
74
70
  config = DeviceConfig(host)
75
- with pytest.raises(SmartDeviceException):
71
+ with pytest.raises(KasaException):
76
72
  await protocol_class(transport=transport_class(config=config)).query(
77
73
  DUMMY_QUERY, retry_count=retry_count
78
74
  )
@@ -84,11 +80,11 @@ async def test_protocol_retries_via_client_session(
84
80
  @pytest.mark.parametrize(
85
81
  "error, retry_expectation",
86
82
  [
87
- (SmartDeviceException("dummy exception"), False),
88
- (RetryableException("dummy exception"), True),
89
- (TimeoutException("dummy exception"), True),
83
+ (KasaException("dummy exception"), False),
84
+ (_RetryableError("dummy exception"), True),
85
+ (TimeoutError("dummy exception"), True),
90
86
  ],
91
- ids=("SmartDeviceException", "RetryableException", "TimeoutException"),
87
+ ids=("KasaException", "_RetryableError", "TimeoutError"),
92
88
  )
93
89
  @pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
94
90
  @pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
@@ -101,7 +97,7 @@ async def test_protocol_retries_via_httpclient(
101
97
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
102
98
 
103
99
  config = DeviceConfig(host)
104
- with pytest.raises(SmartDeviceException):
100
+ with pytest.raises(KasaException):
105
101
  await protocol_class(transport=transport_class(config=config)).query(
106
102
  DUMMY_QUERY, retry_count=retry_count
107
103
  )
@@ -119,11 +115,11 @@ async def test_protocol_no_retry_on_connection_error(
119
115
  conn = mocker.patch.object(
120
116
  aiohttp.ClientSession,
121
117
  "post",
122
- side_effect=AuthenticationException("foo"),
118
+ side_effect=AuthenticationError("foo"),
123
119
  )
124
120
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
125
121
  config = DeviceConfig(host)
126
- with pytest.raises(SmartDeviceException):
122
+ with pytest.raises(KasaException):
127
123
  await protocol_class(transport=transport_class(config=config)).query(
128
124
  DUMMY_QUERY, retry_count=5
129
125
  )
@@ -143,7 +139,7 @@ async def test_protocol_retry_recoverable_error(
143
139
  side_effect=aiohttp.ClientOSError("foo"),
144
140
  )
145
141
  config = DeviceConfig(host)
146
- with pytest.raises(SmartDeviceException):
142
+ with pytest.raises(KasaException):
147
143
  await protocol_class(transport=transport_class(config=config)).query(
148
144
  DUMMY_QUERY, retry_count=5
149
145
  )
@@ -163,7 +159,7 @@ async def test_protocol_reconnect(mocker, retry_count, protocol_class, transport
163
159
  nonlocal remaining
164
160
  remaining -= 1
165
161
  if remaining:
166
- raise ConnectionException("Simulated connection failure")
162
+ raise _ConnectionError("Simulated connection failure")
167
163
 
168
164
  return mock_response
169
165
 
@@ -253,7 +249,7 @@ def test_encrypt_unicode():
253
249
  ),
254
250
  (
255
251
  Credentials("shouldfail", "shouldfail"),
256
- pytest.raises(AuthenticationException),
252
+ pytest.raises(AuthenticationError),
257
253
  ),
258
254
  ],
259
255
  ids=("client", "blank", "kasa_setup", "shouldfail"),
@@ -327,14 +323,14 @@ async def test_handshake(
327
323
  async def _return_handshake_response(url: URL, params=None, data=None, *_, **__):
328
324
  nonlocal client_seed, server_seed, device_auth_hash
329
325
 
330
- if str(url) == "http://127.0.0.1/app/handshake1":
326
+ if str(url) == "http://127.0.0.1:80/app/handshake1":
331
327
  client_seed = data
332
328
  seed_auth_hash = _sha256(
333
329
  seed_auth_hash_calc1(client_seed, server_seed, device_auth_hash)
334
330
  )
335
331
 
336
332
  return _mock_response(200, server_seed + seed_auth_hash)
337
- elif str(url) == "http://127.0.0.1/app/handshake2":
333
+ elif str(url) == "http://127.0.0.1:80/app/handshake2":
338
334
  seed_auth_hash = _sha256(
339
335
  seed_auth_hash_calc2(client_seed, server_seed, device_auth_hash)
340
336
  )
@@ -354,7 +350,7 @@ async def test_handshake(
354
350
  assert protocol._transport._handshake_done is True
355
351
 
356
352
  response_status = 403
357
- with pytest.raises(AuthenticationException):
353
+ with pytest.raises(KasaException):
358
354
  await protocol._transport.perform_handshake()
359
355
  assert protocol._transport._handshake_done is False
360
356
  await protocol.close()
@@ -371,14 +367,14 @@ async def test_query(mocker):
371
367
  async def _return_response(url: URL, params=None, data=None, *_, **__):
372
368
  nonlocal client_seed, server_seed, device_auth_hash, seq
373
369
 
374
- if str(url) == "http://127.0.0.1/app/handshake1":
370
+ if str(url) == "http://127.0.0.1:80/app/handshake1":
375
371
  client_seed = data
376
372
  client_seed_auth_hash = _sha256(data + device_auth_hash)
377
373
 
378
374
  return _mock_response(200, server_seed + client_seed_auth_hash)
379
- elif str(url) == "http://127.0.0.1/app/handshake2":
375
+ elif str(url) == "http://127.0.0.1:80/app/handshake2":
380
376
  return _mock_response(200, b"")
381
- elif str(url) == "http://127.0.0.1/app/request":
377
+ elif str(url) == "http://127.0.0.1:80/app/request":
382
378
  encryption_session = KlapEncryptionSession(
383
379
  protocol._transport._encryption_session.local_seed,
384
380
  protocol._transport._encryption_session.remote_seed,
@@ -404,35 +400,81 @@ async def test_query(mocker):
404
400
 
405
401
 
406
402
  @pytest.mark.parametrize(
407
- "response_status, expectation",
403
+ "response_status, credentials_match, expectation",
408
404
  [
409
- ((403, 403, 403), pytest.raises(AuthenticationException)),
410
- ((200, 403, 403), pytest.raises(AuthenticationException)),
411
- ((200, 200, 403), pytest.raises(AuthenticationException)),
412
- ((200, 200, 400), pytest.raises(SmartDeviceException)),
405
+ pytest.param(
406
+ (403, 403, 403),
407
+ True,
408
+ pytest.raises(KasaException),
409
+ id="handshake1-403-status",
410
+ ),
411
+ pytest.param(
412
+ (200, 403, 403),
413
+ True,
414
+ pytest.raises(KasaException),
415
+ id="handshake2-403-status",
416
+ ),
417
+ pytest.param(
418
+ (200, 200, 403),
419
+ True,
420
+ pytest.raises(_RetryableError),
421
+ id="request-403-status",
422
+ ),
423
+ pytest.param(
424
+ (200, 200, 400),
425
+ True,
426
+ pytest.raises(KasaException),
427
+ id="request-400-status",
428
+ ),
429
+ pytest.param(
430
+ (200, 200, 200),
431
+ False,
432
+ pytest.raises(AuthenticationError),
433
+ id="handshake1-wrong-auth",
434
+ ),
435
+ pytest.param(
436
+ (200, 200, 200),
437
+ secrets.token_bytes(16),
438
+ pytest.raises(KasaException),
439
+ id="handshake1-bad-auth-length",
440
+ ),
413
441
  ],
414
- ids=("handshake1", "handshake2", "request", "non_auth_error"),
415
442
  )
416
- async def test_authentication_failures(mocker, response_status, expectation):
443
+ async def test_authentication_failures(
444
+ mocker, response_status, credentials_match, expectation
445
+ ):
417
446
  client_seed = None
418
447
 
419
448
  server_seed = secrets.token_bytes(16)
420
449
  client_credentials = Credentials("foo", "bar")
421
- device_auth_hash = KlapTransport.generate_auth_hash(client_credentials)
450
+ device_credentials = (
451
+ client_credentials if credentials_match else Credentials("bar", "foo")
452
+ )
453
+ device_auth_hash = KlapTransport.generate_auth_hash(device_credentials)
422
454
 
423
455
  async def _return_response(url: URL, params=None, data=None, *_, **__):
424
- nonlocal client_seed, server_seed, device_auth_hash, response_status
425
-
426
- if str(url) == "http://127.0.0.1/app/handshake1":
456
+ nonlocal \
457
+ client_seed, \
458
+ server_seed, \
459
+ device_auth_hash, \
460
+ response_status, \
461
+ credentials_match
462
+
463
+ if str(url) == "http://127.0.0.1:80/app/handshake1":
427
464
  client_seed = data
428
465
  client_seed_auth_hash = _sha256(data + device_auth_hash)
429
-
466
+ if credentials_match is not False and credentials_match is not True:
467
+ client_seed_auth_hash += credentials_match
430
468
  return _mock_response(
431
469
  response_status[0], server_seed + client_seed_auth_hash
432
470
  )
433
- elif str(url) == "http://127.0.0.1/app/handshake2":
434
- return _mock_response(response_status[1], b"")
435
- elif str(url) == "http://127.0.0.1/app/request":
471
+ elif str(url) == "http://127.0.0.1:80/app/handshake2":
472
+ client_seed = data
473
+ client_seed_auth_hash = _sha256(data + device_auth_hash)
474
+ return _mock_response(
475
+ response_status[1], server_seed + client_seed_auth_hash
476
+ )
477
+ elif str(url) == "http://127.0.0.1:80/app/request":
436
478
  return _mock_response(response_status[2], b"")
437
479
 
438
480
  mocker.patch.object(aiohttp.ClientSession, "post", side_effect=_return_response)
@@ -442,3 +484,14 @@ async def test_authentication_failures(mocker, response_status, expectation):
442
484
 
443
485
  with expectation:
444
486
  await protocol.query({})
487
+
488
+
489
+ async def test_port_override():
490
+ """Test that port override sets the app_url."""
491
+ host = "127.0.0.1"
492
+ config = DeviceConfig(
493
+ host, credentials=Credentials("foo", "bar"), port_override=12345
494
+ )
495
+ transport = KlapTransport(config=config)
496
+
497
+ assert str(transport._app_url) == "http://127.0.0.1:12345/app"
@@ -1,41 +1,41 @@
1
1
  import pytest
2
2
 
3
- from kasa import DeviceType, SmartLightStrip
4
- from kasa.exceptions import SmartDeviceException
3
+ from kasa import DeviceType
4
+ from kasa.iot import IotLightStrip
5
5
 
6
- from .conftest import lightstrip
6
+ from .conftest import lightstrip_iot
7
7
 
8
8
 
9
- @lightstrip
10
- async def test_lightstrip_length(dev: SmartLightStrip):
9
+ @lightstrip_iot
10
+ async def test_lightstrip_length(dev: IotLightStrip):
11
11
  assert dev.is_light_strip
12
12
  assert dev.device_type == DeviceType.LightStrip
13
13
  assert dev.length == dev.sys_info["length"]
14
14
 
15
15
 
16
- @lightstrip
17
- async def test_lightstrip_effect(dev: SmartLightStrip):
16
+ @lightstrip_iot
17
+ async def test_lightstrip_effect(dev: IotLightStrip):
18
18
  assert isinstance(dev.effect, dict)
19
19
  for k in ["brightness", "custom", "enable", "id", "name"]:
20
20
  assert k in dev.effect
21
21
 
22
22
 
23
- @lightstrip
24
- async def test_effects_lightstrip_set_effect(dev: SmartLightStrip):
25
- with pytest.raises(SmartDeviceException):
23
+ @lightstrip_iot
24
+ async def test_effects_lightstrip_set_effect(dev: IotLightStrip):
25
+ with pytest.raises(ValueError):
26
26
  await dev.set_effect("Not real")
27
27
 
28
28
  await dev.set_effect("Candy Cane")
29
+ await dev.update()
29
30
  assert dev.effect["name"] == "Candy Cane"
30
- assert dev.state_information["Effect"] == "Candy Cane"
31
31
 
32
32
 
33
- @lightstrip
33
+ @lightstrip_iot
34
34
  @pytest.mark.parametrize("brightness", [100, 50])
35
35
  async def test_effects_lightstrip_set_effect_brightness(
36
- dev: SmartLightStrip, brightness, mocker
36
+ dev: IotLightStrip, brightness, mocker
37
37
  ):
38
- query_helper = mocker.patch("kasa.SmartLightStrip._query_helper")
38
+ query_helper = mocker.patch("kasa.iot.IotLightStrip._query_helper")
39
39
 
40
40
  # test that default brightness works (100 for candy cane)
41
41
  if brightness == 100:
@@ -48,12 +48,12 @@ async def test_effects_lightstrip_set_effect_brightness(
48
48
  assert payload["brightness"] == brightness
49
49
 
50
50
 
51
- @lightstrip
51
+ @lightstrip_iot
52
52
  @pytest.mark.parametrize("transition", [500, 1000])
53
53
  async def test_effects_lightstrip_set_effect_transition(
54
- dev: SmartLightStrip, transition, mocker
54
+ dev: IotLightStrip, transition, mocker
55
55
  ):
56
- query_helper = mocker.patch("kasa.SmartLightStrip._query_helper")
56
+ query_helper = mocker.patch("kasa.iot.IotLightStrip._query_helper")
57
57
 
58
58
  # test that default (500 for candy cane) transition works
59
59
  if transition == 500:
@@ -66,7 +66,12 @@ async def test_effects_lightstrip_set_effect_transition(
66
66
  assert payload["transition"] == transition
67
67
 
68
68
 
69
- @lightstrip
70
- async def test_effects_lightstrip_has_effects(dev: SmartLightStrip):
69
+ @lightstrip_iot
70
+ async def test_effects_lightstrip_has_effects(dev: IotLightStrip):
71
71
  assert dev.has_effects is True
72
72
  assert dev.effect_list
73
+
74
+
75
+ @lightstrip_iot
76
+ def test_device_type_lightstrip(dev):
77
+ assert dev.device_type == DeviceType.LightStrip
kasa/tests/test_plug.py CHANGED
@@ -1,13 +1,17 @@
1
1
  from kasa import DeviceType
2
2
 
3
- from .conftest import plug, plug_smart
4
- from .newfakes import PLUG_SCHEMA
3
+ from .conftest import plug, plug_iot, plug_smart, switch_smart, wallswitch_iot
4
+ from .test_iotdevice import SYSINFO_SCHEMA
5
5
 
6
+ # these schemas should go to the mainlib as
7
+ # they can be useful when adding support for new features/devices
8
+ # as well as to check that faked devices are operating properly.
6
9
 
7
- @plug
10
+
11
+ @plug_iot
8
12
  async def test_plug_sysinfo(dev):
9
13
  assert dev.sys_info is not None
10
- PLUG_SCHEMA(dev.sys_info)
14
+ SYSINFO_SCHEMA(dev.sys_info)
11
15
 
12
16
  assert dev.model is not None
13
17
 
@@ -15,8 +19,34 @@ async def test_plug_sysinfo(dev):
15
19
  assert dev.is_plug or dev.is_strip
16
20
 
17
21
 
18
- @plug
19
- async def test_led(dev):
22
+ @wallswitch_iot
23
+ async def test_switch_sysinfo(dev):
24
+ assert dev.sys_info is not None
25
+ SYSINFO_SCHEMA(dev.sys_info)
26
+
27
+ assert dev.model is not None
28
+
29
+ assert dev.device_type == DeviceType.WallSwitch
30
+ assert dev.is_wallswitch
31
+
32
+
33
+ @plug_iot
34
+ async def test_plug_led(dev):
35
+ original = dev.led
36
+
37
+ await dev.set_led(False)
38
+ await dev.update()
39
+ assert not dev.led
40
+
41
+ await dev.set_led(True)
42
+ await dev.update()
43
+ assert dev.led
44
+
45
+ await dev.set_led(original)
46
+
47
+
48
+ @wallswitch_iot
49
+ async def test_switch_led(dev):
20
50
  original = dev.led
21
51
 
22
52
  await dev.set_led(False)
@@ -33,9 +63,21 @@ async def test_led(dev):
33
63
  @plug_smart
34
64
  async def test_plug_device_info(dev):
35
65
  assert dev._info is not None
36
- # PLUG_SCHEMA(dev.sys_info)
37
-
38
66
  assert dev.model is not None
39
67
 
40
68
  assert dev.device_type == DeviceType.Plug or dev.device_type == DeviceType.Strip
41
- # assert dev.is_plug or dev.is_strip
69
+
70
+
71
+ @switch_smart
72
+ async def test_switch_device_info(dev):
73
+ assert dev._info is not None
74
+ assert dev.model is not None
75
+
76
+ assert (
77
+ dev.device_type == DeviceType.WallSwitch or dev.device_type == DeviceType.Dimmer
78
+ )
79
+
80
+
81
+ @plug
82
+ def test_device_type_plug(dev):
83
+ assert dev.device_type == DeviceType.Plug
@@ -14,7 +14,7 @@ import pytest
14
14
  from ..aestransport import AesTransport
15
15
  from ..credentials import Credentials
16
16
  from ..deviceconfig import DeviceConfig
17
- from ..exceptions import SmartDeviceException
17
+ from ..exceptions import KasaException
18
18
  from ..iotprotocol import IotProtocol, _deprecated_TPLinkSmartHomeProtocol
19
19
  from ..klaptransport import KlapTransport, KlapTransportV2
20
20
  from ..protocol import (
@@ -46,7 +46,7 @@ async def test_protocol_retries(mocker, retry_count, protocol_class, transport_c
46
46
 
47
47
  conn = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
48
48
  config = DeviceConfig("127.0.0.1")
49
- with pytest.raises(SmartDeviceException):
49
+ with pytest.raises(KasaException):
50
50
  await protocol_class(transport=transport_class(config=config)).query(
51
51
  {}, retry_count=retry_count
52
52
  )
@@ -70,7 +70,7 @@ async def test_protocol_no_retry_on_unreachable(
70
70
  side_effect=OSError(errno.EHOSTUNREACH, "No route to host"),
71
71
  )
72
72
  config = DeviceConfig("127.0.0.1")
73
- with pytest.raises(SmartDeviceException):
73
+ with pytest.raises(KasaException):
74
74
  await protocol_class(transport=transport_class(config=config)).query(
75
75
  {}, retry_count=5
76
76
  )
@@ -94,7 +94,7 @@ async def test_protocol_no_retry_connection_refused(
94
94
  side_effect=ConnectionRefusedError,
95
95
  )
96
96
  config = DeviceConfig("127.0.0.1")
97
- with pytest.raises(SmartDeviceException):
97
+ with pytest.raises(KasaException):
98
98
  await protocol_class(transport=transport_class(config=config)).query(
99
99
  {}, retry_count=5
100
100
  )
@@ -118,7 +118,7 @@ async def test_protocol_retry_recoverable_error(
118
118
  side_effect=OSError(errno.ECONNRESET, "Connection reset by peer"),
119
119
  )
120
120
  config = DeviceConfig("127.0.0.1")
121
- with pytest.raises(SmartDeviceException):
121
+ with pytest.raises(KasaException):
122
122
  await protocol_class(transport=transport_class(config=config)).query(
123
123
  {}, retry_count=5
124
124
  )
@@ -461,8 +461,6 @@ def test_decrypt_unicode(decrypt_class):
461
461
 
462
462
 
463
463
  def _get_subclasses(of_class):
464
- import kasa
465
-
466
464
  package = sys.modules["kasa"]
467
465
  subclasses = set()
468
466
  for _, modname, _ in pkgutil.iter_modules(package.__path__):
@@ -555,7 +553,7 @@ async def test_protocol_will_retry_on_connect(
555
553
  retry_count = 2
556
554
  conn = mocker.patch("asyncio.open_connection", side_effect=error)
557
555
  config = DeviceConfig("127.0.0.1")
558
- with pytest.raises(SmartDeviceException):
556
+ with pytest.raises(KasaException):
559
557
  await protocol_class(transport=transport_class(config=config)).query(
560
558
  {}, retry_count=retry_count
561
559
  )
@@ -597,7 +595,7 @@ async def test_protocol_will_retry_on_write(
597
595
  conn = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
598
596
  write_mock = mocker.patch("asyncio.StreamWriter.write", side_effect=error)
599
597
  config = DeviceConfig("127.0.0.1")
600
- with pytest.raises(SmartDeviceException):
598
+ with pytest.raises(KasaException):
601
599
  await protocol_class(transport=transport_class(config=config)).query(
602
600
  {}, retry_count=retry_count
603
601
  )
@@ -611,9 +609,7 @@ def test_deprecated_protocol():
611
609
  with pytest.deprecated_call():
612
610
  from kasa import TPLinkSmartHomeProtocol
613
611
 
614
- with pytest.raises(
615
- SmartDeviceException, match="host or transport must be supplied"
616
- ):
612
+ with pytest.raises(KasaException, match="host or transport must be supplied"):
617
613
  proto = TPLinkSmartHomeProtocol()
618
614
  host = "127.0.0.1"
619
615
  proto = TPLinkSmartHomeProtocol(host=host)
@@ -1,70 +1,129 @@
1
1
  import asyncio
2
- import sys
3
2
 
4
3
  import pytest
5
4
  import xdoctest
6
5
 
7
- from kasa.tests.conftest import get_device_for_file
6
+ from kasa import Discover
7
+ from kasa.tests.conftest import get_device_for_fixture_protocol
8
8
 
9
9
 
10
10
  def test_bulb_examples(mocker):
11
11
  """Use KL130 (bulb with all features) to test the doctests."""
12
- p = asyncio.run(get_device_for_file("KL130(US)_1.0_1.8.11.json", "IOT"))
13
- mocker.patch("kasa.smartbulb.SmartBulb", return_value=p)
14
- mocker.patch("kasa.smartbulb.SmartBulb.update")
15
- res = xdoctest.doctest_module("kasa.smartbulb", "all")
12
+ p = asyncio.run(get_device_for_fixture_protocol("KL130(US)_1.0_1.8.11.json", "IOT"))
13
+ mocker.patch("kasa.iot.iotbulb.IotBulb", return_value=p)
14
+ mocker.patch("kasa.iot.iotbulb.IotBulb.update")
15
+ res = xdoctest.doctest_module("kasa.iot.iotbulb", "all")
16
16
  assert not res["failed"]
17
17
 
18
18
 
19
19
  def test_smartdevice_examples(mocker):
20
20
  """Use HS110 for emeter examples."""
21
- p = asyncio.run(get_device_for_file("HS110(EU)_1.0_1.2.5.json", "IOT"))
22
- mocker.patch("kasa.smartdevice.SmartDevice", return_value=p)
23
- mocker.patch("kasa.smartdevice.SmartDevice.update")
24
- res = xdoctest.doctest_module("kasa.smartdevice", "all")
21
+ p = asyncio.run(get_device_for_fixture_protocol("HS110(EU)_1.0_1.2.5.json", "IOT"))
22
+ mocker.patch("kasa.iot.iotdevice.IotDevice", return_value=p)
23
+ mocker.patch("kasa.iot.iotdevice.IotDevice.update")
24
+ res = xdoctest.doctest_module("kasa.iot.iotdevice", "all")
25
25
  assert not res["failed"]
26
26
 
27
27
 
28
28
  def test_plug_examples(mocker):
29
29
  """Test plug examples."""
30
- p = asyncio.run(get_device_for_file("HS110(EU)_1.0_1.2.5.json", "IOT"))
31
- mocker.patch("kasa.smartplug.SmartPlug", return_value=p)
32
- mocker.patch("kasa.smartplug.SmartPlug.update")
33
- res = xdoctest.doctest_module("kasa.smartplug", "all")
30
+ p = asyncio.run(get_device_for_fixture_protocol("HS110(EU)_1.0_1.2.5.json", "IOT"))
31
+ # p = await get_device_for_fixture_protocol("HS110(EU)_1.0_1.2.5.json", "IOT")
32
+ mocker.patch("kasa.iot.iotplug.IotPlug", return_value=p)
33
+ mocker.patch("kasa.iot.iotplug.IotPlug.update")
34
+ res = xdoctest.doctest_module("kasa.iot.iotplug", "all")
34
35
  assert not res["failed"]
35
36
 
36
37
 
37
38
  def test_strip_examples(mocker):
38
39
  """Test strip examples."""
39
- p = asyncio.run(get_device_for_file("KP303(UK)_1.0_1.0.3.json", "IOT"))
40
- mocker.patch("kasa.smartstrip.SmartStrip", return_value=p)
41
- mocker.patch("kasa.smartstrip.SmartStrip.update")
42
- res = xdoctest.doctest_module("kasa.smartstrip", "all")
40
+ p = asyncio.run(get_device_for_fixture_protocol("KP303(UK)_1.0_1.0.3.json", "IOT"))
41
+ mocker.patch("kasa.iot.iotstrip.IotStrip", return_value=p)
42
+ mocker.patch("kasa.iot.iotstrip.IotStrip.update")
43
+ res = xdoctest.doctest_module("kasa.iot.iotstrip", "all")
43
44
  assert not res["failed"]
44
45
 
45
46
 
46
47
  def test_dimmer_examples(mocker):
47
48
  """Test dimmer examples."""
48
- p = asyncio.run(get_device_for_file("HS220(US)_1.0_1.5.7.json", "IOT"))
49
- mocker.patch("kasa.smartdimmer.SmartDimmer", return_value=p)
50
- mocker.patch("kasa.smartdimmer.SmartDimmer.update")
51
- res = xdoctest.doctest_module("kasa.smartdimmer", "all")
49
+ p = asyncio.run(get_device_for_fixture_protocol("HS220(US)_1.0_1.5.7.json", "IOT"))
50
+ mocker.patch("kasa.iot.iotdimmer.IotDimmer", return_value=p)
51
+ mocker.patch("kasa.iot.iotdimmer.IotDimmer.update")
52
+ res = xdoctest.doctest_module("kasa.iot.iotdimmer", "all")
52
53
  assert not res["failed"]
53
54
 
54
55
 
55
56
  def test_lightstrip_examples(mocker):
56
57
  """Test lightstrip examples."""
57
- p = asyncio.run(get_device_for_file("KL430(US)_1.0_1.0.10.json", "IOT"))
58
- mocker.patch("kasa.smartlightstrip.SmartLightStrip", return_value=p)
59
- mocker.patch("kasa.smartlightstrip.SmartLightStrip.update")
60
- res = xdoctest.doctest_module("kasa.smartlightstrip", "all")
58
+ p = asyncio.run(get_device_for_fixture_protocol("KL430(US)_1.0_1.0.10.json", "IOT"))
59
+ mocker.patch("kasa.iot.iotlightstrip.IotLightStrip", return_value=p)
60
+ mocker.patch("kasa.iot.iotlightstrip.IotLightStrip.update")
61
+ res = xdoctest.doctest_module("kasa.iot.iotlightstrip", "all")
61
62
  assert not res["failed"]
62
63
 
63
64
 
64
65
  def test_discovery_examples(mocker):
65
66
  """Test discovery examples."""
66
- p = asyncio.run(get_device_for_file("KP303(UK)_1.0_1.0.3.json", "IOT"))
67
+ p = asyncio.run(get_device_for_fixture_protocol("KP303(UK)_1.0_1.0.3.json", "IOT"))
67
68
 
68
69
  mocker.patch("kasa.discover.Discover.discover", return_value=[p])
69
70
  res = xdoctest.doctest_module("kasa.discover", "all")
70
71
  assert not res["failed"]
72
+
73
+
74
+ def test_tutorial_examples(mocker, top_level_await):
75
+ """Test discovery examples."""
76
+ a = asyncio.run(
77
+ get_device_for_fixture_protocol("L530E(EU)_3.0_1.1.6.json", "SMART")
78
+ )
79
+ b = asyncio.run(get_device_for_fixture_protocol("HS110(EU)_1.0_1.2.5.json", "IOT"))
80
+ a.host = "127.0.0.1"
81
+ b.host = "127.0.0.2"
82
+
83
+ # Note autospec does not work for staticmethods in python < 3.12
84
+ # https://github.com/python/cpython/issues/102978
85
+ mocker.patch(
86
+ "kasa.discover.Discover.discover_single", return_value=a, autospec=True
87
+ )
88
+ mocker.patch.object(Discover, "discover", return_value=[a, b], autospec=True)
89
+ res = xdoctest.doctest_module("docs/tutorial.py", "all")
90
+ assert not res["failed"]
91
+
92
+
93
+ @pytest.fixture
94
+ def top_level_await(mocker):
95
+ """Fixture to enable top level awaits in doctests.
96
+
97
+ Uses the async exec feature of python to patch the builtins xdoctest uses.
98
+ See https://github.com/python/cpython/issues/78797
99
+ """
100
+ import ast
101
+ from inspect import CO_COROUTINE
102
+
103
+ orig_exec = exec
104
+ orig_eval = eval
105
+ orig_compile = compile
106
+
107
+ def patch_exec(source, globals=None, locals=None, /, **kwargs):
108
+ if source.co_flags & CO_COROUTINE == CO_COROUTINE:
109
+ asyncio.run(orig_eval(source, globals, locals))
110
+ else:
111
+ orig_exec(source, globals, locals, **kwargs)
112
+
113
+ def patch_eval(source, globals=None, locals=None, /, **kwargs):
114
+ if source.co_flags & CO_COROUTINE == CO_COROUTINE:
115
+ return asyncio.run(orig_eval(source, globals, locals, **kwargs))
116
+ else:
117
+ return orig_eval(source, globals, locals, **kwargs)
118
+
119
+ def patch_compile(
120
+ source, filename, mode, flags=0, dont_inherit=False, optimize=-1, **kwargs
121
+ ):
122
+ flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
123
+ return orig_compile(
124
+ source, filename, mode, flags, dont_inherit, optimize, **kwargs
125
+ )
126
+
127
+ mocker.patch("builtins.eval", side_effect=patch_eval)
128
+ mocker.patch("builtins.exec", side_effect=patch_exec)
129
+ mocker.patch("builtins.compile", side_effect=patch_compile)