Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import unittest
- import x
- class Test(unittest.TestCase):
- def test_x(self):
- my_thread = x.ExceptionRaiser()
- # Test case should fail when thread is started and raises
- # an exception.
- my_thread.start()
- my_thread.join()
- if __name__ == '__main__':
- unittest.main()
- threading._format_exc = traceback.format_exc
- import threading
- import os
- class GlobalExceptionWatcher(object):
- def _store_excepthook(self):
- '''
- Uses as an exception handlers which stores any uncaught exceptions.
- '''
- formated_exc = self.__org_hook()
- self._exceptions.append(formated_exc)
- return formated_exc
- def __enter__(self):
- '''
- Register us to the hook.
- '''
- self._exceptions = []
- self.__org_hook = threading._format_exc
- threading._format_exc = self._store_excepthook
- def __exit__(self, type, value, traceback):
- '''
- Remove us from the hook, assure no exception were thrown.
- '''
- threading._format_exc = self.__org_hook
- if len(self._exceptions) != 0:
- tracebacks = os.linesep.join(self._exceptions)
- raise Exception('Exceptions in other threads: %s' % tracebacks)
- my_thread = x.ExceptionRaiser()
- # will fail when thread is started and raises an exception.
- with GlobalExceptionWatcher():
- my_thread.start()
- my_thread.join()
- from threading import Thread
- class ErrThread(Thread):
- """
- A subclass of Thread that will log store exceptions if the thread does
- not exit normally
- """
- def run(self):
- try:
- Thread.run(self)
- except Exception as self.err:
- pass
- else:
- self.err = None
- class TaskQueue(object):
- """
- A utility class to run ErrThread objects in parallel and raises and exception
- in the event that *any* of them fail.
- """
- def __init__(self, *tasks):
- self.threads = []
- for t in tasks:
- try:
- self.threads.append(ErrThread(**t)) ## passing in a dict of target and args
- except TypeError:
- self.threads.append(ErrThread(target=t))
- def run(self):
- for t in self.threads:
- t.start()
- for t in self.threads:
- t.join()
- if t.err:
- raise Exception('Thread %s failed with error: %s' % (t.name, t.err))
- proc.join()
- self.assertEqual(proc.exitcode, 0, 'Sub-process failed, check output for stack trace')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement