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)

运行结果:

相关推荐
GUET_一路向前4 分钟前
【C语言】解释形参void *data用法
c语言·开发语言·通用指针
skywalk816318 分钟前
转换一个python项目到moonbit,碰到报错输出:编译器对workflow.mbt文件中的类方法要求不一致的类型注解,导致无法正常编译
开发语言·moonbit·trae
三年呀1 小时前
**标题:发散创新之力,探索隐私计算的未来**隐私计算,作为当下数字化时代的热门话题,正受
python
R-G-B1 小时前
OpenCV Python——报错AttributeError: module ‘cv2‘ has no attribute ‘bgsegm‘,解决办法
人工智能·python·opencv·opencv python·attributeerror·module ‘cv2‘·no attribute
DavieLau1 小时前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
张人玉1 小时前
C#Encoding
开发语言·c#
Hard but lovely2 小时前
C++:stl-> list的模拟实现
开发语言·c++·stl·list
白露与泡影2 小时前
Spring容器初始化源码解析
java·python·spring
码界筑梦坊3 小时前
98-基于Python的网上厨房美食推荐系统
开发语言·python·美食
光爷不秃3 小时前
Go语言中安全停止Goroutine的三种方法及设计哲学
开发语言·安全·golang