_testing.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from __future__ import annotations
  2. from collections.abc import Awaitable, Generator
  3. from typing import Any, cast
  4. from ._eventloop import get_async_backend
  5. class TaskInfo:
  6. """
  7. Represents an asynchronous task.
  8. :ivar int id: the unique identifier of the task
  9. :ivar parent_id: the identifier of the parent task, if any
  10. :vartype parent_id: Optional[int]
  11. :ivar str name: the description of the task (if any)
  12. :ivar ~collections.abc.Coroutine coro: the coroutine object of the task
  13. """
  14. __slots__ = "_name", "id", "parent_id", "name", "coro"
  15. def __init__(
  16. self,
  17. id: int,
  18. parent_id: int | None,
  19. name: str | None,
  20. coro: Generator[Any, Any, Any] | Awaitable[Any],
  21. ):
  22. func = get_current_task
  23. self._name = f"{func.__module__}.{func.__qualname__}"
  24. self.id: int = id
  25. self.parent_id: int | None = parent_id
  26. self.name: str | None = name
  27. self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro
  28. def __eq__(self, other: object) -> bool:
  29. if isinstance(other, TaskInfo):
  30. return self.id == other.id
  31. return NotImplemented
  32. def __hash__(self) -> int:
  33. return hash(self.id)
  34. def __repr__(self) -> str:
  35. return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})"
  36. def has_pending_cancellation(self) -> bool:
  37. """
  38. Return ``True`` if the task has a cancellation pending, ``False`` otherwise.
  39. """
  40. return False
  41. def get_current_task() -> TaskInfo:
  42. """
  43. Return the current task.
  44. :return: a representation of the current task
  45. :raises NoEventLoopError: if no supported asynchronous event loop is running in the
  46. current thread
  47. """
  48. return get_async_backend().get_current_task()
  49. def get_running_tasks() -> list[TaskInfo]:
  50. """
  51. Return a list of running tasks in the current event loop.
  52. :return: a list of task info objects
  53. :raises NoEventLoopError: if no supported asynchronous event loop is running in the
  54. current thread
  55. """
  56. return cast("list[TaskInfo]", get_async_backend().get_running_tasks())
  57. async def wait_all_tasks_blocked() -> None:
  58. """Wait until all other tasks are waiting for something."""
  59. await get_async_backend().wait_all_tasks_blocked()