| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import locale |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import signal |
| 7 |
import sys |
| 8 |
from io import TextIOWrapper |
| 9 |
from pathlib import Path |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
from unittest.mock import MagicMock |
| 12 |
|
| 13 |
from tox.execute.local_sub_process import LocalSubProcessExecutor |
| 14 |
from tox.execute.request import ExecuteRequest, StdinSource |
| 15 |
from tox.report import NamedBytesIO |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from types import FrameType |
| 19 |
|
| 20 |
from tox.execute import Outcome |
| 21 |
|
| 22 |
logging.basicConfig(level=logging.DEBUG, format="%(relativeCreated)d\t%(levelname).1s\t%(message)s") |
| 23 |
bad_process = Path(__file__).parent / "bad_process.py" |
| 24 |
|
| 25 |
executor = LocalSubProcessExecutor(colored=False) |
| 26 |
request = ExecuteRequest( |
| 27 |
cmd=[sys.executable, bad_process, sys.argv[1]], |
| 28 |
cwd=Path().absolute(), |
| 29 |
env=os.environ.copy(), |
| 30 |
stdin=StdinSource.API, |
| 31 |
run_id="", |
| 32 |
) |
| 33 |
out_err = ( |
| 34 |
TextIOWrapper(NamedBytesIO("out"), encoding=locale.getpreferredencoding(False)), |
| 35 |
TextIOWrapper(NamedBytesIO("err"), encoding=locale.getpreferredencoding(False)), |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
def show_outcome(outcome: Outcome | None) -> None: |
| 40 |
if outcome is not None: # pragma: no branch |
| 41 |
print(outcome.exit_code) # noqa: T201 |
| 42 |
print(repr(outcome.out)) # noqa: T201 |
| 43 |
print(repr(outcome.err)) # noqa: T201 |
| 44 |
print(outcome.elapsed, end="") # noqa: T201 |
| 45 |
print("done show outcome", file=sys.stderr) # noqa: T201 |
| 46 |
|
| 47 |
|
| 48 |
def handler(s: int, f: FrameType | None) -> None: |
| 49 |
logging.info("signal %s at %s", s, f) |
| 50 |
global interrupt_done # noqa: PLW0603 |
| 51 |
if interrupt_done is False: # pragma: no branch |
| 52 |
interrupt_done = True |
| 53 |
logging.info("interrupt via %s", status) |
| 54 |
status.interrupt() |
| 55 |
logging.info("interrupt finished via %s", status) |
| 56 |
|
| 57 |
|
| 58 |
interrupt_done = False |
| 59 |
signal.signal(signal.SIGINT, handler) |
| 60 |
logging.info("PID %d start %r", os.getpid(), request) |
| 61 |
tox_env = MagicMock(conf={"suicide_timeout": 0.01, "interrupt_timeout": 0.05, "terminate_timeout": 0.07}) |
| 62 |
tox_env.options.no_capture = False |
| 63 |
try: |
| 64 |
with executor.call(request, show=False, out_err=out_err, env=tox_env) as status: |
| 65 |
logging.info("wait on %r", status) |
| 66 |
while status.exit_code is None: |
| 67 |
status.wait(timeout=0.01) # use wait here with timeout to not block the main thread |
| 68 |
logging.info("wait over on %r", status) |
| 69 |
show_outcome(status.outcome) |
| 70 |
except Exception as exception: # pragma: no cover |
| 71 |
logging.exception(exception) # noqa: TRY401 # pragma: no cover |
| 72 |
finally: |
| 73 |
logging.info("done") |
| 74 |
logging.shutdown() |