def cpu_bound(task_id: Optional[int] = None, send_process_id: bool = False) -> str: """ CPU-bound operations will block the event loop: in general it is preferable to run them in a process pool. """ try: logger = getLogger(__name__) def hander(_signum: int, _frame: Optional[Any]) -> NoReturn: logger.info("CPU-bound: Terminate") raise Terminated() signal(SIGTERM, hander) process_id = os.getpid() print(process_id) logger.info("CPU-bound: process id = %d", process_id) if send_process_id: time.sleep(SECOND_SLEEP_FOR_TEST_MIDDLE) logger.info("CPU-bound: Send process id") LocalSocket.send(str(process_id)) logger.info("CPU-bound: Start") result = sum(i * i for i in range(10**7)) logger.debug("CPU-bound: Finish") logger.debug("%d %s", task_id, datetime.now()) return ("" if task_id is None else f"task_id: {task_id}, ") + f"result: {result}" except KeyboardInterrupt: logger.info("CPU-bound: KeyboardInterupt") raise
def test_keyboard_interrupt(self) -> None: """Tests keyboard interrupt and send response to pytest by socket when succeed.""" try: self.test() except BaseException as error: self.logger.exception(error) traceback.print_exc() LocalSocket.send("Test failed") raise else: LocalSocket.send("Test succeed") finally: asyncio.run(asyncio.sleep(10))
def example_use_case_cancel_repost_process_id( queue_sub: Optional["queue.Queue[LogRecord]"] = None, queue_main: Optional["queue.Queue[LogRecord]"] = None) -> None: """The example use case of ProcessTaskPoolExecutor for E2E testing in case of cancel.""" time.sleep(SECOND_SLEEP_FOR_TEST_SHORT) LocalSocket.send(str(os.getpid())) if queue_main: logger = getLogger() logger.addHandler(QueueHandler(queue_main)) logger.setLevel(DEBUG) results = example_use_case_method(queue_sub) results_string = repr(results) LocalSocket.send(results_string) pytest.fail(results_string)
def test_keyboard_interrupt_ctrl_c_new_process_group() -> None: """ see: - On Windows, what is the python launcher 'py' doing that lets control-C cross between process groups? https://stackoverflow.com/q/42180468/12721873 https://github.com/njsmith/appveyor-ctrl-c-test/blob/34e13fab9be56d59c3eba566e26d80505c309438/a.py https://github.com/njsmith/appveyor-ctrl-c-test/blob/34e13fab9be56d59c3eba566e26d80505c309438/run-a.py """ with Popen( f"{sys.executable} tests\\testlibraries\\keyboaard_interrupt_in_windows.py", # Reason: Definition of following constant is Windows only creationflags=CREATE_NEW_PROCESS_GROUP, # type: ignore ) as popen: asyncio.run(asyncio.sleep(SECOND_SLEEP_FOR_TEST_MIDDLE)) LocalSocket.send(str(popen.pid)) assert LocalSocket.receive() == "Test succeed" assert popen.wait() == 0
def report_raises_keyboard_interrupt() -> None: with pytest.raises(KeyboardInterrupt): example_use_case_cancel_repost_process_id() LocalSocket.send("Test succeed")