1

I'm running into the RuntimeError: await wasn't used with future in a simple pytest. I have the pytest_twisted plugin enabled with the argument --reactor asyncio. I can see that twisted is using asyncio and all my twisted tests run fine. However, this code gives me the above error.

async def _sleep():
    await asyncio.sleep(1.0)


@defer.inlineCallbacks
def test_sleep():
    yield defer.ensureDeferred(_sleep())

It's just a simple test case to see if I can mix asyncio and twisted code together. The full stack trace is as follows:

Traceback (most recent call last):
  File "test/test_simple.py", line 23, in test_sleep
    yield defer.ensureDeferred(_sleep())
  File "/usr/local/lib/python3.10/site-packages/twisted/internet/defer.py", line 1697, in _inlineCallbacks
    result = context.run(gen.send, result)
  File "test/test_cli.py", line 18, in _sleep
    await asyncio.sleep(1.0)
  File "/usr/local/lib/python3.10/asyncio/tasks.py", line 605, in sleep
    return await future
RuntimeError: await wasn't used with future

Anything obvious jump out?

Twisted: 22.10.0
Python: 3.10.11
pytest: 7.3.1
pytest_twisted: 1.14.0
robert_difalco
  • 4,821
  • 4
  • 36
  • 58

1 Answers1

0

When writing a test using pytest-twisted you should use pytest_twisted.inlineCallbacks instead of twisted.internet.defer.inlineCallbacks or you should write your tests using async/await instead of inlineCallbacks/yield and decorate them with twisted.internet.defer.ensureDeferred.

The reason for this is largely "obscure implementation details" that aren't generally interesting, just a consequence of the specific way that pytest-twisted integrates pytest and Twisted.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • Thanks but that still has nothing to do with the issue in the question. I actually figured it out and I'll post an answer when I get some time tomorrow. You essentially have to turn coroutines into futures and then once they are async futures, you can turn then into twisted Deferreds. Then you can use them along side twisted. Tests work great whether you use `pytest_twisted.inlineCallbacks` or `twisted.internet.defer.inlineCallbacks`. It used to be that you had to use the pytest decorator but only if your method took fixtures. – robert_difalco May 11 '23 at 06:22
  • @robert_difalco can you please post it? I feel like pytest-twisted can't run asyncio tasks, but maybe I'm missing something. – wRAR Jun 09 '23 at 10:38