Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.42 KB | None | 0 0
  1. import unittest
  2. import x
  3.  
  4. class Test(unittest.TestCase):
  5. def test_x(self):
  6. my_thread = x.ExceptionRaiser()
  7. # Test case should fail when thread is started and raises
  8. # an exception.
  9. my_thread.start()
  10. my_thread.join()
  11.  
  12. if __name__ == '__main__':
  13. unittest.main()
  14.  
  15. threading._format_exc = traceback.format_exc
  16.  
  17. import threading
  18. import os
  19.  
  20. class GlobalExceptionWatcher(object):
  21. def _store_excepthook(self):
  22. '''
  23. Uses as an exception handlers which stores any uncaught exceptions.
  24. '''
  25. formated_exc = self.__org_hook()
  26. self._exceptions.append(formated_exc)
  27. return formated_exc
  28.  
  29. def __enter__(self):
  30. '''
  31. Register us to the hook.
  32. '''
  33. self._exceptions = []
  34. self.__org_hook = threading._format_exc
  35. threading._format_exc = self._store_excepthook
  36.  
  37. def __exit__(self, type, value, traceback):
  38. '''
  39. Remove us from the hook, assure no exception were thrown.
  40. '''
  41. threading._format_exc = self.__org_hook
  42. if len(self._exceptions) != 0:
  43. tracebacks = os.linesep.join(self._exceptions)
  44. raise Exception('Exceptions in other threads: %s' % tracebacks)
  45.  
  46. my_thread = x.ExceptionRaiser()
  47. # will fail when thread is started and raises an exception.
  48. with GlobalExceptionWatcher():
  49. my_thread.start()
  50. my_thread.join()
  51.  
  52. from threading import Thread
  53.  
  54. class ErrThread(Thread):
  55. """
  56. A subclass of Thread that will log store exceptions if the thread does
  57. not exit normally
  58. """
  59. def run(self):
  60. try:
  61. Thread.run(self)
  62. except Exception as self.err:
  63. pass
  64. else:
  65. self.err = None
  66.  
  67.  
  68. class TaskQueue(object):
  69. """
  70. A utility class to run ErrThread objects in parallel and raises and exception
  71. in the event that *any* of them fail.
  72. """
  73.  
  74. def __init__(self, *tasks):
  75.  
  76. self.threads = []
  77.  
  78. for t in tasks:
  79. try:
  80. self.threads.append(ErrThread(**t)) ## passing in a dict of target and args
  81. except TypeError:
  82. self.threads.append(ErrThread(target=t))
  83.  
  84. def run(self):
  85.  
  86. for t in self.threads:
  87. t.start()
  88. for t in self.threads:
  89. t.join()
  90. if t.err:
  91. raise Exception('Thread %s failed with error: %s' % (t.name, t.err))
  92.  
  93. proc.join()
  94. self.assertEqual(proc.exitcode, 0, 'Sub-process failed, check output for stack trace')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement