conftest.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import asyncio
  2. import gc
  3. import multiprocessing as mp
  4. from contextlib import suppress
  5. import psutil
  6. import pytest
  7. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  8. from hivemind.utils.mpfuture import MPFuture, SharedBytes
  9. use_hivemind_log_handler("in_root_logger")
  10. logger = get_logger(__name__)
  11. @pytest.fixture
  12. def event_loop():
  13. """
  14. This overrides the ``event_loop`` fixture from pytest-asyncio
  15. (e.g. to make it compatible with ``asyncio.subprocess``).
  16. This fixture is identical to the original one but does not call ``loop.close()`` in the end.
  17. Indeed, at this point, the loop is already stopped (i.e. next tests are free to create new loops).
  18. However, finalizers of objects created in the current test may reference the current loop and fail if it is closed.
  19. For example, this happens while using ``asyncio.subprocess`` (the ``asyncio.subprocess.Process`` finalizer
  20. fails if the loop is closed, but works if the loop is only stopped).
  21. """
  22. yield asyncio.get_event_loop()
  23. @pytest.fixture(autouse=True, scope="session")
  24. def cleanup_children():
  25. yield
  26. gc.collect() # Call .__del__() for removed objects
  27. children = psutil.Process().children(recursive=True)
  28. if children:
  29. logger.info(f"Cleaning up {len(children)} leftover child processes")
  30. for child in children:
  31. with suppress(psutil.NoSuchProcess):
  32. child.terminate()
  33. psutil.wait_procs(children, timeout=1)
  34. for child in children:
  35. with suppress(psutil.NoSuchProcess):
  36. child.kill()
  37. MPFuture.reset_backend()