如何使用 doctest 测试异步函数?

Bha*_*rel 8 doctest python-3.x python-asyncio

示例代码:

async def test():
  """
  >>> await test()
  hello world
  """
  print("hello world")
Run Code Online (Sandbox Code Playgroud)

尝试使用 doctests 运行它会导致SyntaxError: 'await' outside function.

Bha*_*rel 7

Doctest 在任何函数之外的代码中运行代码。您不能在异步函数之外使用await 表达式。

为了运行异步函数,您可以asyncio.run()像这样使用:

import asyncio

async def test():
  """
  >>> asyncio.run(test())
  hello world
  """
  print("hello world")
Run Code Online (Sandbox Code Playgroud)