Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure uncaught errors in connection tasks are logged #101

Merged
merged 1 commit into from
Feb 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pyheos/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,23 @@ async def _on_command_error(self, error: CommandFailedError) -> None:
for callback in self._on_command_error_callbacks:
await callback(error)

def _log_callback_exception(self, future: asyncio.Future[Any]) -> None:
"""Log uncaught exception that occurs in a callback."""
if not future.cancelled() and future.exception():
_LOGGER.exception(
"Unexpected exception in task: %s",
future,
exc_info=future.exception(),
)

def _register_task(
self, future: Coroutine[Any, Any, None], name: str | None = None
) -> None:
"""Register a task that is running in the background, so it can be canceled and reset later."""
task: asyncio.Task[None] = asyncio.create_task(future, name=name)
self._running_tasks.add(task)
task.add_done_callback(self._running_tasks.discard)
task.add_done_callback(self._log_callback_exception)

async def _reset(self) -> None:
"""Reset the state of the connection."""
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/player.get_now_playing_media_failed.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"heos": {"command": "player/get_now_playing_media", "result": "fail", "message": "eid=2&text=ID Not Valid&pid=1"}}
26 changes: 26 additions & 0 deletions tests/test_heos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1518,3 +1518,29 @@ async def test_unrecognized_event_logs(
await heos.dispatcher.wait_all()

assert "Unrecognized event: " in caplog.text


@calls_player_commands()
async def test_uncaught_error_in_event_callback_logs(
mock_device: MockHeosDevice, heos: Heos, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unexpected exception during event callback execution logs."""
await heos.get_players()
player = heos.players[1]

# Register command that results in an exception
command = mock_device.register(
c.COMMAND_GET_NOW_PLAYING_MEDIA,
None,
"player.get_now_playing_media_failed",
replace=True,
)
# Write event through mock device
await mock_device.write_event(
"event.player_now_playing_changed", {"player_id": player.player_id}
)

while "Unexpected exception in task:" not in caplog.text:
await asyncio.sleep(0.1)

command.assert_called()