| 1 |
import asyncio |
| 2 |
import os |
| 3 |
import subprocess |
| 4 |
import sys |
| 5 |
from typing import AsyncGenerator |
| 6 |
|
| 7 |
import pytest |
| 8 |
import pytest_asyncio |
| 9 |
|
| 10 |
from cockpit._vendor.systemd_ctypes import EventLoopPolicy |
| 11 |
|
| 12 |
collect_ignore: list[str] = [] |
| 13 |
if sys.version_info < (3, 12): |
| 14 |
# Not used from cockpit-bridge and only intended for Python 3.12+ |
| 15 |
collect_ignore.append("ws") |
| 16 |
|
| 17 |
|
| 18 |
def any_subprocesses() -> bool: |
| 19 |
# Make sure we don't leak subprocesses |
| 20 |
try: |
| 21 |
os.waitid(os.P_ALL, -1, os.WEXITED | os.WNOHANG | os.WNOWAIT) |
| 22 |
except ChildProcessError: |
| 23 |
return False # good ! |
| 24 |
else: |
| 25 |
return True # at least one process (or zombie) still waitable |
| 26 |
|
| 27 |
|
| 28 |
# some issues: |
| 29 |
# - even sourcing this will break old python versions in ways we don't care to fix |
| 30 |
# - even sourcing this requires aiohttp, which isn't available everywhere |
| 31 |
# - there are general issues running under tox which need investigation |
| 32 |
# - this also requires a bots/ checkout which we don't have in distros |
| 33 |
if "NO_QUNIT" in os.environ: |
| 34 |
collect_ignore.append("test_browser.py") |
| 35 |
else: |
| 36 |
pytest_plugins = "js_coverage" |
| 37 |
|
| 38 |
|
| 39 |
@pytest.fixture |
| 40 |
# AbstractEventLoopPolicy is deprecated in 3.14 and will be removed in 3.16 |
| 41 |
def event_loop_policy() -> asyncio.AbstractEventLoopPolicy: # type: ignore[name-defined] |
| 42 |
return EventLoopPolicy() |
| 43 |
|
| 44 |
|
| 45 |
@pytest_asyncio.fixture(autouse=True) |
| 46 |
async def _check_settled() -> AsyncGenerator[None, None]: |
| 47 |
yield |
| 48 |
|
| 49 |
current_task = asyncio.current_task() |
| 50 |
assert current_task is not None |
| 51 |
event_loop = asyncio.get_running_loop() |
| 52 |
|
| 53 |
# Let all tasks and subprocesses run to completion |
| 54 |
for _ in range(200): |
| 55 |
all_tasks = asyncio.all_tasks(loop=event_loop) - {current_task} |
| 56 |
if not (all_tasks or any_subprocesses()): |
| 57 |
break |
| 58 |
await asyncio.sleep(0.005) |
| 59 |
|
| 60 |
# No tasks left |
| 61 |
assert asyncio.all_tasks(loop=event_loop) == {current_task} |
| 62 |
|
| 63 |
# No subprocesses left |
| 64 |
if any_subprocesses(): |
| 65 |
# Bad news. Show some helpful output. |
| 66 |
subprocess.run(['ps', 'f', f'--pid={os.getpid()}', f'--ppid={os.getpid()}']) |
| 67 |
# clear it out for the sake of the other tests |
| 68 |
subprocess.run(['pkill', '-9', '-P', f'{os.getpid()}']) |
| 69 |
try: |
| 70 |
for _ in range(100): # zombie vacuum |
| 71 |
os.wait() |
| 72 |
except ChildProcessError: |
| 73 |
pass |
| 74 |
|
| 75 |
pytest.fail('Some subprocesses still running!') |