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复用,不复用的请求性能比较,源码地址:
码云上

相关推荐
千寻girling41 分钟前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook4 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风5 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风5 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei21 小时前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员