I'm testing my Python software using Pytest.
I have to call many async
function and sometimes my tests pass even when I forgot to write the await
keyword.
I would like my test to automatically fail if I call an async
function without await
.
I was thinking about a decorator to add at the top of my tests, something like
async def func():
return 42
@checkawait
async def test_await():
func() # <-- forgot to await
I would like this test to fail with the decorator, because func
is an async function that was never awaited.
(I know this is not a proper test, since I'm not testing anything. It's just an example).
Without the decorator test_await
passes.
I really don't know what to do.
I asked chatGPT which told me to use this
def checkawait(test):
@functools.wraps(test)
async def wrapper(*args, **kwargs):
coros = []
res = test(*args, **kwargs)
if asyncio.iscoroutine(res):
coros.append(res)
while coros:
done, coros = await asyncio.wait(coros, timeout=0.1)
if not done:
raise Exception("Not all coroutines have completed")
return res
return wrapper
which, of course, is not working.
Does anyone have any ideas? Is it even possible to do so? Thanks