Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest failure in a separate thread

We're adapting pytest for our integration testing, and trying to use pytest fixtures to spawn some background test environment monitoring using separate threads.

The monitor threads have no problem launching at startup when we use the fixture, but I haven't found a way for pytest to fail the main test if one of the background monitor threads detects a problem.

Does anyone know a nice way to accomplish this in pytest? Is there any hook that we could use in the main pytest thread to catch a pytest.fail being called in one of our background monitor threads?

Thanks!

like image 360
Keir Jackson Avatar asked May 04 '17 19:05

Keir Jackson


2 Answers

In case the spawning of threads can not be customized, here's a little pytest plugin to capture exceptions raised in other threads and re-raise them in the main thread. It provides a reraise fixture that can be used as a context manager to capture exceptions:

from threading import Thread

def test_assert(reraise):

    def run():
        with reraise:
            assert False

    Thread(target=run).start()
like image 112
bjoluc Avatar answered Oct 19 '22 15:10

bjoluc


For future reference, this is a solution I used:

https://gist.github.com/sbrugman/59b3535ebcd5aa0e2598293cfa58b6ab

We wrap certain parts of threading.Thread to propagate exceptions. Note that this works when you have access to the location where the thread is spawned.

like image 42
Simon Avatar answered Oct 19 '22 14:10

Simon