2024-01-13 17:37:24 +00:00
|
|
|
import asyncio
|
2022-04-24 17:38:42 +00:00
|
|
|
import errno
|
2023-12-19 14:11:59 +00:00
|
|
|
import importlib
|
|
|
|
import inspect
|
2019-11-11 19:31:56 +00:00
|
|
|
import json
|
2021-09-26 14:50:58 +00:00
|
|
|
import logging
|
2024-01-25 17:37:19 +00:00
|
|
|
import os
|
2023-12-19 14:11:59 +00:00
|
|
|
import pkgutil
|
2021-09-24 21:25:43 +00:00
|
|
|
import struct
|
|
|
|
import sys
|
2024-07-17 17:57:09 +00:00
|
|
|
from typing import cast
|
2019-11-11 19:31:56 +00:00
|
|
|
|
2020-05-27 17:02:09 +00:00
|
|
|
import pytest
|
|
|
|
|
2024-07-17 17:57:09 +00:00
|
|
|
from kasa.iot import IotDevice
|
|
|
|
|
2024-01-03 21:46:08 +00:00
|
|
|
from ..aestransport import AesTransport
|
|
|
|
from ..credentials import Credentials
|
2024-07-02 12:43:37 +00:00
|
|
|
from ..device import Device
|
2023-12-29 19:17:15 +00:00
|
|
|
from ..deviceconfig import DeviceConfig
|
2024-02-21 15:52:55 +00:00
|
|
|
from ..exceptions import KasaException
|
2024-01-26 09:11:31 +00:00
|
|
|
from ..iotprotocol import IotProtocol, _deprecated_TPLinkSmartHomeProtocol
|
2024-01-03 21:46:08 +00:00
|
|
|
from ..klaptransport import KlapTransport, KlapTransportV2
|
2023-12-19 14:11:59 +00:00
|
|
|
from ..protocol import (
|
2024-01-22 15:28:30 +00:00
|
|
|
BaseProtocol,
|
2023-12-19 14:11:59 +00:00
|
|
|
BaseTransport,
|
2024-07-17 17:57:09 +00:00
|
|
|
mask_mac,
|
|
|
|
redact_data,
|
2023-12-19 14:11:59 +00:00
|
|
|
)
|
2024-01-25 17:37:19 +00:00
|
|
|
from ..xortransport import XorEncryption, XorTransport
|
2024-07-17 17:57:09 +00:00
|
|
|
from .conftest import device_iot
|
|
|
|
from .fakeprotocol_iot import FakeIotTransport
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
2020-05-27 17:02:09 +00:00
|
|
|
@pytest.mark.parametrize("retry_count", [1, 3, 5])
|
2024-01-25 17:37:19 +00:00
|
|
|
async def test_protocol_retries(mocker, retry_count, protocol_class, transport_class):
|
2020-05-27 17:02:09 +00:00
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
2018-08-08 14:52:03 +00:00
|
|
|
|
2020-05-27 17:02:09 +00:00
|
|
|
mocker.patch(
|
|
|
|
"asyncio.StreamWriter.write", side_effect=Exception("dummy exception")
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
)
|
2018-08-08 14:52:03 +00:00
|
|
|
|
2020-05-27 17:02:09 +00:00
|
|
|
return reader, writer
|
|
|
|
|
|
|
|
conn = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-29 19:17:15 +00:00
|
|
|
{}, retry_count=retry_count
|
|
|
|
)
|
2020-05-27 17:02:09 +00:00
|
|
|
|
|
|
|
assert conn.call_count == retry_count + 1
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_no_retry_on_unreachable(
|
|
|
|
mocker, protocol_class, transport_class
|
|
|
|
):
|
2022-04-24 17:38:42 +00:00
|
|
|
conn = mocker.patch(
|
|
|
|
"asyncio.open_connection",
|
|
|
|
side_effect=OSError(errno.EHOSTUNREACH, "No route to host"),
|
|
|
|
)
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-29 19:17:15 +00:00
|
|
|
{}, retry_count=5
|
|
|
|
)
|
2022-04-24 17:38:42 +00:00
|
|
|
|
|
|
|
assert conn.call_count == 1
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_no_retry_connection_refused(
|
|
|
|
mocker, protocol_class, transport_class
|
|
|
|
):
|
2022-04-24 17:38:42 +00:00
|
|
|
conn = mocker.patch(
|
|
|
|
"asyncio.open_connection",
|
|
|
|
side_effect=ConnectionRefusedError,
|
|
|
|
)
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-29 19:17:15 +00:00
|
|
|
{}, retry_count=5
|
|
|
|
)
|
2022-04-24 17:38:42 +00:00
|
|
|
|
|
|
|
assert conn.call_count == 1
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_retry_recoverable_error(
|
|
|
|
mocker, protocol_class, transport_class
|
|
|
|
):
|
2022-04-24 17:38:42 +00:00
|
|
|
conn = mocker.patch(
|
|
|
|
"asyncio.open_connection",
|
|
|
|
side_effect=OSError(errno.ECONNRESET, "Connection reset by peer"),
|
|
|
|
)
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
2023-12-29 19:17:15 +00:00
|
|
|
{}, retry_count=5
|
|
|
|
)
|
2022-04-24 17:38:42 +00:00
|
|
|
|
|
|
|
assert conn.call_count == 6
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class", "encryption_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
XorTransport,
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport, XorEncryption),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
2021-09-24 21:25:43 +00:00
|
|
|
@pytest.mark.parametrize("retry_count", [1, 3, 5])
|
2024-01-25 17:37:19 +00:00
|
|
|
async def test_protocol_reconnect(
|
|
|
|
mocker, retry_count, protocol_class, transport_class, encryption_class
|
|
|
|
):
|
2021-09-24 21:25:43 +00:00
|
|
|
remaining = retry_count
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encryption_class.encrypt('{"great":"success"}')[
|
|
|
|
transport_class.BLOCK_SIZE :
|
2021-09-24 21:25:43 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
def _fail_one_less_than_retry_count(*_):
|
|
|
|
nonlocal remaining
|
|
|
|
remaining -= 1
|
|
|
|
if remaining:
|
|
|
|
raise Exception("Simulated write failure")
|
|
|
|
|
|
|
|
async def _mock_read(byte_count):
|
|
|
|
nonlocal encrypted
|
2024-01-25 17:37:19 +00:00
|
|
|
if byte_count == transport_class.BLOCK_SIZE:
|
2021-09-24 21:25:43 +00:00
|
|
|
return struct.pack(">I", len(encrypted))
|
|
|
|
if byte_count == len(encrypted):
|
|
|
|
return encrypted
|
|
|
|
|
|
|
|
raise ValueError(f"No mock for {byte_count}")
|
|
|
|
|
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
mocker.patch.object(writer, "write", _fail_one_less_than_retry_count)
|
|
|
|
mocker.patch.object(reader, "readexactly", _mock_read)
|
|
|
|
return reader, writer
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-01-25 17:37:19 +00:00
|
|
|
protocol = protocol_class(transport=transport_class(config=config))
|
2021-09-24 21:25:43 +00:00
|
|
|
mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
|
|
|
response = await protocol.query({}, retry_count=retry_count)
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class", "encryption_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
XorTransport,
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport, XorEncryption),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_handles_cancellation_during_write(
|
|
|
|
mocker, protocol_class, transport_class, encryption_class
|
|
|
|
):
|
2024-01-13 17:37:24 +00:00
|
|
|
attempts = 0
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encryption_class.encrypt('{"great":"success"}')[
|
|
|
|
transport_class.BLOCK_SIZE :
|
2024-01-13 17:37:24 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
def _cancel_first_attempt(*_):
|
|
|
|
nonlocal attempts
|
|
|
|
attempts += 1
|
|
|
|
if attempts == 1:
|
|
|
|
raise asyncio.CancelledError("Simulated task cancel")
|
|
|
|
|
|
|
|
async def _mock_read(byte_count):
|
|
|
|
nonlocal encrypted
|
2024-01-25 17:37:19 +00:00
|
|
|
if byte_count == transport_class.BLOCK_SIZE:
|
2024-01-13 17:37:24 +00:00
|
|
|
return struct.pack(">I", len(encrypted))
|
|
|
|
if byte_count == len(encrypted):
|
|
|
|
return encrypted
|
|
|
|
|
|
|
|
raise ValueError(f"No mock for {byte_count}")
|
|
|
|
|
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
mocker.patch.object(writer, "write", _cancel_first_attempt)
|
|
|
|
mocker.patch.object(reader, "readexactly", _mock_read)
|
|
|
|
return reader, writer
|
|
|
|
|
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-01-25 17:37:19 +00:00
|
|
|
protocol = protocol_class(transport=transport_class(config=config))
|
|
|
|
conn_mock = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
2024-01-13 17:37:24 +00:00
|
|
|
with pytest.raises(asyncio.CancelledError):
|
|
|
|
await protocol.query({})
|
2024-01-25 17:37:19 +00:00
|
|
|
writer_obj = protocol if hasattr(protocol, "writer") else protocol._transport
|
|
|
|
assert writer_obj.writer is None
|
|
|
|
conn_mock.assert_awaited_once()
|
2024-01-13 17:37:24 +00:00
|
|
|
response = await protocol.query({})
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class", "encryption_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
XorTransport,
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport, XorEncryption),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_handles_cancellation_during_connection(
|
|
|
|
mocker, protocol_class, transport_class, encryption_class
|
|
|
|
):
|
2024-01-13 17:37:24 +00:00
|
|
|
attempts = 0
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encryption_class.encrypt('{"great":"success"}')[
|
|
|
|
transport_class.BLOCK_SIZE :
|
2024-01-13 17:37:24 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
async def _mock_read(byte_count):
|
|
|
|
nonlocal encrypted
|
2024-01-25 17:37:19 +00:00
|
|
|
if byte_count == transport_class.BLOCK_SIZE:
|
2024-01-13 17:37:24 +00:00
|
|
|
return struct.pack(">I", len(encrypted))
|
|
|
|
if byte_count == len(encrypted):
|
|
|
|
return encrypted
|
|
|
|
|
|
|
|
raise ValueError(f"No mock for {byte_count}")
|
|
|
|
|
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
nonlocal attempts
|
|
|
|
attempts += 1
|
|
|
|
if attempts == 1:
|
|
|
|
raise asyncio.CancelledError("Simulated task cancel")
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
mocker.patch.object(reader, "readexactly", _mock_read)
|
|
|
|
return reader, writer
|
|
|
|
|
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-01-25 17:37:19 +00:00
|
|
|
protocol = protocol_class(transport=transport_class(config=config))
|
|
|
|
conn_mock = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
2024-01-13 17:37:24 +00:00
|
|
|
with pytest.raises(asyncio.CancelledError):
|
|
|
|
await protocol.query({})
|
2024-01-25 17:37:19 +00:00
|
|
|
|
|
|
|
writer_obj = protocol if hasattr(protocol, "writer") else protocol._transport
|
|
|
|
assert writer_obj.writer is None
|
|
|
|
conn_mock.assert_awaited_once()
|
2024-01-13 17:37:24 +00:00
|
|
|
response = await protocol.query({})
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class", "encryption_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
XorTransport,
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport, XorEncryption),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
2021-09-26 14:50:58 +00:00
|
|
|
@pytest.mark.parametrize("log_level", [logging.WARNING, logging.DEBUG])
|
2024-01-25 17:37:19 +00:00
|
|
|
async def test_protocol_logging(
|
|
|
|
mocker, caplog, log_level, protocol_class, transport_class, encryption_class
|
|
|
|
):
|
2021-09-26 14:50:58 +00:00
|
|
|
caplog.set_level(log_level)
|
|
|
|
logging.getLogger("kasa").setLevel(log_level)
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encryption_class.encrypt('{"great":"success"}')[
|
|
|
|
transport_class.BLOCK_SIZE :
|
2021-09-26 14:50:58 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
async def _mock_read(byte_count):
|
|
|
|
nonlocal encrypted
|
2024-01-25 17:37:19 +00:00
|
|
|
if byte_count == transport_class.BLOCK_SIZE:
|
2021-09-26 14:50:58 +00:00
|
|
|
return struct.pack(">I", len(encrypted))
|
|
|
|
if byte_count == len(encrypted):
|
|
|
|
return encrypted
|
|
|
|
raise ValueError(f"No mock for {byte_count}")
|
|
|
|
|
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
mocker.patch.object(reader, "readexactly", _mock_read)
|
|
|
|
return reader, writer
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-01-25 17:37:19 +00:00
|
|
|
protocol = protocol_class(transport=transport_class(config=config))
|
2021-09-26 14:50:58 +00:00
|
|
|
mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
|
|
|
response = await protocol.query({})
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
if log_level == logging.DEBUG:
|
|
|
|
assert "success" in caplog.text
|
|
|
|
else:
|
|
|
|
assert "success" not in caplog.text
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class", "encryption_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
XorTransport,
|
|
|
|
_deprecated_TPLinkSmartHomeProtocol,
|
|
|
|
),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport, XorEncryption),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
2023-07-09 23:55:27 +00:00
|
|
|
@pytest.mark.parametrize("custom_port", [123, None])
|
2024-01-25 17:37:19 +00:00
|
|
|
async def test_protocol_custom_port(
|
|
|
|
mocker, custom_port, protocol_class, transport_class, encryption_class
|
|
|
|
):
|
|
|
|
encrypted = encryption_class.encrypt('{"great":"success"}')[
|
|
|
|
transport_class.BLOCK_SIZE :
|
2023-07-09 23:55:27 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
async def _mock_read(byte_count):
|
|
|
|
nonlocal encrypted
|
2024-01-25 17:37:19 +00:00
|
|
|
if byte_count == transport_class.BLOCK_SIZE:
|
2023-07-09 23:55:27 +00:00
|
|
|
return struct.pack(">I", len(encrypted))
|
|
|
|
if byte_count == len(encrypted):
|
|
|
|
return encrypted
|
|
|
|
raise ValueError(f"No mock for {byte_count}")
|
|
|
|
|
|
|
|
def aio_mock_writer(_, port):
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
if custom_port is None:
|
|
|
|
assert port == 9999
|
|
|
|
else:
|
|
|
|
assert port == custom_port
|
|
|
|
mocker.patch.object(reader, "readexactly", _mock_read)
|
|
|
|
return reader, writer
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
config = DeviceConfig("127.0.0.1", port_override=custom_port)
|
2024-01-25 17:37:19 +00:00
|
|
|
protocol = protocol_class(transport=transport_class(config=config))
|
2023-07-09 23:55:27 +00:00
|
|
|
mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
|
|
|
response = await protocol.query({})
|
|
|
|
assert response == {"great": "success"}
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"encrypt_class",
|
2024-01-26 09:11:31 +00:00
|
|
|
[_deprecated_TPLinkSmartHomeProtocol, XorEncryption],
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"decrypt_class",
|
2024-01-26 09:11:31 +00:00
|
|
|
[_deprecated_TPLinkSmartHomeProtocol, XorEncryption],
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
def test_encrypt(encrypt_class, decrypt_class):
|
2020-05-27 17:02:09 +00:00
|
|
|
d = json.dumps({"foo": 1, "bar": 2})
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encrypt_class.encrypt(d)
|
2020-05-27 17:02:09 +00:00
|
|
|
# encrypt adds a 4 byte header
|
|
|
|
encrypted = encrypted[4:]
|
2024-01-25 17:37:19 +00:00
|
|
|
assert d == decrypt_class.decrypt(encrypted)
|
2020-05-27 17:02:09 +00:00
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"encrypt_class",
|
2024-01-26 09:11:31 +00:00
|
|
|
[_deprecated_TPLinkSmartHomeProtocol, XorEncryption],
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
def test_encrypt_unicode(encrypt_class):
|
2020-05-27 17:02:09 +00:00
|
|
|
d = "{'snowman': '\u2603'}"
|
|
|
|
|
|
|
|
e = bytes(
|
|
|
|
[
|
|
|
|
208,
|
|
|
|
247,
|
|
|
|
132,
|
|
|
|
234,
|
|
|
|
133,
|
|
|
|
242,
|
|
|
|
159,
|
|
|
|
254,
|
|
|
|
144,
|
|
|
|
183,
|
|
|
|
141,
|
|
|
|
173,
|
|
|
|
138,
|
|
|
|
104,
|
|
|
|
240,
|
|
|
|
115,
|
|
|
|
84,
|
|
|
|
41,
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
encrypted = encrypt_class.encrypt(d)
|
2020-05-27 17:02:09 +00:00
|
|
|
# encrypt adds a 4 byte header
|
|
|
|
encrypted = encrypted[4:]
|
|
|
|
|
|
|
|
assert e == encrypted
|
|
|
|
|
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"decrypt_class",
|
2024-01-26 09:11:31 +00:00
|
|
|
[_deprecated_TPLinkSmartHomeProtocol, XorEncryption],
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
def test_decrypt_unicode(decrypt_class):
|
2020-05-27 17:02:09 +00:00
|
|
|
e = bytes(
|
|
|
|
[
|
|
|
|
208,
|
|
|
|
247,
|
|
|
|
132,
|
|
|
|
234,
|
|
|
|
133,
|
|
|
|
242,
|
|
|
|
159,
|
|
|
|
254,
|
|
|
|
144,
|
|
|
|
183,
|
|
|
|
141,
|
|
|
|
173,
|
|
|
|
138,
|
|
|
|
104,
|
|
|
|
240,
|
|
|
|
115,
|
|
|
|
84,
|
|
|
|
41,
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
|
|
|
d = "{'snowman': '\u2603'}"
|
2018-08-08 14:52:03 +00:00
|
|
|
|
2024-01-25 17:37:19 +00:00
|
|
|
assert d == decrypt_class.decrypt(e)
|
2023-12-19 14:11:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _get_subclasses(of_class):
|
|
|
|
package = sys.modules["kasa"]
|
|
|
|
subclasses = set()
|
|
|
|
for _, modname, _ in pkgutil.iter_modules(package.__path__):
|
|
|
|
importlib.import_module("." + modname, package="kasa")
|
|
|
|
module = sys.modules["kasa." + modname]
|
|
|
|
for name, obj in inspect.getmembers(module):
|
2024-01-26 09:11:31 +00:00
|
|
|
if (
|
|
|
|
inspect.isclass(obj)
|
|
|
|
and issubclass(obj, of_class)
|
|
|
|
and name != "_deprecated_TPLinkSmartHomeProtocol"
|
|
|
|
):
|
2023-12-19 14:11:59 +00:00
|
|
|
subclasses.add((name, obj))
|
2024-09-27 09:27:53 +00:00
|
|
|
return sorted(subclasses)
|
2023-12-19 14:11:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2024-01-22 15:28:30 +00:00
|
|
|
"class_name_obj", _get_subclasses(BaseProtocol), ids=lambda t: t[0]
|
2023-12-19 14:11:59 +00:00
|
|
|
)
|
|
|
|
def test_protocol_init_signature(class_name_obj):
|
2024-01-29 16:11:29 +00:00
|
|
|
if class_name_obj[0].startswith("_"):
|
|
|
|
pytest.skip("Skipping internal protocols")
|
|
|
|
return
|
2023-12-19 14:11:59 +00:00
|
|
|
params = list(inspect.signature(class_name_obj[1].__init__).parameters.values())
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
assert len(params) == 2
|
2024-08-30 15:30:07 +00:00
|
|
|
assert params[0].name == "self"
|
|
|
|
assert params[0].kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
|
|
|
|
assert params[1].name == "transport"
|
|
|
|
assert params[1].kind == inspect.Parameter.KEYWORD_ONLY
|
2023-12-19 14:11:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"class_name_obj", _get_subclasses(BaseTransport), ids=lambda t: t[0]
|
|
|
|
)
|
|
|
|
def test_transport_init_signature(class_name_obj):
|
|
|
|
params = list(inspect.signature(class_name_obj[1].__init__).parameters.values())
|
|
|
|
|
2023-12-29 19:17:15 +00:00
|
|
|
assert len(params) == 2
|
2024-08-30 15:30:07 +00:00
|
|
|
assert params[0].name == "self"
|
|
|
|
assert params[0].kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
|
|
|
|
assert params[1].name == "config"
|
|
|
|
assert params[1].kind == inspect.Parameter.KEYWORD_ONLY
|
2024-01-03 21:46:08 +00:00
|
|
|
|
|
|
|
|
2024-07-02 12:43:37 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("transport_class", "login_version", "expected_hash"),
|
|
|
|
[
|
|
|
|
pytest.param(
|
|
|
|
AesTransport,
|
|
|
|
1,
|
|
|
|
"eyJwYXNzd29yZCI6IlFtRnkiLCJ1c2VybmFtZSI6Ik1qQXhZVFppTXpBMU0yTmpNVFF5TW1ReVl6TTJOekJpTmpJMk1UWXlNakZrTWpJNU1Ea3lPUT09In0=",
|
|
|
|
id="aes-lv-1",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
AesTransport,
|
|
|
|
2,
|
|
|
|
"eyJwYXNzd29yZDIiOiJaVFE1Tm1aa01qQXhNelprTkdKaU56Z3lPR1ZpWWpCaFlqa3lOV0l4WW1RNU56Y3lNRGhsTkE9PSIsInVzZXJuYW1lIjoiTWpBeFlUWmlNekExTTJOak1UUXlNbVF5WXpNMk56QmlOakkyTVRZeU1qRmtNakk1TURreU9RPT0ifQ==",
|
|
|
|
id="aes-lv-2",
|
|
|
|
),
|
|
|
|
pytest.param(KlapTransport, 1, "xBhMRGYWStVCVk9aSD8/6Q==", id="klap-lv-1"),
|
|
|
|
pytest.param(KlapTransport, 2, "xBhMRGYWStVCVk9aSD8/6Q==", id="klap-lv-2"),
|
|
|
|
pytest.param(
|
|
|
|
KlapTransportV2,
|
|
|
|
1,
|
|
|
|
"tEmiensOcZkP9twDEZKwU3JJl3asmseKCP7N9sfatVo=",
|
|
|
|
id="klapv2-lv-1",
|
|
|
|
),
|
|
|
|
pytest.param(
|
|
|
|
KlapTransportV2,
|
|
|
|
2,
|
|
|
|
"tEmiensOcZkP9twDEZKwU3JJl3asmseKCP7N9sfatVo=",
|
|
|
|
id="klapv2-lv-2",
|
|
|
|
),
|
|
|
|
pytest.param(XorTransport, None, None, id="xor"),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("credentials", "expected_blank"),
|
|
|
|
[
|
|
|
|
pytest.param(Credentials("Foo", "Bar"), False, id="credentials"),
|
|
|
|
pytest.param(None, True, id="no-credentials"),
|
|
|
|
pytest.param(Credentials(None, "Bar"), True, id="no-username"), # type: ignore[arg-type]
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_transport_credentials_hash(
|
|
|
|
mocker, transport_class, login_version, expected_hash, credentials, expected_blank
|
|
|
|
):
|
|
|
|
"""Test that the actual hashing doesn't break and empty credential returns an empty hash."""
|
|
|
|
host = "127.0.0.1"
|
|
|
|
|
|
|
|
params = Device.ConnectionParameters(
|
|
|
|
device_family=Device.Family.SmartTapoPlug,
|
|
|
|
encryption_type=Device.EncryptionType.Xor,
|
|
|
|
login_version=login_version,
|
|
|
|
)
|
|
|
|
config = DeviceConfig(host, credentials=credentials, connection_type=params)
|
|
|
|
transport = transport_class(config=config)
|
|
|
|
|
|
|
|
credentials_hash = transport.credentials_hash
|
|
|
|
|
|
|
|
expected = None if expected_blank else expected_hash
|
|
|
|
assert credentials_hash == expected
|
|
|
|
|
|
|
|
|
2024-01-03 21:46:08 +00:00
|
|
|
@pytest.mark.parametrize(
|
2024-01-25 17:37:19 +00:00
|
|
|
"transport_class",
|
2024-08-30 15:30:07 +00:00
|
|
|
[AesTransport, KlapTransport, KlapTransportV2, XorTransport],
|
2024-01-03 21:46:08 +00:00
|
|
|
)
|
2024-07-02 12:43:37 +00:00
|
|
|
async def test_transport_credentials_hash_from_config(mocker, transport_class):
|
|
|
|
"""Test that credentials_hash provided via config sets correctly."""
|
2024-01-03 21:46:08 +00:00
|
|
|
host = "127.0.0.1"
|
|
|
|
|
|
|
|
credentials = Credentials("Foo", "Bar")
|
|
|
|
config = DeviceConfig(host, credentials=credentials)
|
|
|
|
transport = transport_class(config=config)
|
|
|
|
credentials_hash = transport.credentials_hash
|
|
|
|
config = DeviceConfig(host, credentials_hash=credentials_hash)
|
|
|
|
transport = transport_class(config=config)
|
|
|
|
|
|
|
|
assert transport.credentials_hash == credentials_hash
|
2024-01-25 17:37:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("error", "retry_expectation"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
|
|
|
(ConnectionRefusedError("dummy exception"), False),
|
|
|
|
(OSError(errno.EHOSTDOWN, os.strerror(errno.EHOSTDOWN)), False),
|
|
|
|
(OSError(errno.ECONNRESET, os.strerror(errno.ECONNRESET)), True),
|
|
|
|
(Exception("dummy exception"), True),
|
|
|
|
],
|
|
|
|
ids=("ConnectionRefusedError", "OSErrorNoRetry", "OSErrorRetry", "Exception"),
|
|
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_will_retry_on_connect(
|
|
|
|
mocker, protocol_class, transport_class, error, retry_expectation
|
|
|
|
):
|
|
|
|
retry_count = 2
|
|
|
|
conn = mocker.patch("asyncio.open_connection", side_effect=error)
|
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
|
|
|
{}, retry_count=retry_count
|
|
|
|
)
|
|
|
|
|
|
|
|
assert conn.call_count == (retry_count + 1 if retry_expectation else 1)
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("error", "retry_expectation"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
|
|
|
(ConnectionRefusedError("dummy exception"), True),
|
|
|
|
(OSError(errno.EHOSTDOWN, os.strerror(errno.EHOSTDOWN)), True),
|
|
|
|
(OSError(errno.ECONNRESET, os.strerror(errno.ECONNRESET)), True),
|
|
|
|
(Exception("dummy exception"), True),
|
|
|
|
],
|
|
|
|
ids=("ConnectionRefusedError", "OSErrorNoRetry", "OSErrorRetry", "Exception"),
|
|
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
2024-08-30 15:30:07 +00:00
|
|
|
("protocol_class", "transport_class"),
|
2024-01-25 17:37:19 +00:00
|
|
|
[
|
2024-01-26 09:11:31 +00:00
|
|
|
(_deprecated_TPLinkSmartHomeProtocol, XorTransport),
|
2024-01-25 17:37:19 +00:00
|
|
|
(IotProtocol, XorTransport),
|
|
|
|
],
|
2024-01-26 09:11:31 +00:00
|
|
|
ids=("_deprecated_TPLinkSmartHomeProtocol", "IotProtocol-XorTransport"),
|
2024-01-25 17:37:19 +00:00
|
|
|
)
|
|
|
|
async def test_protocol_will_retry_on_write(
|
|
|
|
mocker, protocol_class, transport_class, error, retry_expectation
|
|
|
|
):
|
|
|
|
retry_count = 2
|
|
|
|
writer = mocker.patch("asyncio.StreamWriter")
|
|
|
|
write_mock = mocker.patch.object(writer, "write", side_effect=error)
|
|
|
|
|
|
|
|
def aio_mock_writer(_, __):
|
|
|
|
nonlocal writer
|
|
|
|
reader = mocker.patch("asyncio.StreamReader")
|
|
|
|
|
|
|
|
return reader, writer
|
|
|
|
|
|
|
|
conn = mocker.patch("asyncio.open_connection", side_effect=aio_mock_writer)
|
|
|
|
write_mock = mocker.patch("asyncio.StreamWriter.write", side_effect=error)
|
|
|
|
config = DeviceConfig("127.0.0.1")
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException):
|
2024-01-25 17:37:19 +00:00
|
|
|
await protocol_class(transport=transport_class(config=config)).query(
|
|
|
|
{}, retry_count=retry_count
|
|
|
|
)
|
|
|
|
|
|
|
|
expected_call_count = retry_count + 1 if retry_expectation else 1
|
|
|
|
assert conn.call_count == expected_call_count
|
|
|
|
assert write_mock.call_count == expected_call_count
|
2024-01-26 09:11:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_deprecated_protocol():
|
|
|
|
with pytest.deprecated_call():
|
|
|
|
from kasa import TPLinkSmartHomeProtocol
|
|
|
|
|
2024-02-21 15:52:55 +00:00
|
|
|
with pytest.raises(KasaException, match="host or transport must be supplied"):
|
2024-01-26 09:11:31 +00:00
|
|
|
proto = TPLinkSmartHomeProtocol()
|
|
|
|
host = "127.0.0.1"
|
|
|
|
proto = TPLinkSmartHomeProtocol(host=host)
|
|
|
|
assert proto.config.host == host
|
2024-07-17 17:57:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
@device_iot
|
|
|
|
async def test_iot_queries_redaction(dev: IotDevice, caplog: pytest.LogCaptureFixture):
|
|
|
|
"""Test query sensitive info redaction."""
|
|
|
|
device_id = "123456789ABCDEF"
|
|
|
|
cast(FakeIotTransport, dev.protocol._transport).proto["system"]["get_sysinfo"][
|
|
|
|
"deviceId"
|
|
|
|
] = device_id
|
|
|
|
|
|
|
|
# Info no message logging
|
|
|
|
caplog.set_level(logging.INFO)
|
|
|
|
await dev.update()
|
|
|
|
assert device_id not in caplog.text
|
|
|
|
|
|
|
|
caplog.set_level(logging.DEBUG, logger="kasa")
|
|
|
|
# The fake iot protocol also logs so disable it
|
|
|
|
test_logger = logging.getLogger("kasa.tests.fakeprotocol_iot")
|
|
|
|
test_logger.setLevel(logging.INFO)
|
|
|
|
|
|
|
|
# Debug no redaction
|
|
|
|
caplog.clear()
|
|
|
|
cast(IotProtocol, dev.protocol)._redact_data = False
|
|
|
|
await dev.update()
|
|
|
|
assert device_id in caplog.text
|
|
|
|
|
|
|
|
# Debug redaction
|
|
|
|
caplog.clear()
|
|
|
|
cast(IotProtocol, dev.protocol)._redact_data = True
|
|
|
|
await dev.update()
|
|
|
|
assert device_id not in caplog.text
|
|
|
|
assert "REDACTED_" + device_id[9::] in caplog.text
|
|
|
|
|
|
|
|
|
|
|
|
async def test_redact_data():
|
|
|
|
"""Test redact data function."""
|
|
|
|
data = {
|
|
|
|
"device_id": "123456789ABCDEF",
|
|
|
|
"owner": "0987654",
|
|
|
|
"mac": "12:34:56:78:90:AB",
|
|
|
|
"ip": "192.168.1",
|
|
|
|
"no_val": None,
|
|
|
|
}
|
|
|
|
excpected_data = {
|
|
|
|
"device_id": "REDACTED_ABCDEF",
|
|
|
|
"owner": "**REDACTED**",
|
|
|
|
"mac": "12:34:56:00:00:00",
|
|
|
|
"ip": "**REDACTEX**",
|
|
|
|
"no_val": None,
|
|
|
|
}
|
|
|
|
REDACTORS = {
|
|
|
|
"device_id": lambda x: "REDACTED_" + x[9::],
|
|
|
|
"owner": None,
|
|
|
|
"mac": mask_mac,
|
|
|
|
"ip": lambda x: "127.0.0." + x.split(".")[3],
|
|
|
|
}
|
|
|
|
|
|
|
|
redacted_data = redact_data(data, REDACTORS)
|
|
|
|
|
|
|
|
assert redacted_data == excpected_data
|