Pytest对协程异步函数进行单元测试

安装

安装基础包 pytest,pytest-asyncio

python 复制代码
pip install pytest pytest-asyncio

测试:

python 复制代码
pytest -s -v ./python-code/do-async/aiohttp_session_pytest.py

书写规范

  1. 类名必须以 Test 开头
  2. 方法和函数名必须以test开头
python 复制代码
class  TestAddFunc(object):  # 测试用例的类名必须以 Test 为开头
    def test_01(self):  # 方法名和函数名必须以 test 为开头
        print(add(10,20))

    def test_02(self):
        print(add(10, 20))

    def test_03(self):
        print(add(10, 20))

运行

命令行运行:

格式:

复制代码
pytest -s  -v 文件名

# -s:输出测试用例中的print打印的信息
# -v: 输出测试用例的类名和方法名
# -x: 一旦发现测试用例失败,立即停止运行
# no:warnings: 不显示警告

通过Pycharm 运行:

直接点击左侧的绿色箭头,就能运行单元测试

通过pytest.main()运行:

格式:

python 复制代码
# pytest.main(["模块文件名::类名::方法名字","参数"])
pytest.main(["./demo/pytest_01.py","-sv"])
# pytest.main(["./demo/pytest_01.py::TestAddFunc","-sv"])
# pytest.main(["./demo/pytest_01.py::TestAddFunc::test_01","-sv"])
python 复制代码
if __name__ == '__main__':
    pytest.main(["./asyncio_session_pytest.py::TestAsyncioRequest::test_async_req_session", "-sv"])

总结

这是简单的pytest 测试协程异步的教程,主要是用来测试同步请求,aiohttp的session复用,不复用的请求性能比较,源码地址:
码云上

相关推荐
冷雨夜中漫步7 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴7 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再7 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手9 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934739 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy9 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
肖永威11 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ11 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha11 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy11 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法