| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import gc |
| 4 |
import os |
| 5 |
import random |
| 6 |
import signal |
| 7 |
import subprocess |
| 8 |
import sys |
| 9 |
from collections.abc import AsyncIterator, Callable |
| 10 |
from contextlib import AbstractAsyncContextManager, asynccontextmanager |
| 11 |
from functools import partial |
| 12 |
from pathlib import Path as SyncPath |
| 13 |
from signal import Signals |
| 14 |
from typing import ( |
| 15 |
TYPE_CHECKING, |
| 16 |
Any, |
| 17 |
NoReturn, |
| 18 |
TypeAlias, |
| 19 |
) |
| 20 |
from unittest import mock |
| 21 |
|
| 22 |
import pytest |
| 23 |
|
| 24 |
import trio |
| 25 |
|
| 26 |
from .. import ( |
| 27 |
Event, |
| 28 |
Process, |
| 29 |
_core, |
| 30 |
fail_after, |
| 31 |
move_on_after, |
| 32 |
run_process, |
| 33 |
sleep, |
| 34 |
sleep_forever, |
| 35 |
) |
| 36 |
from .._core._tests.tutil import skip_if_fbsd_pipes_broken, slow |
| 37 |
from ..lowlevel import open_process |
| 38 |
from ..testing import MockClock, assert_no_checkpoints, wait_all_tasks_blocked |
| 39 |
|
| 40 |
if TYPE_CHECKING: |
| 41 |
from types import FrameType |
| 42 |
|
| 43 |
from .._abc import ReceiveStream |
| 44 |
|
| 45 |
if sys.platform == "win32": |
| 46 |
SignalType: TypeAlias = None |
| 47 |
else: |
| 48 |
SignalType: TypeAlias = Signals |
| 49 |
|
| 50 |
SIGKILL: SignalType |
| 51 |
SIGTERM: SignalType |
| 52 |
SIGUSR1: SignalType |
| 53 |
|
| 54 |
posix = os.name == "posix" |
| 55 |
if (not TYPE_CHECKING and posix) or sys.platform != "win32": |
| 56 |
from signal import SIGKILL, SIGTERM, SIGUSR1 |
| 57 |
else: |
| 58 |
SIGKILL, SIGTERM, SIGUSR1 = None, None, None |
| 59 |
|
| 60 |
|
| 61 |
# Since Windows has very few command-line utilities generally available, |
| 62 |
# all of our subprocesses are Python processes running short bits of |
| 63 |
# (mostly) cross-platform code. |
| 64 |
def python(code: str) -> list[str]: |
| 65 |
return [sys.executable, "-u", "-c", "import sys; " + code] |
| 66 |
|
| 67 |
|
| 68 |
EXIT_TRUE = python("sys.exit(0)") |
| 69 |
EXIT_FALSE = python("sys.exit(1)") |
| 70 |
CAT = python("sys.stdout.buffer.write(sys.stdin.buffer.read())") |
| 71 |
|
| 72 |
if posix: |
| 73 |
|
| 74 |
def SLEEP(seconds: int) -> list[str]: |
| 75 |
return ["sleep", str(seconds)] |
| 76 |
|
| 77 |
else: |
| 78 |
|
| 79 |
def SLEEP(seconds: int) -> list[str]: |
| 80 |
return python(f"import time; time.sleep({seconds})") |
| 81 |
|
| 82 |
|
| 83 |
@asynccontextmanager |
| 84 |
async def open_process_then_kill( # type: ignore[misc, explicit-any] |
| 85 |
*args: Any, |
| 86 |
**kwargs: Any, |
| 87 |
) -> AsyncIterator[Process]: |
| 88 |
proc = await open_process(*args, **kwargs) |
| 89 |
try: |
| 90 |
yield proc |
| 91 |
finally: |
| 92 |
proc.kill() |
| 93 |
await proc.wait() |
| 94 |
|
| 95 |
|
| 96 |
@asynccontextmanager |
| 97 |
async def run_process_in_nursery( # type: ignore[misc, explicit-any] |
| 98 |
*args: Any, |
| 99 |
**kwargs: Any, |
| 100 |
) -> AsyncIterator[Process]: |
| 101 |
async with _core.open_nursery() as nursery: |
| 102 |
kwargs.setdefault("check", False) |
| 103 |
value = await nursery.start(partial(run_process, *args, **kwargs)) |
| 104 |
assert isinstance(value, Process) |
| 105 |
proc: Process = value |
| 106 |
yield proc # noqa: RUF075 |
| 107 |
nursery.cancel_scope.cancel() |
| 108 |
|
| 109 |
|
| 110 |
background_process_param = pytest.mark.parametrize( |
| 111 |
"background_process", |
| 112 |
[open_process_then_kill, run_process_in_nursery], |
| 113 |
ids=["open_process", "run_process in nursery"], |
| 114 |
) |
| 115 |
|
| 116 |
BackgroundProcessType: TypeAlias = Callable[ # type: ignore[explicit-any] |
| 117 |
..., |
| 118 |
AbstractAsyncContextManager[Process], |
| 119 |
] |
| 120 |
|
| 121 |
|
| 122 |
@background_process_param |
| 123 |
async def test_basic(background_process: BackgroundProcessType) -> None: |
| 124 |
async with background_process(EXIT_TRUE) as proc: |
| 125 |
await proc.wait() |
| 126 |
assert isinstance(proc, Process) |
| 127 |
assert proc._pidfd is None |
| 128 |
assert proc.returncode == 0 |
| 129 |
assert repr(proc) == f"<trio.Process {EXIT_TRUE}: exited with status 0>" |
| 130 |
|
| 131 |
async with background_process(EXIT_FALSE) as proc: |
| 132 |
await proc.wait() |
| 133 |
assert proc.returncode == 1 |
| 134 |
assert repr(proc) == "<trio.Process {!r}: {}>".format( |
| 135 |
EXIT_FALSE, |
| 136 |
"exited with status 1", |
| 137 |
) |
| 138 |
|
| 139 |
|
| 140 |
@background_process_param |
| 141 |
async def test_basic_no_pidfd(background_process: BackgroundProcessType) -> None: |
| 142 |
with mock.patch("trio._subprocess.can_try_pidfd_open", new=False): |
| 143 |
async with background_process(EXIT_TRUE) as proc: |
| 144 |
assert proc._pidfd is None |
| 145 |
await proc.wait() |
| 146 |
assert isinstance(proc, Process) |
| 147 |
assert proc._pidfd is None |
| 148 |
assert proc.returncode == 0 |
| 149 |
assert repr(proc) == f"<trio.Process {EXIT_TRUE}: exited with status 0>" |
| 150 |
|
| 151 |
async with background_process(EXIT_FALSE) as proc: |
| 152 |
await proc.wait() |
| 153 |
assert proc.returncode == 1 |
| 154 |
assert repr(proc) == "<trio.Process {!r}: {}>".format( |
| 155 |
EXIT_FALSE, |
| 156 |
"exited with status 1", |
| 157 |
) |
| 158 |
|
| 159 |
|
| 160 |
@background_process_param |
| 161 |
async def test_auto_update_returncode( |
| 162 |
background_process: BackgroundProcessType, |
| 163 |
) -> None: |
| 164 |
async with background_process(SLEEP(9999)) as p: |
| 165 |
assert p.returncode is None |
| 166 |
assert "running" in repr(p) |
| 167 |
p.kill() |
| 168 |
p._proc.wait() |
| 169 |
assert p.returncode is not None |
| 170 |
assert "exited" in repr(p) |
| 171 |
assert p._pidfd is None |
| 172 |
assert p.returncode is not None |
| 173 |
|
| 174 |
|
| 175 |
@background_process_param |
| 176 |
async def test_multi_wait(background_process: BackgroundProcessType) -> None: |
| 177 |
async with background_process(SLEEP(10)) as proc: |
| 178 |
# Check that wait (including multi-wait) tolerates being cancelled |
| 179 |
async with _core.open_nursery() as nursery: |
| 180 |
nursery.start_soon(proc.wait) |
| 181 |
nursery.start_soon(proc.wait) |
| 182 |
nursery.start_soon(proc.wait) |
| 183 |
await wait_all_tasks_blocked() |
| 184 |
nursery.cancel_scope.cancel() |
| 185 |
|
| 186 |
# Now try waiting for real |
| 187 |
async with _core.open_nursery() as nursery: |
| 188 |
nursery.start_soon(proc.wait) |
| 189 |
nursery.start_soon(proc.wait) |
| 190 |
nursery.start_soon(proc.wait) |
| 191 |
await wait_all_tasks_blocked() |
| 192 |
proc.kill() |
| 193 |
|
| 194 |
|
| 195 |
@background_process_param |
| 196 |
async def test_multi_wait_no_pidfd(background_process: BackgroundProcessType) -> None: |
| 197 |
with mock.patch("trio._subprocess.can_try_pidfd_open", new=False): |
| 198 |
async with background_process(SLEEP(10)) as proc: |
| 199 |
# Check that wait (including multi-wait) tolerates being cancelled |
| 200 |
async with _core.open_nursery() as nursery: |
| 201 |
nursery.start_soon(proc.wait) |
| 202 |
nursery.start_soon(proc.wait) |
| 203 |
nursery.start_soon(proc.wait) |
| 204 |
await wait_all_tasks_blocked() |
| 205 |
nursery.cancel_scope.cancel() |
| 206 |
|
| 207 |
# Now try waiting for real |
| 208 |
async with _core.open_nursery() as nursery: |
| 209 |
nursery.start_soon(proc.wait) |
| 210 |
nursery.start_soon(proc.wait) |
| 211 |
nursery.start_soon(proc.wait) |
| 212 |
await wait_all_tasks_blocked() |
| 213 |
proc.kill() |
| 214 |
|
| 215 |
|
| 216 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR = python( |
| 217 |
"data = sys.stdin.buffer.read(); " |
| 218 |
"sys.stdout.buffer.write(data); " |
| 219 |
"sys.stderr.buffer.write(data[::-1])", |
| 220 |
) |
| 221 |
|
| 222 |
|
| 223 |
@background_process_param |
| 224 |
async def test_pipes(background_process: BackgroundProcessType) -> None: |
| 225 |
async with background_process( |
| 226 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR, |
| 227 |
stdin=subprocess.PIPE, |
| 228 |
stdout=subprocess.PIPE, |
| 229 |
stderr=subprocess.PIPE, |
| 230 |
) as proc: |
| 231 |
msg = b"the quick brown fox jumps over the lazy dog" |
| 232 |
|
| 233 |
async def feed_input() -> None: |
| 234 |
assert proc.stdin is not None |
| 235 |
await proc.stdin.send_all(msg) |
| 236 |
await proc.stdin.aclose() |
| 237 |
|
| 238 |
async def check_output(stream: ReceiveStream, expected: bytes) -> None: |
| 239 |
seen = bytearray() |
| 240 |
async for chunk in stream: |
| 241 |
seen += chunk |
| 242 |
assert seen == expected |
| 243 |
|
| 244 |
assert proc.stdout is not None |
| 245 |
assert proc.stderr is not None |
| 246 |
|
| 247 |
async with _core.open_nursery() as nursery: |
| 248 |
# fail eventually if something is broken |
| 249 |
nursery.cancel_scope.deadline = _core.current_time() + 30.0 |
| 250 |
nursery.start_soon(feed_input) |
| 251 |
nursery.start_soon(check_output, proc.stdout, msg) |
| 252 |
nursery.start_soon(check_output, proc.stderr, msg[::-1]) |
| 253 |
|
| 254 |
assert not nursery.cancel_scope.cancelled_caught |
| 255 |
assert await proc.wait() == 0 |
| 256 |
|
| 257 |
|
| 258 |
@background_process_param |
| 259 |
async def test_interactive(background_process: BackgroundProcessType) -> None: |
| 260 |
# Test some back-and-forth with a subprocess. This one works like so: |
| 261 |
# in: 32\n |
| 262 |
# out: 0000...0000\n (32 zeroes) |
| 263 |
# err: 1111...1111\n (64 ones) |
| 264 |
# in: 10\n |
| 265 |
# out: 2222222222\n (10 twos) |
| 266 |
# err: 3333....3333\n (20 threes) |
| 267 |
# in: EOF |
| 268 |
# out: EOF |
| 269 |
# err: EOF |
| 270 |
|
| 271 |
async with background_process( |
| 272 |
python( |
| 273 |
"idx = 0\n" |
| 274 |
"while True:\n" |
| 275 |
" line = sys.stdin.readline()\n" |
| 276 |
" if line == '': break\n" |
| 277 |
" request = int(line.strip())\n" |
| 278 |
" print(str(idx * 2) * request)\n" |
| 279 |
" print(str(idx * 2 + 1) * request * 2, file=sys.stderr)\n" |
| 280 |
" idx += 1\n", |
| 281 |
), |
| 282 |
stdin=subprocess.PIPE, |
| 283 |
stdout=subprocess.PIPE, |
| 284 |
stderr=subprocess.PIPE, |
| 285 |
) as proc: |
| 286 |
newline = b"\n" if posix else b"\r\n" |
| 287 |
|
| 288 |
async def expect(idx: int, request: int) -> None: |
| 289 |
async with _core.open_nursery() as nursery: |
| 290 |
|
| 291 |
async def drain_one( |
| 292 |
stream: ReceiveStream, |
| 293 |
count: int, |
| 294 |
digit: int, |
| 295 |
) -> None: |
| 296 |
while count > 0: |
| 297 |
result = await stream.receive_some(count) |
| 298 |
assert result == (f"{digit}".encode() * len(result)) |
| 299 |
count -= len(result) |
| 300 |
assert count == 0 |
| 301 |
assert await stream.receive_some(len(newline)) == newline |
| 302 |
|
| 303 |
assert proc.stdout is not None |
| 304 |
assert proc.stderr is not None |
| 305 |
nursery.start_soon(drain_one, proc.stdout, request, idx * 2) |
| 306 |
nursery.start_soon(drain_one, proc.stderr, request * 2, idx * 2 + 1) |
| 307 |
|
| 308 |
assert proc.stdin is not None |
| 309 |
assert proc.stdout is not None |
| 310 |
assert proc.stderr is not None |
| 311 |
with fail_after(5): |
| 312 |
await proc.stdin.send_all(b"12") |
| 313 |
await sleep(0.1) |
| 314 |
await proc.stdin.send_all(b"345" + newline) |
| 315 |
await expect(0, 12345) |
| 316 |
await proc.stdin.send_all(b"100" + newline + b"200" + newline) |
| 317 |
await expect(1, 100) |
| 318 |
await expect(2, 200) |
| 319 |
await proc.stdin.send_all(b"0" + newline) |
| 320 |
await expect(3, 0) |
| 321 |
await proc.stdin.send_all(b"999999") |
| 322 |
with move_on_after(0.1) as scope: |
| 323 |
await expect(4, 0) |
| 324 |
assert scope.cancelled_caught |
| 325 |
await proc.stdin.send_all(newline) |
| 326 |
await expect(4, 999999) |
| 327 |
await proc.stdin.aclose() |
| 328 |
assert await proc.stdout.receive_some(1) == b"" |
| 329 |
assert await proc.stderr.receive_some(1) == b"" |
| 330 |
await proc.wait() |
| 331 |
|
| 332 |
assert proc.returncode == 0 |
| 333 |
|
| 334 |
|
| 335 |
async def test_run() -> None: |
| 336 |
data = bytes(random.randint(0, 255) for _ in range(2**18)) |
| 337 |
|
| 338 |
result = await run_process( |
| 339 |
CAT, |
| 340 |
stdin=data, |
| 341 |
capture_stdout=True, |
| 342 |
capture_stderr=True, |
| 343 |
) |
| 344 |
assert result.args == CAT |
| 345 |
assert result.returncode == 0 |
| 346 |
assert result.stdout == data |
| 347 |
assert result.stderr == b"" |
| 348 |
|
| 349 |
result = await run_process(CAT, capture_stdout=True) |
| 350 |
assert result.args == CAT |
| 351 |
assert result.returncode == 0 |
| 352 |
assert result.stdout == b"" |
| 353 |
assert result.stderr is None |
| 354 |
|
| 355 |
result = await run_process( |
| 356 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR, |
| 357 |
stdin=data, |
| 358 |
capture_stdout=True, |
| 359 |
capture_stderr=True, |
| 360 |
) |
| 361 |
assert result.args == COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR |
| 362 |
assert result.returncode == 0 |
| 363 |
assert result.stdout == data |
| 364 |
assert result.stderr == data[::-1] |
| 365 |
|
| 366 |
# invalid combinations |
| 367 |
with pytest.raises(UnicodeError): |
| 368 |
await run_process(CAT, stdin="oh no, it's text") |
| 369 |
|
| 370 |
pipe_stdin_error = r"^stdin=subprocess\.PIPE is only valid with nursery\.start, since that's the only way to access the pipe; use nursery\.start or pass the data you want to write directly$" |
| 371 |
with pytest.raises(ValueError, match=pipe_stdin_error): |
| 372 |
await run_process(CAT, stdin=subprocess.PIPE) |
| 373 |
pipe_stdout_error = r"^stdout=subprocess\.PIPE is only valid with nursery\.start, since that's the only way to access the pipe$" |
| 374 |
with pytest.raises(ValueError, match=pipe_stdout_error): |
| 375 |
await run_process(CAT, stdout=subprocess.PIPE) |
| 376 |
with pytest.raises( |
| 377 |
ValueError, |
| 378 |
match=pipe_stdout_error.replace("stdout", "stderr", 1), |
| 379 |
): |
| 380 |
await run_process(CAT, stderr=subprocess.PIPE) |
| 381 |
with pytest.raises( |
| 382 |
ValueError, |
| 383 |
match=r"^can't specify both stdout and capture_stdout$", |
| 384 |
): |
| 385 |
await run_process(CAT, capture_stdout=True, stdout=subprocess.DEVNULL) |
| 386 |
with pytest.raises( |
| 387 |
ValueError, |
| 388 |
match=r"^can't specify both stderr and capture_stderr$", |
| 389 |
): |
| 390 |
await run_process(CAT, capture_stderr=True, stderr=None) |
| 391 |
|
| 392 |
|
| 393 |
async def test_run_check() -> None: |
| 394 |
cmd = python("sys.stderr.buffer.write(b'test\\n'); sys.exit(1)") |
| 395 |
with pytest.raises(subprocess.CalledProcessError) as excinfo: |
| 396 |
await run_process(cmd, stdin=subprocess.DEVNULL, capture_stderr=True) |
| 397 |
assert excinfo.value.cmd == cmd |
| 398 |
assert excinfo.value.returncode == 1 |
| 399 |
assert excinfo.value.stderr == b"test\n" |
| 400 |
assert excinfo.value.stdout is None |
| 401 |
|
| 402 |
result = await run_process( |
| 403 |
cmd, |
| 404 |
capture_stdout=True, |
| 405 |
capture_stderr=True, |
| 406 |
check=False, |
| 407 |
) |
| 408 |
assert result.args == cmd |
| 409 |
assert result.stdout == b"" |
| 410 |
assert result.stderr == b"test\n" |
| 411 |
assert result.returncode == 1 |
| 412 |
|
| 413 |
|
| 414 |
@skip_if_fbsd_pipes_broken |
| 415 |
async def test_run_with_broken_pipe() -> None: |
| 416 |
result = await run_process( |
| 417 |
[sys.executable, "-c", "import sys; sys.stdin.close()"], |
| 418 |
stdin=b"x" * 131072, |
| 419 |
) |
| 420 |
assert result.returncode == 0 |
| 421 |
assert result.stdout is result.stderr is None |
| 422 |
|
| 423 |
|
| 424 |
@background_process_param |
| 425 |
async def test_stderr_stdout(background_process: BackgroundProcessType) -> None: |
| 426 |
async with background_process( |
| 427 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR, |
| 428 |
stdin=subprocess.PIPE, |
| 429 |
stdout=subprocess.PIPE, |
| 430 |
stderr=subprocess.STDOUT, |
| 431 |
) as proc: |
| 432 |
assert proc.stdio is not None |
| 433 |
assert proc.stdout is not None |
| 434 |
assert proc.stderr is None |
| 435 |
await proc.stdio.send_all(b"1234") |
| 436 |
await proc.stdio.send_eof() |
| 437 |
|
| 438 |
output = [] |
| 439 |
while True: |
| 440 |
chunk = await proc.stdio.receive_some(16) |
| 441 |
if chunk == b"": |
| 442 |
break |
| 443 |
output.append(chunk) |
| 444 |
assert b"".join(output) == b"12344321" |
| 445 |
assert proc.returncode == 0 |
| 446 |
|
| 447 |
# equivalent test with run_process() |
| 448 |
result = await run_process( |
| 449 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR, |
| 450 |
stdin=b"1234", |
| 451 |
capture_stdout=True, |
| 452 |
stderr=subprocess.STDOUT, |
| 453 |
) |
| 454 |
assert result.returncode == 0 |
| 455 |
assert result.stdout == b"12344321" |
| 456 |
assert result.stderr is None |
| 457 |
|
| 458 |
# this one hits the branch where stderr=STDOUT but stdout |
| 459 |
# is not redirected |
| 460 |
async with background_process( |
| 461 |
CAT, |
| 462 |
stdin=subprocess.PIPE, |
| 463 |
stderr=subprocess.STDOUT, |
| 464 |
) as proc: |
| 465 |
assert proc.stdout is None |
| 466 |
assert proc.stderr is None |
| 467 |
await proc.stdin.aclose() |
| 468 |
await proc.wait() |
| 469 |
assert proc.returncode == 0 |
| 470 |
|
| 471 |
if posix: |
| 472 |
try: |
| 473 |
r, w = os.pipe() |
| 474 |
|
| 475 |
async with background_process( |
| 476 |
COPY_STDIN_TO_STDOUT_AND_BACKWARD_TO_STDERR, |
| 477 |
stdin=subprocess.PIPE, |
| 478 |
stdout=w, |
| 479 |
stderr=subprocess.STDOUT, |
| 480 |
) as proc: |
| 481 |
os.close(w) |
| 482 |
assert proc.stdio is None |
| 483 |
assert proc.stdout is None |
| 484 |
assert proc.stderr is None |
| 485 |
await proc.stdin.send_all(b"1234") |
| 486 |
await proc.stdin.aclose() |
| 487 |
assert await proc.wait() == 0 |
| 488 |
assert os.read(r, 4096) == b"12344321" |
| 489 |
assert os.read(r, 4096) == b"" |
| 490 |
finally: |
| 491 |
os.close(r) |
| 492 |
|
| 493 |
|
| 494 |
async def test_errors() -> None: |
| 495 |
with pytest.raises(TypeError) as excinfo: |
| 496 |
# call-overload on unix, call-arg on windows |
| 497 |
await open_process(["ls"], encoding="utf-8") # type: ignore |
| 498 |
assert "unbuffered byte streams" in str(excinfo.value) |
| 499 |
assert "the 'encoding' option is not supported" in str(excinfo.value) |
| 500 |
|
| 501 |
if posix: |
| 502 |
with pytest.raises(TypeError) as excinfo: |
| 503 |
await open_process(["ls"], shell=True) |
| 504 |
with pytest.raises(TypeError) as excinfo: |
| 505 |
await open_process("ls", shell=False) |
| 506 |
|
| 507 |
|
| 508 |
@background_process_param |
| 509 |
async def test_signals(background_process: BackgroundProcessType) -> None: |
| 510 |
async def test_one_signal( |
| 511 |
send_it: Callable[[Process], None], |
| 512 |
signum: signal.Signals | None, |
| 513 |
) -> None: |
| 514 |
with move_on_after(1.0) as scope: |
| 515 |
async with background_process(SLEEP(3600)) as proc: |
| 516 |
send_it(proc) |
| 517 |
await proc.wait() |
| 518 |
assert not scope.cancelled_caught |
| 519 |
if posix: |
| 520 |
assert signum is not None |
| 521 |
assert proc.returncode == -signum |
| 522 |
else: |
| 523 |
assert proc.returncode != 0 |
| 524 |
|
| 525 |
await test_one_signal(Process.kill, SIGKILL) |
| 526 |
await test_one_signal(Process.terminate, SIGTERM) |
| 527 |
# Test that we can send arbitrary signals. |
| 528 |
# |
| 529 |
# We used to use SIGINT here, but it turns out that the Python interpreter |
| 530 |
# has race conditions that can cause it to explode in weird ways if it |
| 531 |
# tries to handle SIGINT during startup. SIGUSR1's default disposition is |
| 532 |
# to terminate the target process, and Python doesn't try to do anything |
| 533 |
# clever to handle it. |
| 534 |
if (not TYPE_CHECKING and posix) or sys.platform != "win32": |
| 535 |
await test_one_signal(lambda proc: proc.send_signal(SIGUSR1), SIGUSR1) |
| 536 |
|
| 537 |
|
| 538 |
@pytest.mark.skipif(not posix, reason="POSIX specific") |
| 539 |
@background_process_param |
| 540 |
async def test_wait_reapable_fails(background_process: BackgroundProcessType) -> None: |
| 541 |
if TYPE_CHECKING and sys.platform == "win32": |
| 542 |
return |
| 543 |
old_sigchld = signal.signal(signal.SIGCHLD, signal.SIG_IGN) |
| 544 |
try: |
| 545 |
# With SIGCHLD disabled, the wait() syscall will wait for the |
| 546 |
# process to exit but then fail with ECHILD. Make sure we |
| 547 |
# support this case as the stdlib subprocess module does. |
| 548 |
async with background_process(SLEEP(3600)) as proc: |
| 549 |
async with _core.open_nursery() as nursery: |
| 550 |
nursery.start_soon(proc.wait) |
| 551 |
await wait_all_tasks_blocked() |
| 552 |
proc.kill() |
| 553 |
nursery.cancel_scope.deadline = _core.current_time() + 1.0 |
| 554 |
assert not nursery.cancel_scope.cancelled_caught |
| 555 |
assert proc.returncode == 0 # exit status unknowable, so... |
| 556 |
finally: |
| 557 |
signal.signal(signal.SIGCHLD, old_sigchld) |
| 558 |
|
| 559 |
|
| 560 |
@pytest.mark.skipif(not posix, reason="POSIX specific") |
| 561 |
@background_process_param |
| 562 |
async def test_wait_reapable_fails_no_pidfd( |
| 563 |
background_process: BackgroundProcessType, |
| 564 |
) -> None: |
| 565 |
if TYPE_CHECKING and sys.platform == "win32": |
| 566 |
return |
| 567 |
with mock.patch("trio._subprocess.can_try_pidfd_open", new=False): |
| 568 |
old_sigchld = signal.signal(signal.SIGCHLD, signal.SIG_IGN) |
| 569 |
try: |
| 570 |
# With SIGCHLD disabled, the wait() syscall will wait for the |
| 571 |
# process to exit but then fail with ECHILD. Make sure we |
| 572 |
# support this case as the stdlib subprocess module does. |
| 573 |
async with background_process(SLEEP(3600)) as proc: |
| 574 |
async with _core.open_nursery() as nursery: |
| 575 |
nursery.start_soon(proc.wait) |
| 576 |
await wait_all_tasks_blocked() |
| 577 |
proc.kill() |
| 578 |
nursery.cancel_scope.deadline = _core.current_time() + 1.0 |
| 579 |
assert not nursery.cancel_scope.cancelled_caught |
| 580 |
assert proc.returncode == 0 # exit status unknowable, so... |
| 581 |
finally: |
| 582 |
signal.signal(signal.SIGCHLD, old_sigchld) |
| 583 |
|
| 584 |
|
| 585 |
@slow |
| 586 |
def test_waitid_eintr() -> None: |
| 587 |
# This only matters on PyPy (where we're coding EINTR handling |
| 588 |
# ourselves) but the test works on all waitid platforms. |
| 589 |
from .._subprocess_platform import wait_child_exiting |
| 590 |
|
| 591 |
if TYPE_CHECKING and (sys.platform == "win32" or sys.platform == "darwin"): |
| 592 |
return |
| 593 |
|
| 594 |
if not wait_child_exiting.__module__.endswith("waitid"): |
| 595 |
pytest.skip("waitid only") |
| 596 |
|
| 597 |
# despite the TYPE_CHECKING early return silencing warnings about signal.SIGALRM etc |
| 598 |
# this import is still checked on win32&darwin and raises [attr-defined]. |
| 599 |
# Linux doesn't raise [attr-defined] though, so we need [unused-ignore] |
| 600 |
from .._subprocess_platform.waitid import ( # type: ignore[attr-defined, unused-ignore] |
| 601 |
sync_wait_reapable, |
| 602 |
) |
| 603 |
|
| 604 |
got_alarm = False |
| 605 |
sleeper = subprocess.Popen(["sleep", "3600"]) |
| 606 |
|
| 607 |
def on_alarm(sig: int, frame: FrameType | None) -> None: |
| 608 |
nonlocal got_alarm |
| 609 |
got_alarm = True |
| 610 |
sleeper.kill() |
| 611 |
|
| 612 |
old_sigalrm = signal.signal(signal.SIGALRM, on_alarm) |
| 613 |
try: |
| 614 |
signal.alarm(1) |
| 615 |
sync_wait_reapable(sleeper.pid) |
| 616 |
assert sleeper.wait(timeout=1) == -9 |
| 617 |
finally: |
| 618 |
if sleeper.returncode is None: # pragma: no cover |
| 619 |
# We only get here if something fails in the above; |
| 620 |
# if the test passes, wait() will reap the process |
| 621 |
sleeper.kill() |
| 622 |
sleeper.wait() |
| 623 |
signal.signal(signal.SIGALRM, old_sigalrm) |
| 624 |
|
| 625 |
|
| 626 |
async def test_custom_deliver_cancel() -> None: |
| 627 |
custom_deliver_cancel_called = False |
| 628 |
|
| 629 |
async def custom_deliver_cancel(proc: Process) -> None: |
| 630 |
nonlocal custom_deliver_cancel_called |
| 631 |
custom_deliver_cancel_called = True |
| 632 |
proc.terminate() |
| 633 |
# Make sure this does get cancelled when the process exits, and that |
| 634 |
# the process really exited. |
| 635 |
try: |
| 636 |
await sleep_forever() |
| 637 |
finally: |
| 638 |
assert proc.returncode is not None |
| 639 |
|
| 640 |
async with _core.open_nursery() as nursery: |
| 641 |
nursery.start_soon( |
| 642 |
partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel), |
| 643 |
) |
| 644 |
await wait_all_tasks_blocked() |
| 645 |
nursery.cancel_scope.cancel() |
| 646 |
|
| 647 |
assert custom_deliver_cancel_called |
| 648 |
|
| 649 |
|
| 650 |
def test_bad_deliver_cancel() -> None: |
| 651 |
async def custom_deliver_cancel(proc: Process) -> None: |
| 652 |
proc.terminate() |
| 653 |
raise ValueError("foo") |
| 654 |
|
| 655 |
async def do_stuff() -> None: |
| 656 |
async with _core.open_nursery() as nursery: |
| 657 |
nursery.start_soon( |
| 658 |
partial(run_process, SLEEP(9999), deliver_cancel=custom_deliver_cancel), |
| 659 |
) |
| 660 |
await wait_all_tasks_blocked() |
| 661 |
nursery.cancel_scope.cancel() |
| 662 |
|
| 663 |
# double wrap from our nursery + the internal nursery |
| 664 |
with pytest.RaisesGroup( |
| 665 |
pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="^foo$")) |
| 666 |
): |
| 667 |
_core.run(do_stuff, strict_exception_groups=True) |
| 668 |
|
| 669 |
|
| 670 |
async def test_warn_on_failed_cancel_terminate(monkeypatch: pytest.MonkeyPatch) -> None: |
| 671 |
original_terminate = Process.terminate |
| 672 |
|
| 673 |
def broken_terminate(self: Process) -> NoReturn: |
| 674 |
original_terminate(self) |
| 675 |
raise OSError("whoops") |
| 676 |
|
| 677 |
monkeypatch.setattr(Process, "terminate", broken_terminate) |
| 678 |
|
| 679 |
with pytest.warns(RuntimeWarning, match=".*whoops.*"): # noqa: PT031 |
| 680 |
async with _core.open_nursery() as nursery: |
| 681 |
nursery.start_soon(run_process, SLEEP(9999)) |
| 682 |
await wait_all_tasks_blocked() |
| 683 |
nursery.cancel_scope.cancel() |
| 684 |
|
| 685 |
|
| 686 |
@pytest.mark.skipif(not posix, reason="posix only") |
| 687 |
async def test_warn_on_cancel_SIGKILL_escalation( |
| 688 |
autojump_clock: MockClock, |
| 689 |
monkeypatch: pytest.MonkeyPatch, |
| 690 |
) -> None: |
| 691 |
monkeypatch.setattr(Process, "terminate", lambda *args: None) |
| 692 |
|
| 693 |
with pytest.warns(RuntimeWarning, match=".*ignored SIGTERM.*"): # noqa: PT031 |
| 694 |
async with _core.open_nursery() as nursery: |
| 695 |
nursery.start_soon(run_process, SLEEP(9999)) |
| 696 |
await wait_all_tasks_blocked() |
| 697 |
nursery.cancel_scope.cancel() |
| 698 |
|
| 699 |
|
| 700 |
# the background_process_param exercises a lot of run_process cases, but it uses |
| 701 |
# check=False, so lets have a test that uses check=True as well |
| 702 |
async def test_run_process_background_fail() -> None: |
| 703 |
with pytest.RaisesGroup(subprocess.CalledProcessError): |
| 704 |
async with _core.open_nursery() as nursery: |
| 705 |
value = await nursery.start(run_process, EXIT_FALSE) |
| 706 |
assert isinstance(value, Process) |
| 707 |
proc: Process = value |
| 708 |
assert proc.returncode == 1 |
| 709 |
|
| 710 |
|
| 711 |
@pytest.mark.skipif( |
| 712 |
not SyncPath("/dev/fd").exists(), |
| 713 |
reason="requires a way to iterate through open files", |
| 714 |
) |
| 715 |
async def test_for_leaking_fds() -> None: |
| 716 |
gc.collect() # address possible flakiness on PyPy |
| 717 |
|
| 718 |
starting_fds = set(SyncPath("/dev/fd").iterdir()) # noqa: ASYNC240 |
| 719 |
await run_process(EXIT_TRUE) |
| 720 |
assert set(SyncPath("/dev/fd").iterdir()) == starting_fds # noqa: ASYNC240 |
| 721 |
|
| 722 |
with pytest.raises(subprocess.CalledProcessError): |
| 723 |
await run_process(EXIT_FALSE) |
| 724 |
assert set(SyncPath("/dev/fd").iterdir()) == starting_fds # noqa: ASYNC240 |
| 725 |
|
| 726 |
with pytest.raises(PermissionError): |
| 727 |
await run_process(["/dev/fd/0"]) |
| 728 |
assert set(SyncPath("/dev/fd").iterdir()) == starting_fds # noqa: ASYNC240 |
| 729 |
|
| 730 |
|
| 731 |
async def test_run_process_internal_error(monkeypatch: pytest.MonkeyPatch) -> None: |
| 732 |
# There's probably less extreme ways of triggering errors inside the nursery |
| 733 |
# in run_process. |
| 734 |
async def very_broken_open(*args: object, **kwargs: object) -> str: |
| 735 |
return "oops" |
| 736 |
|
| 737 |
monkeypatch.setattr(trio._subprocess, "_open_process", very_broken_open) |
| 738 |
with pytest.RaisesGroup(AttributeError, AttributeError): |
| 739 |
await run_process(EXIT_TRUE, capture_stdout=True) |
| 740 |
|
| 741 |
|
| 742 |
# regression test for #2209 |
| 743 |
async def test_subprocess_pidfd_unnotified() -> None: |
| 744 |
noticed_exit = None |
| 745 |
|
| 746 |
async def wait_and_tell(proc: Process) -> None: |
| 747 |
nonlocal noticed_exit |
| 748 |
noticed_exit = Event() |
| 749 |
await proc.wait() |
| 750 |
noticed_exit.set() |
| 751 |
|
| 752 |
proc = await open_process(SLEEP(9999)) |
| 753 |
async with _core.open_nursery() as nursery: |
| 754 |
nursery.start_soon(wait_and_tell, proc) |
| 755 |
await wait_all_tasks_blocked() |
| 756 |
assert isinstance(noticed_exit, Event) |
| 757 |
proc.terminate() |
| 758 |
# without giving trio a chance to do so, |
| 759 |
with assert_no_checkpoints(): |
| 760 |
# wait until the process has actually exited; |
| 761 |
proc._proc.wait() |
| 762 |
# force a call to poll (that closes the pidfd on linux) |
| 763 |
proc.poll() |
| 764 |
with move_on_after(5): |
| 765 |
# Some platforms use threads to wait for exit, so it might take a bit |
| 766 |
# for everything to notice |
| 767 |
await noticed_exit.wait() |
| 768 |
assert noticed_exit.is_set(), "child task wasn't woken after poll, DEADLOCK" |