This commit is contained in:
J. Nick Koston 2023-11-19 10:47:21 -06:00
parent 0dfb322c5c
commit f55428549f
No known key found for this signature in database
3 changed files with 41 additions and 25 deletions

View File

@ -1,5 +1,7 @@
"""Device creation by type.""" """Device creation by type."""
import logging
import time
from typing import Any, Dict, Optional, Type from typing import Any, Dict, Optional, Type
from .credentials import Credentials from .credentials import Credentials
@ -19,6 +21,8 @@ DEVICE_TYPE_TO_CLASS = {
DeviceType.LightStrip: SmartLightStrip, DeviceType.LightStrip: SmartLightStrip,
} }
_LOGGER = logging.getLogger(__name__)
async def connect( async def connect(
host: str, host: str,
@ -48,11 +52,24 @@ async def connect(
:rtype: SmartDevice :rtype: SmartDevice
:return: Object for querying/controlling found device. :return: Object for querying/controlling found device.
""" """
debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
if debug_enabled:
start_time = time.perf_counter()
if device_type and (klass := DEVICE_TYPE_TO_CLASS.get(device_type)): if device_type and (klass := DEVICE_TYPE_TO_CLASS.get(device_type)):
dev: SmartDevice = klass( dev: SmartDevice = klass(
host=host, port=port, credentials=credentials, timeout=timeout host=host, port=port, credentials=credentials, timeout=timeout
) )
await dev.update() await dev.update()
if debug_enabled:
end_time = time.perf_counter()
_LOGGER.debug(
"Device %s with known type (%s) took %.2f seconds to connect",
host,
device_type.value,
end_time - start_time,
)
return dev return dev
unknown_dev = SmartDevice( unknown_dev = SmartDevice(
@ -65,6 +82,14 @@ async def connect(
# so we don't have to reconnect # so we don't have to reconnect
dev.protocol = unknown_dev.protocol dev.protocol = unknown_dev.protocol
await dev.update() await dev.update()
if debug_enabled:
end_time = time.perf_counter()
_LOGGER.debug(
"Device %s with unknown type (%s) took %.2f seconds to connect",
host,
dev.device_type.value,
end_time - start_time,
)
return dev return dev

View File

@ -1,32 +1,24 @@
# type: ignore # type: ignore
import re import logging
import socket
import sys
from typing import Type from typing import Type
import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342 import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342
from kasa import ( from kasa import (
DeviceType, DeviceType,
Discover,
SmartBulb, SmartBulb,
SmartDevice, SmartDevice,
SmartDeviceException, SmartDeviceException,
SmartDimmer, SmartDimmer,
SmartLightStrip, SmartLightStrip,
SmartPlug, SmartPlug,
protocol,
) )
from kasa.device_factory import DEVICE_TYPE_TO_CLASS, connect from kasa.device_factory import connect
from kasa.discover import _DiscoverProtocol, json_dumps
from kasa.exceptions import UnsupportedDeviceException
from .conftest import bulb, dimmer, lightstrip, plug, strip
@pytest.mark.parametrize("custom_port", [123, None]) @pytest.mark.parametrize("custom_port", [123, None])
async def test_connect(discovery_data: dict, mocker, custom_port): async def test_connect(discovery_data: dict, mocker, custom_port):
"""Make sure that connect_single returns an initialized SmartDevice instance.""" """Make sure that connect returns an initialized SmartDevice instance."""
host = "127.0.0.1" host = "127.0.0.1"
mocker.patch("kasa.TPLinkSmartHomeProtocol.query", return_value=discovery_data) mocker.patch("kasa.TPLinkSmartHomeProtocol.query", return_value=discovery_data)
@ -53,7 +45,7 @@ async def test_connect_passed_device_type(
klass: Type[SmartDevice], klass: Type[SmartDevice],
custom_port, custom_port,
): ):
"""Make sure that connect_single with a passed device type.""" """Make sure that connect with a passed device type."""
host = "127.0.0.1" host = "127.0.0.1"
mocker.patch("kasa.TPLinkSmartHomeProtocol.query", return_value=discovery_data) mocker.patch("kasa.TPLinkSmartHomeProtocol.query", return_value=discovery_data)
@ -63,9 +55,20 @@ async def test_connect_passed_device_type(
async def test_connect_query_fails(discovery_data: dict, mocker): async def test_connect_query_fails(discovery_data: dict, mocker):
"""Make sure that connect_single fails when query fails.""" """Make sure that connect fails when query fails."""
host = "127.0.0.1" host = "127.0.0.1"
mocker.patch("kasa.TPLinkSmartHomeProtocol.query", side_effect=SmartDeviceException) mocker.patch("kasa.TPLinkSmartHomeProtocol.query", side_effect=SmartDeviceException)
with pytest.raises(SmartDeviceException): with pytest.raises(SmartDeviceException):
await connect(host) await connect(host)
async def test_connect_logs_connect_time(
discovery_data: dict, caplog: pytest.LogCaptureFixture, mocker
):
"""Test that the connect time is logged when debug logging is enabled."""
host = "127.0.0.1"
mocker.patch("kasa.TPLinkSmartHomeProtocol.query", return_value=discovery_data)
logging.getLogger("kasa").setLevel(logging.DEBUG)
await connect(host)
assert "seconds to connect" in caplog.text

View File

@ -1,16 +1,4 @@
import inspect
from datetime import datetime
from unittest.mock import patch
import pytest # type: ignore # https://github.com/pytest-dev/pytest/issues/3342
import kasa
from kasa import Credentials, SmartDevice, SmartDeviceException
from kasa.smartdevice import DeviceType from kasa.smartdevice import DeviceType
from kasa.smartstrip import SmartStripPlug
from .conftest import handle_turn_on, has_emeter, no_emeter, turn_on
from .newfakes import PLUG_SCHEMA, TZ_SCHEMA, FakeTransportProtocol
async def test_device_type_from_value(): async def test_device_type_from_value():