Last active
September 7, 2021 08:44
-
-
Save sbrugman/59b3535ebcd5aa0e2598293cfa58b6ab to your computer and use it in GitHub Desktop.
Wrapper around Python's thread that propages exceptions (pytest).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
class TestableThread(threading.Thread): | |
"""Wrapper around `threading.Thread` that propagates exceptions.""" | |
def __init__(self, target, args): | |
super().__init__(self, target=target, args=args) | |
self.exc = None | |
def run(self): | |
"""Method representing the thread's activity. | |
You may override this method in a subclass. The standard run() method | |
invokes the callable object passed to the object's constructor as the | |
target argument, if any, with sequential and keyword arguments taken | |
from the args and kwargs arguments, respectively. | |
""" | |
try: | |
super().run(self) | |
except BaseException as e: | |
self.exc = e | |
finally: | |
del self._target, self._args, self._kwargs | |
def join(self, timeout=None): | |
"""Wait until the thread terminates. | |
This blocks the calling thread until the thread whose join() method is | |
called terminates -- either normally or through an unhandled exception | |
or until the optional timeout occurs. | |
When the timeout argument is present and not None, it should be a | |
floating point number specifying a timeout for the operation in seconds | |
(or fractions thereof). As join() always returns None, you must call | |
is_alive() after join() to decide whether a timeout happened -- if the | |
thread is still alive, the join() call timed out. | |
When the timeout argument is not present or None, the operation will | |
block until the thread terminates. | |
A thread can be join()ed many times. | |
join() raises a RuntimeError if an attempt is made to join the current | |
thread as that would cause a deadlock. It is also an error to join() a | |
thread before it has been started and attempts to do so raises the same | |
exception. | |
""" | |
super().join(timeout) | |
if self.exc: | |
raise self.exc |
The more generic and updated to Python3 version:
class TestableThread(Thread):
"""
Wrapper around `threading.Thread` that propagates exceptions.
REF: https://gist.github.com/sbrugman/59b3535ebcd5aa0e2598293cfa58b6ab
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.exc = None
def run(self):
try:
super().run()
except BaseException as e:
self.exc = e
finally:
del self._target, self._args, self._kwargs
def join(self, timeout=None):
super().join(timeout)
if self.exc:
raise self.exc
Slightly adapted the above to use it in a pytest fixture and get rid of unnecessarily green tests. This also works for threads that you never call join() on.
@pytest.fixture(autouse=True, scope="function")
def error_on_raise_in_thread():
"""
Replaces Thread with a a wrapper to record any exceptions and re-raise them after test execution.
In case multiple threads raise exceptions only one will be raised.
"""
last_exception = None
class ThreadWrapper(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self):
try:
super().run()
except BaseException as e:
nonlocal last_exception
last_exception = e
with patch('threading.Thread', ThreadWrapper):
yield
if last_exception:
raise last_exception
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful implementation, thank you for sharing it.