def test_console_direct(): extension = ConsoleDirectEventHandler() with patch('sys.stdout') as stdout: event = StdoutLine(b'bytes line') extension((event, None)) assert stdout.buffer.write.call_count == 1 event = StdoutLine('string line') extension((event, None)) assert stdout.write.call_count == 1 stdout.buffer.write.reset_mock() stdout.write.reset_mock() extension(('unknown', None)) assert stdout.buffer.write.call_count == 0 assert stdout.write.call_count == 0 with patch('sys.stderr') as stderr: event = StderrLine(b'bytes line') extension((event, None)) assert stderr.buffer.write.call_count == 1 event = StderrLine('string line') extension((event, None)) assert stderr.write.call_count == 1 stderr.buffer.write.reset_mock() stderr.write.reset_mock() extension(('unknown', None)) assert stderr.buffer.write.call_count == 0 assert stderr.write.call_count == 0
def print(self, msg, *, file=None): # noqa: A003 """ Post a message event into the event queue. :param msg: The message :param file: The sink to write the message to. An argument of `None` or `sys.stdout` posts a `StdoutLine` event, `sys.stderr` posts a `StderrLine` event. """ if file is None or file == sys.stdout: data = StdoutLine(msg + '\n') elif file == sys.stderr: data = StderrLine(msg + '\n') else: assert False, 'Unknown file object: ' + str(file) self.context.put_event_into_queue(data)
async def __call__(self, *args, **kwargs): """ Perform the unit of work. The overview of the process: * Put a :class:`JobStarted` event into the queue * Pass the task context to the task * Invoke the task * In case the task is canceled return a :attribute:`SIGINT_RESULT` code * In case of an exception within the task put a :class:`StderrLine` event into the queue and re-raise the exception * Put a :class:`JobEnded` event into the queue :returns: The return code of the invoked task :raises Exception: Any exception the invoked task raises """ self.put_event_into_queue(JobStarted(self.task_context.pkg.name)) # replace function to use this job as the event context self.task_context.put_event_into_queue = self.put_event_into_queue self.task.set_context(context=self.task_context) rc = 0 try: rc = await self.task(*args, **kwargs) except CancelledError: rc = SIGINT_RESULT except Exception: rc = 1 self.put_event_into_queue( StderrLine(traceback.format_exc().encode())) raise finally: if self.returncode is None: self.returncode = rc or 0 self.put_event_into_queue( JobEnded(self.task_context.pkg.name, self.returncode)) return self.returncode
def stderr_callback(line): context.put_event_into_queue(StderrLine(line))