python - 我可以让 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')
等一年我明明不能测试,但理论上能做到吗?
解决方案
您还可以通过编写单元测试和模拟协程来测试它。
# 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。
推荐阅读
- excel - 使用 Find 在行中查找某些文本,然后在满足某些条件时从下面的行中提取数据
- java - 在 Win 10 的命令行中使用 Java 开关
- mysql - < created_at 的 mysql 索引而不是 in
- sql - 循环从一个表中选择查询结果并在同一个表中更新列
- ios - 让当前用户删除一个 firebase 孩子
- c++ - 实现 std::iter_difference_t
- vue.js - 动态道具对象的计算属性
- forms - 如何更改选择器下划线的颜色?
- python - 在 main.py 中使用时导入模块抛出错误,但在项目之外工作
- java - 如何使用不同元素的属性为 ios 应用程序创建 xpath