Pytest running indefinitely with threads

Viewed 292

I am using PyTest to perform some unit testing for a personal project. The pytest calls a class that initialises multiple threads. As these threads run indefinitely they never close and pytest never terminates, meaning my gitlab pipeline that runs the testing automatically fails. Threads are essential to testing and mocking the calling of these threads will not solve the issue in this instance.

Is there a way to configure PyTest to terminate all subthreads on pass or fail? Or is there a way I can implement this behaviour using some bash trickery?

Thanks in advance for any assistance.

E.g

Class A:
def  __init__():
    thread.start(C, daemon=True)
thread.start(D, daemon=True)
…   

Class B:
    def  __init__():
        Self.a = A()
    
    def example(self, inp):
        return self.a.function(inp)

test_B_example()
    assert a.function(“test”)

PyTest test_B_example -> Runs forever despite having passed.

Tried adding sys.exit() to python code to terminate the code after all tests have been executed but did not work.

1 Answers

Had the same problem and could solve it, by just letting the thread run as a daemon:

fred = threading.Thread(target=self.updater, args=(1,))
fred.daemon = True
fred.start()
Related