-
I'm using a custom When I run my application normally, the excepthook works as expected import threading
def excepthook(args: threading.ExceptHookArgs):
print("what happens next is very important...")
threading.excepthook = excepthook
def foo():
raise ValueError("oh no!")
t = threading.Thread(target=foo)
t.start()
t.join() Output:
But when I try to test the same function with pytest, the excepthook is replaced with some import threading
def excepthook(args: threading.ExceptHookArgs):
print("what happens next is very important...")
threading.excepthook = excepthook
def test_excepthook():
def foo():
raise ValueError("oh no!")
t = threading.Thread(target=foo)
t.start()
t.join() Output:
It looks like this function is responsible and it gets added to each test function automatically. How can I prevent that from happening? Running pytest 6.2.4 on Python 3.8 on Windows. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
you can disable the plugin https://docs.pytest.org/en/6.2.x/usage.html#warning-about-unraisable-exceptions-and-unhandled-thread-exceptions with but rather than rely on global state, you could also refactor your application and test to set your thread hook in a context manager: import contextlib
import threading
@contextlib.contextmanager
def threadhook_context(new_hook):
old_hook, threading.excepthook = threading.excepthook, new_hook
try:
yield old_hook
finally:
assert threading.excepthook is new_hook
threading.excepthook = old_hook
def excepthook(args: threading.ExceptHookArgs):
print("what happens next is very important...")
def foo():
raise ValueError("oh no!")
def some_system_under_test():
with threadhook_context(excepthook):
t = threading.Thread(target=foo)
t.start()
t.join()
def test_excepthook(capsys):
assert some_system_under_test() is None
assert capsys.readouterr().out == "what happens next is very important...\n" this is how trio manages it: https://github.com/python-trio/trio/blob/289610534afb73ab34a982d846c040a8e39b3ed4/trio/_core/tests/tutil.py#L99-L109 |
Beta Was this translation helpful? Give feedback.
you can disable the plugin https://docs.pytest.org/en/6.2.x/usage.html#warning-about-unraisable-exceptions-and-unhandled-thread-exceptions with
-p no:threadexception
but rather than rely on global state, you could also refactor your application and test to set your thread hook in a context manager: