From 220dfd0d88518b72c7521487cf23f3f3cfe45bae Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Tue, 24 Nov 2026 09:33:08 +0100 Subject: [PATCH] Tests against unawaited and pending tasks --- CHANGELOG.md | 15 ++++++++++ docs/source/advanced/async.rst | 10 ++++++- pyhap/accessory_driver.py | 17 ++++++++++++ pyproject.toml | 15 ++++++++++ tests/conftest.py | 43 ++++++++++++++++++++++++++++ tests/test_asyncio_guards.py | 51 ++++++++++++++++++++++++++++++++++ 6 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 tests/test_asyncio_guards.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 557a5bbe..f0d3e09d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,18 @@ Sections removes a pairing (guarded, since removing the last admin wipes all pairings). Also `load_accessory_state`/`save_accessory_state`/ `remove_client_pairing` in `pyhap.client` for the programmatic equivalent. +- Test tooling that fails on awaitables that are never awaited: pytest now + promotes `RuntimeWarning` ("coroutine ... was never awaited", surfacing as + `PytestUnraisableExceptionWarning` under the error filter) to test + failures via `filterwarnings` in `pyproject.toml`, a guard fixture in + `tests/conftest.py` fails any test during which asyncio logs "Task was + destroyed but it is pending!", and ruff's `RUF006` flags + `create_task`/`ensure_future` results that are not kept. Together with the + `_noop()` side effect of the `async_zeroconf` mock, this makes the existing + start/stop tests fail if the driver ever stops awaiting the broadcast + awaitables zeroconf returns (the + [#580](https://github.com/ikalchev/HAP-python/pull/580) bug class). + `tests/test_asyncio_guards.py` guards the `filterwarnings` config itself. ### Fixed @@ -58,6 +70,9 @@ Sections connection closed. The per-connection response was kept under the closed connection's address forever, where a later connection reusing the address could read it, e.g. a Setup Endpoints answer with its session's SRTP keys. +- Cancel tasks still pending on the loop before `AccessoryDriver.start` + closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at + shutdown ("Task was destroyed but it is pending!"). ### Changed diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index 460f9be2..d9abaf9a 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -166,7 +166,15 @@ Caveats never back to the connection that caused it. * **Un-awaited tasks are not free.** A bare ``asyncio.create_task`` result can be garbage-collected before it runs, and its exception is only a - warning; prefer :func:`pyhap.util.async_create_background_task`. + warning; prefer :func:`pyhap.util.async_create_background_task`. The same + applies to awaitables returned *by* awaited calls — e.g. zeroconf's + ``async_unregister_service`` returns the goodbye-broadcast task, which must + be awaited too, or it is still pending when the loop closes. The test + suite enforces this: ``RuntimeWarning`` ("coroutine ... was never + awaited") is promoted to a test error via ``filterwarnings``, a guard + fixture in ``tests/conftest.py`` fails any test during which asyncio logs + "Task was destroyed but it is pending!", and ruff's ``RUF006`` flags + ``create_task``/``ensure_future`` results that are not kept. * **Subprocesses on the loop's executor.** If your accessory runs ffmpeg or other subprocesses (cameras do), be aware the loop reaps them; the driver sets a child watcher when it owns the loop. Starting subprocesses from a diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 0d2800a7..790b8da9 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -492,9 +492,26 @@ def start(self) -> None: self.loop.call_soon_threadsafe(self.loop.create_task, self.async_stop()) self.loop.run_forever() finally: + self._cancel_pending_tasks() self.loop.close() logger.info("Closed the event loop") + def _cancel_pending_tasks(self) -> None: + """Cancel tasks still pending on the loop before it is closed. + + Without this, a task that is still running when the loop stops (e.g. + a ``run_at_interval`` wrapper awaiting its ``run`` task) is destroyed + pending at loop close, which asyncio logs as "Task was destroyed but + it is pending!". + """ + pending = [task for task in asyncio.all_tasks(self.loop) if not task.done()] + for task in pending: + task.cancel() + if pending: + self.loop.run_until_complete( + asyncio.gather(*pending, return_exceptions=True) + ) + def start_service(self) -> None: """Start the service.""" self._validate_start() diff --git a/pyproject.toml b/pyproject.toml index d3082e2a..a7a84495 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,6 +85,7 @@ select = [ "UP", # pyupgrade "ANN", # flake8-annotations "E721", # type-comparison: use isinstance(x, T) instead of type(x) == T + "RUF006", # asyncio-dangling-task: keep a reference to create_task/ensure_future results ] ignore = [ "ANN401", # Any is sometimes the honest type; prefer precise types @@ -161,3 +162,17 @@ norecursedirs = [ "testing_config", ] asyncio_mode = "auto" +# Catch awaitables that are never awaited: an un-awaited coroutine raises +# RuntimeWarning("coroutine ... was never awaited") when it is finalized; +# the error filter turns that into an exception inside the coroutine's +# __del__, which surfaces as an unraisable "Exception ignored while +# finalizing coroutine ..." (pytest.PytestUnraisableExceptionWarning) and is +# promoted to a test failure by the second entry. +# +# Pending tasks destroyed at +# loop shutdown ("Task was destroyed but it is pending!") only log on the +# asyncio logger and are caught by the guard fixture in tests/conftest.py. +filterwarnings = [ + "error::RuntimeWarning", + "error:Exception ignored.*coroutine:pytest.PytestUnraisableExceptionWarning", +] diff --git a/tests/conftest.py b/tests/conftest.py index 6fa10b34..65793154 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,8 @@ import asyncio from collections.abc import AsyncIterator, Callable, Iterator +import gc +import logging import pathlib from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -59,6 +61,47 @@ def mock_local_address() -> Iterator[None]: yield +@pytest.fixture(autouse=True) +def fail_on_dangling_asyncio_objects() -> Iterator[None]: + """Fail a test when asyncio reports an awaitable that was never awaited. + + An un-awaited coroutine raises ``RuntimeWarning("coroutine ... was never + awaited")`` when finalized, which ``filterwarnings`` in pyproject.toml + promotes to an error. A pending task that is garbage collected only logs + "Task was destroyed but it is pending!" on the asyncio logger, so capture + those records here and fail the test that was running when it happened. + """ + records: list[logging.LogRecord] = [] + + class _Handler(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: + records.append(record) + + handler = _Handler(level=logging.ERROR) + asyncio_logger = logging.getLogger("asyncio") + asyncio_logger.addHandler(handler) + try: + yield + finally: + gc.collect() + asyncio_logger.removeHandler(handler) + dangling = [ + record.getMessage() + for record in records + if record.levelno >= logging.ERROR + and ( + "was destroyed but it is pending" in record.getMessage() + or "was never awaited" in record.getMessage() + ) + ] + if dangling: + pytest.fail( + "asyncio reported un-awaited or dangling awaitables:\n" + + "\n".join(dangling), + pytrace=False, + ) + + class MockDriver: def __init__(self) -> None: self.loader = Loader() diff --git a/tests/test_asyncio_guards.py b/tests/test_asyncio_guards.py new file mode 100644 index 00000000..386fa08f --- /dev/null +++ b/tests/test_asyncio_guards.py @@ -0,0 +1,51 @@ +"""Guard tests for the suite's un-awaited-awaitable detection. + +pyproject.toml promotes ``RuntimeWarning`` and +``pytest.PytestUnraisableExceptionWarning`` to test failures, and +``tests/conftest.py`` fails a test when asyncio logs "Task was destroyed but +it is pending!" / "... was never awaited". The tests here prove that this +harness actually catches awaitables that are never awaited. +""" + +import pathlib +import subprocess +import sys + +REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent + + +def test_suite_fails_on_unawaited_coroutine(tmp_path: pathlib.Path) -> None: + """A test that drops a coroutine must fail under the suite's config. + + Runs a scratch test file through pytest with this repo's pyproject.toml + as the config, so the assertion exercises the real ``filterwarnings`` + setup rather than a copy of it. + + A separate process fork is necessary as __del__ on a coroutine raises when + it is not awaited and propagates to sys.unraisablehook, not to the caller + (so we cannot assert properly here). + """ + test_file = tmp_path / "test_unawaited_coroutine.py" + test_file.write_text( + "def test_unawaited():\n async def coro():\n pass\n coro()\n" + ) + proc = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-c", + str(REPO_ROOT / "pyproject.toml"), + "-p", + "no:cacheprovider", + "-q", + str(test_file), + ], + capture_output=True, + text=True, + cwd=REPO_ROOT, + timeout=120, + check=False, + ) + assert proc.returncode != 0 + assert "coroutine" in proc.stdout