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)

运行结果:

相关推荐
只睡四小时1 分钟前
LoAF 归因:原生 JS 每次输入 201 次布局读取
开发语言·javascript·性能优化·ecmascript·甘特图·前端性能·loaf
Elaine33614 分钟前
【图解进程、线程与协程:从任务执行到并发与并行】
python·操作系统·多线程·协程·多进程
ShineWinsu22 分钟前
对于Qt:QMediaPlayer和QVideoWidget的解析
开发语言·c++·qt·视频·客户端·qmediaplayer·媒体播放器
开开心心_Every26 分钟前
安卓手写文字生成工具,多种纸张一直免费
服务器·开发语言·jupyter·智能手机·计算机外设·vim·php
Thanks_ks27 分钟前
Python 函数参数:位置参数、关键字参数与解包规则
python·函数参数·位置参数·关键字参数·星号解包·仅位置参数·仅关键字参数
IT小小猪27 分钟前
录音转文字做成流水线:一套规范 + 质检脚本 + 自动排版,34 分钟音频出 25 页 PDF
运维·人工智能·python
爱写代码的倒霉蛋30 分钟前
长鑫AI应用开发面经(一面)
python
打工仔折腾 AI40 分钟前
C++ AI SDK(十):DataManager的数据库读写、事务与一致性设计
开发语言·数据库·c++·人工智能·后端·python·性能优化
benchmark_cc1 小时前
vn.py 如何接入 A 股历史行情?使用 QuantDash 映射 BarData 并导入回测数据库
开发语言·数据库·python·pandas·量化交易·股票数据·quantdash
ZZzzhh75851 小时前
Spark日志事件聚合分析实战:从HDFS读取到分布式聚合与可视化
大数据·python·hdfs·spark·pandas