Bharel
Bharel

Reputation: 26901

How do I test async functions with doctest?

Example code:

async def test():
  """
  >>> await test()
  hello world
  """
  print("hello world")

Attempting to run this with doctests results in SyntaxError: 'await' outside function.

Upvotes: 9

Views: 913

Answers (1)

Bharel
Bharel

Reputation: 26901

Doctest runs the code in the code outside any function. You can't use await expressions outside of an async function.

In order to run async functions, you can use asyncio.run() like so:

import asyncio

async def test():
  """
  >>> asyncio.run(test())
  hello world
  """
  print("hello world")

Upvotes: 7

Related Questions