python-kasa 0.6.2.1__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 (164) 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 +7 -5
  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 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  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/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +33 -24
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -12,11 +12,11 @@ from ..aestransport import AesTransport
12
12
  from ..credentials import Credentials
13
13
  from ..deviceconfig import DeviceConfig
14
14
  from ..exceptions import (
15
- AuthenticationException,
16
- ConnectionException,
17
- RetryableException,
18
- SmartDeviceException,
19
- TimeoutException,
15
+ AuthenticationError,
16
+ KasaException,
17
+ TimeoutError,
18
+ _ConnectionError,
19
+ _RetryableError,
20
20
  )
21
21
  from ..httpclient import HttpClient
22
22
  from ..iotprotocol import IotProtocol
@@ -68,7 +68,7 @@ async def test_protocol_retries_via_client_session(
68
68
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
69
69
 
70
70
  config = DeviceConfig(host)
71
- with pytest.raises(SmartDeviceException):
71
+ with pytest.raises(KasaException):
72
72
  await protocol_class(transport=transport_class(config=config)).query(
73
73
  DUMMY_QUERY, retry_count=retry_count
74
74
  )
@@ -80,11 +80,11 @@ async def test_protocol_retries_via_client_session(
80
80
  @pytest.mark.parametrize(
81
81
  "error, retry_expectation",
82
82
  [
83
- (SmartDeviceException("dummy exception"), False),
84
- (RetryableException("dummy exception"), True),
85
- (TimeoutException("dummy exception"), True),
83
+ (KasaException("dummy exception"), False),
84
+ (_RetryableError("dummy exception"), True),
85
+ (TimeoutError("dummy exception"), True),
86
86
  ],
87
- ids=("SmartDeviceException", "RetryableException", "TimeoutException"),
87
+ ids=("KasaException", "_RetryableError", "TimeoutError"),
88
88
  )
89
89
  @pytest.mark.parametrize("transport_class", [AesTransport, KlapTransport])
90
90
  @pytest.mark.parametrize("protocol_class", [IotProtocol, SmartProtocol])
@@ -97,7 +97,7 @@ async def test_protocol_retries_via_httpclient(
97
97
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
98
98
 
99
99
  config = DeviceConfig(host)
100
- with pytest.raises(SmartDeviceException):
100
+ with pytest.raises(KasaException):
101
101
  await protocol_class(transport=transport_class(config=config)).query(
102
102
  DUMMY_QUERY, retry_count=retry_count
103
103
  )
@@ -115,11 +115,11 @@ async def test_protocol_no_retry_on_connection_error(
115
115
  conn = mocker.patch.object(
116
116
  aiohttp.ClientSession,
117
117
  "post",
118
- side_effect=AuthenticationException("foo"),
118
+ side_effect=AuthenticationError("foo"),
119
119
  )
120
120
  mocker.patch.object(protocol_class, "BACKOFF_SECONDS_AFTER_TIMEOUT", 0)
121
121
  config = DeviceConfig(host)
122
- with pytest.raises(SmartDeviceException):
122
+ with pytest.raises(KasaException):
123
123
  await protocol_class(transport=transport_class(config=config)).query(
124
124
  DUMMY_QUERY, retry_count=5
125
125
  )
@@ -139,7 +139,7 @@ async def test_protocol_retry_recoverable_error(
139
139
  side_effect=aiohttp.ClientOSError("foo"),
140
140
  )
141
141
  config = DeviceConfig(host)
142
- with pytest.raises(SmartDeviceException):
142
+ with pytest.raises(KasaException):
143
143
  await protocol_class(transport=transport_class(config=config)).query(
144
144
  DUMMY_QUERY, retry_count=5
145
145
  )
@@ -159,7 +159,7 @@ async def test_protocol_reconnect(mocker, retry_count, protocol_class, transport
159
159
  nonlocal remaining
160
160
  remaining -= 1
161
161
  if remaining:
162
- raise ConnectionException("Simulated connection failure")
162
+ raise _ConnectionError("Simulated connection failure")
163
163
 
164
164
  return mock_response
165
165
 
@@ -249,7 +249,7 @@ def test_encrypt_unicode():
249
249
  ),
250
250
  (
251
251
  Credentials("shouldfail", "shouldfail"),
252
- pytest.raises(AuthenticationException),
252
+ pytest.raises(AuthenticationError),
253
253
  ),
254
254
  ],
255
255
  ids=("client", "blank", "kasa_setup", "shouldfail"),
@@ -323,14 +323,14 @@ async def test_handshake(
323
323
  async def _return_handshake_response(url: URL, params=None, data=None, *_, **__):
324
324
  nonlocal client_seed, server_seed, device_auth_hash
325
325
 
326
- if str(url) == "http://127.0.0.1/app/handshake1":
326
+ if str(url) == "http://127.0.0.1:80/app/handshake1":
327
327
  client_seed = data
328
328
  seed_auth_hash = _sha256(
329
329
  seed_auth_hash_calc1(client_seed, server_seed, device_auth_hash)
330
330
  )
331
331
 
332
332
  return _mock_response(200, server_seed + seed_auth_hash)
333
- elif str(url) == "http://127.0.0.1/app/handshake2":
333
+ elif str(url) == "http://127.0.0.1:80/app/handshake2":
334
334
  seed_auth_hash = _sha256(
335
335
  seed_auth_hash_calc2(client_seed, server_seed, device_auth_hash)
336
336
  )
@@ -350,7 +350,7 @@ async def test_handshake(
350
350
  assert protocol._transport._handshake_done is True
351
351
 
352
352
  response_status = 403
353
- with pytest.raises(AuthenticationException):
353
+ with pytest.raises(KasaException):
354
354
  await protocol._transport.perform_handshake()
355
355
  assert protocol._transport._handshake_done is False
356
356
  await protocol.close()
@@ -367,14 +367,14 @@ async def test_query(mocker):
367
367
  async def _return_response(url: URL, params=None, data=None, *_, **__):
368
368
  nonlocal client_seed, server_seed, device_auth_hash, seq
369
369
 
370
- if str(url) == "http://127.0.0.1/app/handshake1":
370
+ if str(url) == "http://127.0.0.1:80/app/handshake1":
371
371
  client_seed = data
372
372
  client_seed_auth_hash = _sha256(data + device_auth_hash)
373
373
 
374
374
  return _mock_response(200, server_seed + client_seed_auth_hash)
375
- elif str(url) == "http://127.0.0.1/app/handshake2":
375
+ elif str(url) == "http://127.0.0.1:80/app/handshake2":
376
376
  return _mock_response(200, b"")
377
- elif str(url) == "http://127.0.0.1/app/request":
377
+ elif str(url) == "http://127.0.0.1:80/app/request":
378
378
  encryption_session = KlapEncryptionSession(
379
379
  protocol._transport._encryption_session.local_seed,
380
380
  protocol._transport._encryption_session.remote_seed,
@@ -400,35 +400,81 @@ async def test_query(mocker):
400
400
 
401
401
 
402
402
  @pytest.mark.parametrize(
403
- "response_status, expectation",
403
+ "response_status, credentials_match, expectation",
404
404
  [
405
- ((403, 403, 403), pytest.raises(AuthenticationException)),
406
- ((200, 403, 403), pytest.raises(AuthenticationException)),
407
- ((200, 200, 403), pytest.raises(AuthenticationException)),
408
- ((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
+ ),
409
441
  ],
410
- ids=("handshake1", "handshake2", "request", "non_auth_error"),
411
442
  )
412
- async def test_authentication_failures(mocker, response_status, expectation):
443
+ async def test_authentication_failures(
444
+ mocker, response_status, credentials_match, expectation
445
+ ):
413
446
  client_seed = None
414
447
 
415
448
  server_seed = secrets.token_bytes(16)
416
449
  client_credentials = Credentials("foo", "bar")
417
- 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)
418
454
 
419
455
  async def _return_response(url: URL, params=None, data=None, *_, **__):
420
- nonlocal client_seed, server_seed, device_auth_hash, response_status
421
-
422
- 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":
423
464
  client_seed = data
424
465
  client_seed_auth_hash = _sha256(data + device_auth_hash)
425
-
466
+ if credentials_match is not False and credentials_match is not True:
467
+ client_seed_auth_hash += credentials_match
426
468
  return _mock_response(
427
469
  response_status[0], server_seed + client_seed_auth_hash
428
470
  )
429
- elif str(url) == "http://127.0.0.1/app/handshake2":
430
- return _mock_response(response_status[1], b"")
431
- 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":
432
478
  return _mock_response(response_status[2], b"")
433
479
 
434
480
  mocker.patch.object(aiohttp.ClientSession, "post", side_effect=_return_response)
@@ -438,3 +484,14 @@ async def test_authentication_failures(mocker, response_status, expectation):
438
484
 
439
485
  with expectation:
440
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,14 +1,14 @@
1
1
  from kasa import DeviceType
2
2
 
3
- from .conftest import plug, plug_smart
4
- from .test_smartdevice import SYSINFO_SCHEMA
3
+ from .conftest import plug, plug_iot, plug_smart, switch_smart, wallswitch_iot
4
+ from .test_iotdevice import SYSINFO_SCHEMA
5
5
 
6
6
  # these schemas should go to the mainlib as
7
7
  # they can be useful when adding support for new features/devices
8
8
  # as well as to check that faked devices are operating properly.
9
9
 
10
10
 
11
- @plug
11
+ @plug_iot
12
12
  async def test_plug_sysinfo(dev):
13
13
  assert dev.sys_info is not None
14
14
  SYSINFO_SCHEMA(dev.sys_info)
@@ -19,8 +19,34 @@ async def test_plug_sysinfo(dev):
19
19
  assert dev.is_plug or dev.is_strip
20
20
 
21
21
 
22
- @plug
23
- 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):
24
50
  original = dev.led
25
51
 
26
52
  await dev.set_led(False)
@@ -37,9 +63,21 @@ async def test_led(dev):
37
63
  @plug_smart
38
64
  async def test_plug_device_info(dev):
39
65
  assert dev._info is not None
40
- # PLUG_SCHEMA(dev.sys_info)
41
-
42
66
  assert dev.model is not None
43
67
 
44
68
  assert dev.device_type == DeviceType.Plug or dev.device_type == DeviceType.Strip
45
- # 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
  )
@@ -553,7 +553,7 @@ async def test_protocol_will_retry_on_connect(
553
553
  retry_count = 2
554
554
  conn = mocker.patch("asyncio.open_connection", side_effect=error)
555
555
  config = DeviceConfig("127.0.0.1")
556
- with pytest.raises(SmartDeviceException):
556
+ with pytest.raises(KasaException):
557
557
  await protocol_class(transport=transport_class(config=config)).query(
558
558
  {}, retry_count=retry_count
559
559
  )
@@ -595,7 +595,7 @@ async def test_protocol_will_retry_on_write(
595
595
  conn = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
596
596
  write_mock = mocker.patch("asyncio.StreamWriter.write", side_effect=error)
597
597
  config = DeviceConfig("127.0.0.1")
598
- with pytest.raises(SmartDeviceException):
598
+ with pytest.raises(KasaException):
599
599
  await protocol_class(transport=transport_class(config=config)).query(
600
600
  {}, retry_count=retry_count
601
601
  )
@@ -609,9 +609,7 @@ def test_deprecated_protocol():
609
609
  with pytest.deprecated_call():
610
610
  from kasa import TPLinkSmartHomeProtocol
611
611
 
612
- with pytest.raises(
613
- SmartDeviceException, match="host or transport must be supplied"
614
- ):
612
+ with pytest.raises(KasaException, match="host or transport must be supplied"):
615
613
  proto = TPLinkSmartHomeProtocol()
616
614
  host = "127.0.0.1"
617
615
  proto = TPLinkSmartHomeProtocol(host=host)
@@ -1,68 +1,129 @@
1
1
  import asyncio
2
2
 
3
+ import pytest
3
4
  import xdoctest
4
5
 
5
- 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
6
8
 
7
9
 
8
10
  def test_bulb_examples(mocker):
9
11
  """Use KL130 (bulb with all features) to test the doctests."""
10
- p = asyncio.run(get_device_for_file("KL130(US)_1.0_1.8.11.json", "IOT"))
11
- mocker.patch("kasa.smartbulb.SmartBulb", return_value=p)
12
- mocker.patch("kasa.smartbulb.SmartBulb.update")
13
- 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")
14
16
  assert not res["failed"]
15
17
 
16
18
 
17
19
  def test_smartdevice_examples(mocker):
18
20
  """Use HS110 for emeter examples."""
19
- p = asyncio.run(get_device_for_file("HS110(EU)_1.0_1.2.5.json", "IOT"))
20
- mocker.patch("kasa.smartdevice.SmartDevice", return_value=p)
21
- mocker.patch("kasa.smartdevice.SmartDevice.update")
22
- 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")
23
25
  assert not res["failed"]
24
26
 
25
27
 
26
28
  def test_plug_examples(mocker):
27
29
  """Test plug examples."""
28
- p = asyncio.run(get_device_for_file("HS110(EU)_1.0_1.2.5.json", "IOT"))
29
- mocker.patch("kasa.smartplug.SmartPlug", return_value=p)
30
- mocker.patch("kasa.smartplug.SmartPlug.update")
31
- 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")
32
35
  assert not res["failed"]
33
36
 
34
37
 
35
38
  def test_strip_examples(mocker):
36
39
  """Test strip examples."""
37
- p = asyncio.run(get_device_for_file("KP303(UK)_1.0_1.0.3.json", "IOT"))
38
- mocker.patch("kasa.smartstrip.SmartStrip", return_value=p)
39
- mocker.patch("kasa.smartstrip.SmartStrip.update")
40
- 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")
41
44
  assert not res["failed"]
42
45
 
43
46
 
44
47
  def test_dimmer_examples(mocker):
45
48
  """Test dimmer examples."""
46
- p = asyncio.run(get_device_for_file("HS220(US)_1.0_1.5.7.json", "IOT"))
47
- mocker.patch("kasa.smartdimmer.SmartDimmer", return_value=p)
48
- mocker.patch("kasa.smartdimmer.SmartDimmer.update")
49
- 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")
50
53
  assert not res["failed"]
51
54
 
52
55
 
53
56
  def test_lightstrip_examples(mocker):
54
57
  """Test lightstrip examples."""
55
- p = asyncio.run(get_device_for_file("KL430(US)_1.0_1.0.10.json", "IOT"))
56
- mocker.patch("kasa.smartlightstrip.SmartLightStrip", return_value=p)
57
- mocker.patch("kasa.smartlightstrip.SmartLightStrip.update")
58
- 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")
59
62
  assert not res["failed"]
60
63
 
61
64
 
62
65
  def test_discovery_examples(mocker):
63
66
  """Test discovery examples."""
64
- 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"))
65
68
 
66
69
  mocker.patch("kasa.discover.Discover.discover", return_value=[p])
67
70
  res = xdoctest.doctest_module("kasa.discover", "all")
68
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)