pytest-asyncio:协程异步测试案例

简介:pytest-asyncio是一个pytest插件。它便于测试使用异步库的代码。具体来说,pytest-asyncio提供了对作为测试函数的协同程序的支持。这允许用户在测试中等待代码。

历史攻略:

asyncio并发访问websocket

Python:协程 - 快速创建三步骤

Python:获取协程返回值的四种方式

Python:多进程,多线程,协程基础案例

Python:aiomultiprocess实现协程与多进程的强强联合

安装:

pip install pytest-asyncio

使用案例:aysncio_demo.py

# -*- coding: utf-8 -*-
# time: 2024/4/5 12:06
# file: asyncio_demo.py
# 公众号: 玩转测试开发

import asyncio
import datetime


async def do_somethings(user):
    # 1、定义协程函数
    print(f"{user} is do_somethings. the time is {datetime.datetime.now()}")
    await asyncio.sleep(0.1)
    return user + " is finish do_somethings."


async def do_another(user):
    print(f"{user} is do_another. the time is {datetime.datetime.now()}")
    await asyncio.sleep(0.2)
    return user + " is finish do_another."


async def do_others(user):
    print(f"{user} is do_others. the time is {datetime.datetime.now()}")
    return user + " is finish do_others."


if __name__ == '__main__':
    # 3、加入事件循环。
    tasks = []
    for i in range(3):
        tasks.append(do_somethings("tom"))
        tasks.append(do_another("ken"))
        tasks.append(do_others("lily"))

    asyncio.run(asyncio.wait(tasks))

test_demo.py

# -*- coding: utf-8 -*-
# time: 2024/3/31 10:34
# file: test_demo.py
# 公众号: 玩转测试开发
import sys
import pytest
from lib.asyncio_demo import do_somethings, do_another, do_others
from logger import log


@pytest.mark.asyncio
async def test_do_somethings():
    user = "tom"
    res = await do_somethings(user)
    log.info(f"{res}")
    pytest.assume(user + " is finish do_somethings." in res)


@pytest.mark.asyncio
async def test_do_another():
    user = "ken"
    res = await do_another(user)
    log.info(f"{res}")
    pytest.assume(user + " is finish do_another." in res)


@pytest.mark.asyncio
async def test_do_others():
    user = "lily"
    res = await do_others(user)
    log.info(f"{res}")
    
    # 此次故意放一个错误试试。
    pytest.assume(user + " is finish do_others." not in res)

运行结果:

相关推荐
架构文摘JGWZ15 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
FreakStudio16 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
leon62516 分钟前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
锦亦之22331 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏1 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2331 小时前
c++ static(详解)
开发语言·c++
菜菜想进步1 小时前
内存管理(C++版)
c语言·开发语言·c++
2301_789985941 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习
知星小度S1 小时前
C语言——自定义类型
c语言·开发语言
redcocal1 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘