首页 > 解决方案 > 我可以让 asyncio.sleep() 睡一年吗?

问题描述

asyncio.sleep()想睡一年。

像这样的东西:

async def run():
  # first print
  print('hi')
  # wait a year
  await asyncio.sleep(31536000)
  # second print
  print('hi after a year')

等一年我明明不能测试,但理论上能做到吗?

标签: pythonpython-3.xpython-asyncio

解决方案


您还可以通过编写单元测试和模拟协程来测试它。

# file1.py
async def run(seconds):
  # first print
  print('hi')
  # wait a year
  await asyncio.sleep(seconds)
  # second print
  print('hi after a year')
# test_file1.py

import asyncio
from unittest import mock
from unittest.mock import patch

import pytest

import file1


class AsyncMock(mock.MagicMock):
    async def __call__(self, *args, **kwargs):
        return super(AsyncMock, self).__call__(*args, **kwargs)


class TestAsyncioSleep:
    @patch('file1.run', new_callable=AsyncMock)
    def test_fun(self, sleep_mock):
        event_loop = asyncio.get_event_loop()
        task = event_loop.run_until_complete(so_async.run(31536000))
        sleep_mock.assert_called_with(31536000)

我正在用 AsyncMock() 类模拟 asyncio.sleep。


推荐阅读