Search code examples
windowspytesttimeout

How to make pytest timeout fail test instead of stopping whole run on windows?


I wonder if there is a possibility for pytest-timeout(or any other solution) to fail timed out test instead of dropping whole run? Pytest-timeout has timeout method signal which accomplishes exactly what I need but only on Unix systems. Is there anything that might give me same behaviour on windows?


Solution

  • You can create your own timeout decorator

    from threading import Thread
    import functools
    
    
    def timeout(seconds):
        def deco(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, seconds))]
    
                def new_func():
                    try:
                        res[0] = func(*args, **kwargs)
                    except Exception as e:
                        res[0] = e
    
                t = Thread(target=new_func)
                t.daemon = True
                try:
                    t.start()
                    t.join(seconds)
                except Exception as je:
                    print('error starting thread')
                    raise je
                ret = res[0]
                if isinstance(ret, BaseException):
                    raise ret
                return ret
    
            return wrapper
    
        return deco
    
    @timeout(2)
    def test_x():
        ...