"""Owned Python children can be cancelled and collected without waiting for run timeout.""" import os from pathlib import Path import signal import sys import tempfile import threading import time import unittest from unittest.mock import Mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import processes class ProcessCancellationTests(unittest.TestCase): @unittest.skipIf(os.name == "nt", "POSIX process-group signal contract") def test_cancellation_kills_silent_term_ignoring_descendant_after_parent_exits(self): with tempfile.TemporaryDirectory() as directory: heartbeat = Path(directory) / "heartbeat.txt" descendant = ("import os,signal,time\nfrom pathlib import Path\n" "signal.signal(signal.SIGTERM, signal.SIG_IGN)\nos.close(1)\nos.close(2)\n" f"path=Path({str(heartbeat)!r})\n" "while True:\n path.write_text(str(time.monotonic()))\n time.sleep(.02)\n") child = ("import os,subprocess,sys,time\nfrom pathlib import Path\n" f"subprocess.Popen([sys.executable, '-c', {descendant!r}])\n" f"path=Path({str(heartbeat)!r})\n" "while not path.exists(): time.sleep(.01)\n" "print('parent-ready:'+str(os.getpid()), flush=True)\ntime.sleep(60)\n") cancellation, group, observed = threading.Event(), [], [] def observe(stream, chunk): if stream == "stdout": observed.append(chunk) if "\n" in "".join(observed): group.append(int("".join(observed).split("parent-ready:", 1)[1].split()[0])) cancellation.set() try: result = processes.run_process([sys.executable, "-u", "-c", child], timeout=10, cleanup_timeout=.25, cancellation_event=cancellation, observer=observe) self.assertTrue(result.cancelled) self.assertEqual(result.returncode, -signal.SIGTERM) first = heartbeat.read_text() time.sleep(.2) self.assertEqual(heartbeat.read_text(), first, "silent same-group descendant must stop after parent collection") finally: if group: try: os.killpg(group[0], signal.SIGKILL) except ProcessLookupError: pass @unittest.skipIf(os.name == "nt", "POSIX process-group signal contract") def test_cancellation_kills_and_collects_owned_python_group_and_retains_result(self): cancellation = threading.Event() child = ("import signal,subprocess,sys,time\n" "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n" "print('parent-ready', flush=True)\n" "time.sleep(60)\n") def observe(stream, chunk): if stream == "stdout" and "parent-ready" in chunk: cancellation.set() started = time.monotonic() result = processes.run_process([sys.executable, "-u", "-c", child], timeout=20, cleanup_timeout=.25, cancellation_event=cancellation, observer=observe) self.assertTrue(result.cancelled) self.assertFalse(result.timed_out) self.assertEqual(result.returncode, -signal.SIGKILL) self.assertIn("parent-ready", result.stdout) self.assertLess(time.monotonic() - started, 4) def test_invalid_cancellation_signal_is_rejected_before_start(self): factory = Mock() with self.assertRaises(processes.ProcessError): processes.run_process([sys.executable, "-c", "pass"], timeout=1, cancellation_event=object(), popen=factory) factory.assert_not_called() if __name__ == "__main__": unittest.main()