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+requests实现接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
一直走下去-明8 小时前
简单的http抓包解包完整代码
开发语言·python
雷帝木木8 小时前
数据湖与数据仓库:从理论到实践
人工智能·python·深度学习·机器学习
数字化转型分享点滴9 小时前
机加工车间上线 SH‑AIOT 物联网会遇到哪些常见实施难点
python·物联网
0566469 小时前
agent学习——流式响应与文本切分
网络·python·学习
OPEN-F9 小时前
Python进阶教程:正则表达式进阶与文本处理
开发语言·python·正则表达式
新网企兴10 小时前
2026年陕西做GEO推广,找新网企兴解决获客难题
python·搜索引擎
青 春 记 忆10 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
for_ever_love__10 小时前
python基础语法学习: 面向对象的三大特性
开发语言·python·学习
Spider赵毅10 小时前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup