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

相关推荐
Polar__Star16 小时前
如何结合计划任务实现自动定时备份任务配置_全自动化运维管理
jvm·数据库·python
weixin_5806140021 小时前
如何提取SQL日期中的年份_使用YEAR或EXTRACT函数
jvm·数据库·python
2301_8135995521 小时前
SQL生产环境规范_数据库使用最佳实践
jvm·数据库·python
李可以量化21 小时前
QMT 量化实战:用 Python 实现线性回归通道,精准识别趋势中的支撑与压力(下)
python·qmt·量化 qmt ptrade
a9511416421 天前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
Dxy12393102161 天前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
qq_189807031 天前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
zhangchaoxies1 天前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python
Luca_kill1 天前
MCP数据采集革命:从传统爬虫到智能代理的技术进化
爬虫·python·ai·数据采集·mcp·webscraping·集蜂云
zhangchaoxies1 天前
CSS如何实现响应式弹性网格布局_配合media query修改flex-wrap属性
jvm·数据库·python