Search code examples
pythonasynchronousexceptionasync-awaitio

How to catch Python "coroutine was never awaited" warning and trigger an EXCEPTION


I'm writing a python test suite which makes frequent use of async io. As a result I have a number of test fixture functions which are defined as "async" and must be called with "await..." to be useful.

However, I frequently forget the "await" when writing a test. When the test is run, it may output quite a bit of logging information, and somewhere in the middle there will be a single line which says "RuntimeWarning: coroutine 'MyFixture.DoSomething' was never awaited".

It's easy to miss this warning in the log, and wonder why the test didn't do what it was supposed to.

Is it possible to turn this runtime warning into a fatal exception which will stop the execution in a really obvious way, or allow me to catch it and turn on a siren and flashing lights or something?

This seems like an obvious question, but I haven't found any answer by googling!


Solution

  • Quote from python docs.

    Warning control. Python’s warning machinery by default prints warning messages to sys.stderr.
    -Werror # Convert to exceptions

    When calling python from the command line, add -Werror to make all warnings (runtimewarning, deprecationwarning, etc) count as exceptions.
    This should turn your asynchronous runtimewarning into a runtimeerror (or exception, i'm not sure which).