Browse Source

fix: log failed background tasks instead of leaving them unretrieved (#586)

* fix: log failed background tasks instead of leaving them unretrieved

* fix: keep unexpected background task failures visible at error level

* test: compare background task set against a snapshot
derekcentrico 9 hours ago
parent
commit
d46452efff
2 changed files with 112 additions and 2 deletions
  1. 22 1
      switchbot/helpers.py
  2. 90 1
      tests/test_helpers.py

+ 22 - 1
switchbot/helpers.py

@@ -1,10 +1,19 @@
 from __future__ import annotations
 
 import asyncio
+import logging
 import struct
 from collections.abc import Coroutine
 from typing import Any, TypeVar
 
+from bleak.exc import BleakError
+
+_LOGGER = logging.getLogger(__name__)
+
+# Background tasks are opportunistic refreshes, so a dropped BLE exchange is
+# expected and retried on the next advertisement or poll.
+_TRANSIENT_EXCEPTIONS = (TimeoutError, BleakError, EOFError, BrokenPipeError)
+
 _R = TypeVar("_R")
 
 _BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
@@ -18,10 +27,22 @@ def create_background_task(target: Coroutine[Any, Any, _R]) -> asyncio.Task[_R]:
     """Create a background task."""
     task = asyncio.create_task(target)
     _BACKGROUND_TASKS.add(task)
-    task.add_done_callback(_BACKGROUND_TASKS.remove)
+    task.add_done_callback(_background_task_done)
     return task
 
 
+def _background_task_done(task: asyncio.Task[Any]) -> None:
+    """Drop a finished background task and log its failure, if any."""
+    _BACKGROUND_TASKS.discard(task)
+    if task.cancelled() or (exc := task.exception()) is None:
+        return
+    name = getattr(task.get_coro(), "__qualname__", task.get_name())
+    if isinstance(exc, _TRANSIENT_EXCEPTIONS):
+        _LOGGER.debug("Background task %s failed", name, exc_info=exc)
+    else:
+        _LOGGER.error("Background task %s failed", name, exc_info=exc)
+
+
 def parse_power_data(
     data: bytes, offset: int, scale: float = 1.0, mask: int | None = None
 ) -> float:

+ 90 - 1
tests/test_helpers.py

@@ -1,8 +1,97 @@
 """Tests for helper functions."""
 
+import asyncio
+import gc
+import logging
+
 import pytest
 
-from switchbot.helpers import parse_power_data
+from switchbot.helpers import (
+    _BACKGROUND_TASKS,
+    create_background_task,
+    parse_power_data,
+)
+
+
+async def _drain_background_task(task: asyncio.Task) -> list[dict]:
+    """Let a background task finish and collect unhandled-exception reports."""
+    loop = asyncio.get_running_loop()
+    reports: list[dict] = []
+    previous_handler = loop.get_exception_handler()
+    loop.set_exception_handler(lambda _loop, context: reports.append(context))
+    try:
+        await asyncio.wait([task])
+        await asyncio.sleep(0)
+        del task
+        gc.collect()
+        await asyncio.sleep(0)
+    finally:
+        loop.set_exception_handler(previous_handler)
+    return reports
+
+
+async def _update() -> None:
+    raise TimeoutError
+
+
+async def _parse() -> None:
+    raise IndexError("index out of range")
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+    ("coro_func", "level", "exc_name"),
+    [
+        pytest.param(_update, logging.DEBUG, "TimeoutError", id="transient"),
+        pytest.param(_parse, logging.ERROR, "IndexError", id="unexpected"),
+    ],
+)
+async def test_background_task_failure_is_logged(
+    caplog: pytest.LogCaptureFixture,
+    coro_func,
+    level: int,
+    exc_name: str,
+) -> None:
+    """Test a failed background task is logged instead of left unretrieved."""
+    caplog.set_level(logging.DEBUG, logger="switchbot.helpers")
+    pending = set(_BACKGROUND_TASKS)
+
+    reports = await _drain_background_task(create_background_task(coro_func()))
+
+    assert reports == []
+    assert pending == _BACKGROUND_TASKS
+    [record] = caplog.records
+    assert record.levelno == level
+    assert record.getMessage() == f"Background task {coro_func.__name__} failed"
+    assert record.exc_info[0].__name__ == exc_name
+
+
+@pytest.mark.asyncio
+async def test_background_task_cancelled() -> None:
+    """Test a cancelled background task is dropped without errors."""
+    task = create_background_task(asyncio.sleep(10))
+    await asyncio.sleep(0)
+    task.cancel()
+
+    reports = await _drain_background_task(task)
+
+    assert reports == []
+    assert task not in _BACKGROUND_TASKS
+
+
+@pytest.mark.asyncio
+async def test_background_task_success() -> None:
+    """Test a successful background task is dropped from the set."""
+
+    async def _ok() -> int:
+        return 1
+
+    pending = set(_BACKGROUND_TASKS)
+
+    reports = await _drain_background_task(create_background_task(_ok()))
+
+    assert reports == []
+    assert pending == _BACKGROUND_TASKS
 
 
 def test_parse_power_data_basic():