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

相关推荐
逻极4 分钟前
Scikit-learn 实战:15 分钟构建生产级中国房价预测模型
python·机器学习·scikit-learn
行板Andante6 分钟前
AttributeError: ‘super‘ object has no attribute ‘sklearn_tags‘解决
人工智能·python·sklearn
tryCbest9 分钟前
Python基础之爬虫技术(一)
开发语言·爬虫·python
husterlichf10 分钟前
逻辑回归以及python(sklearn)详解
python·逻辑回归·sklearn
AI小云20 分钟前
【Numpy数据运算】数组间运算
开发语言·python·numpy
q***783737 分钟前
【玩转全栈】----Django制作部门管理页面
后端·python·django
CoderIsArt1 小时前
抽象语法树AST与python的Demo实现
python
郝开2 小时前
Spring Boot 2.7.18(最终 2.x 系列版本)3 - 枚举规范定义:定义基础枚举接口;定义枚举工具类;示例枚举
spring boot·后端·python·枚举·enum
钅日 勿 XiName3 小时前
一小时速通Pytorch之自动梯度(Autograd)和计算图(Computational Graph)(二)
人工智能·pytorch·python
故林丶3 小时前
【Django】Django笔记
python·django