Skip to content
Advertisement

How to timeout an async test in pytest with fixture?

I am testing an async function that might get deadlocked. I tried to add a fixture to limit the function to only run for 5 seconds before raising a failure, but it hasn’t worked so far.

Setup:

JavaScript

Code:

JavaScript

Edit: Mikhail’s solution works fine. I can’t find a way to incorporate it into a fixture, though.

Advertisement

Answer

Convenient way to limit function (or block of code) with timeout is to use async-timeout module. You can use it inside your test function or, for example, create a decorator. Unlike with fixture it’ll allow to specify concrete time for each test:

JavaScript

It’s not hard to create decorator for concrete time (with_timeout_5 = partial(with_timeout, 5)).


I don’t know how to create texture (if you really need fixture), but code above can provide starting point. Also not sure if there’s a common way to achieve goal better.

Advertisement