Skip to content

Commit

Permalink
Avoid calling pformat unless debug logging is enabled (#217)
Browse files Browse the repository at this point in the history
* Avoid calling pformat unless debug logging is enabled

* add logging test

* isort

* check for debug logging

* formatting
  • Loading branch information
bdraco committed Sep 26, 2021
1 parent 85f17ab commit 76c1264
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
7 changes: 5 additions & 2 deletions kasa/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ async def _execute_query(self, request: str) -> Dict:
"""Execute a query on the device and wait for the response."""
assert self.writer is not None
assert self.reader is not None
debug_log = _LOGGER.isEnabledFor(logging.DEBUG)

_LOGGER.debug("> (%i) %s", len(request), request)
if debug_log:
_LOGGER.debug("> (%i) %s", len(request), request)
self.writer.write(TPLinkSmartHomeProtocol.encrypt(request))
await self.writer.drain()

Expand All @@ -101,7 +103,8 @@ async def _execute_query(self, request: str) -> Dict:
buffer = await self.reader.readexactly(length)
response = TPLinkSmartHomeProtocol.decrypt(buffer)
json_payload = json.loads(response)
_LOGGER.debug("< (%i) %s", len(response), pf(json_payload))
if debug_log:
_LOGGER.debug("< (%i) %s", len(response), pf(json_payload))
return json_payload

async def close(self):
Expand Down
34 changes: 34 additions & 0 deletions kasa/tests/test_protocol.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging
import struct
import sys

Expand Down Expand Up @@ -64,6 +65,39 @@ def aio_mock_writer(_, __):
assert response == {"great": "success"}


@pytest.mark.skipif(sys.version_info < (3, 8), reason="3.8 is first one with asyncmock")
@pytest.mark.parametrize("log_level", [logging.WARNING, logging.DEBUG])
async def test_protocol_logging(mocker, caplog, log_level):
caplog.set_level(log_level)
logging.getLogger("kasa").setLevel(log_level)
encrypted = TPLinkSmartHomeProtocol.encrypt('{"great":"success"}')[
TPLinkSmartHomeProtocol.BLOCK_SIZE :
]

async def _mock_read(byte_count):
nonlocal encrypted
if byte_count == TPLinkSmartHomeProtocol.BLOCK_SIZE:
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

protocol = TPLinkSmartHomeProtocol("127.0.0.1")
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


def test_encrypt():
d = json.dumps({"foo": 1, "bar": 2})
encrypted = TPLinkSmartHomeProtocol.encrypt(d)
Expand Down

0 comments on commit 76c1264

Please sign in to comment.