目录
简介
pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高
-
非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
-
能够支持简单的单元测试和复杂的功能测试
-
支持参数化
-
执行测试过程中可以将某些测试跳过,或者对某些预期失败的case标记成失败
-
支持重复执行失败的case
-
支持运行由nose, unittest编写的测试case
-
具有很多第三方插件,并且可以自定义扩展
-
requests是python知名的http爬虫库,同样简单易用,是python开源项目的TOP10。
-
本文主要介绍requests项目如何使用pytest进行单元测试,希望达到下面3个目标:
- 熟练pytest的使用
- 学习如何对项目进行单元测试
- 深入requests的一些实现细节
一、requests项目单元测试状况
requests的单元测试代码全部在 tests 目录,使用 pytest.ini 进行配置。测试除pytest
外,还需要安装:
库名 | 描述 |
---|---|
httpbin | 一个使用flask实现的http服务,可以客户端定义http响应,主要用于测试http协议 |
pytest-httpbin | pytest的插件,封装httpbin的实现 |
pytest-mock | pytest的插件,提供mock |
pytest-cov | pytest的插件,提供覆盖率 |
上述依赖
master
版本在requirement-dev文件中定义;2.24.0
版本会在pipenv中定义。
测试用例使用make命令,子命令在Makefile中定义, 使用make ci
运行所有单元测试结果如下:
$ make ci
pytest tests --junitxml=report.xml
======================================================================================================= test session starts =======================================================================================================
platform linux -- Python 3.6.8, pytest-3.10.1, py-1.10.0, pluggy-0.13.1
rootdir: /home/work6/project/requests, inifile: pytest.ini
plugins: mock-2.0.0, httpbin-1.0.0, cov-2.9.0
collected 552 items
tests/test_help.py ... [ 0%]
tests/test_hooks.py ... [ 1%]
tests/test_lowlevel.py ............... [ 3%]
tests/test_packages.py ... [ 4%]
tests/test_requests.py .................................................................................................................................................................................................... [ 39%]
127.0.0.1 - - [10/Aug/2021 08:41:53] "GET /stream/4 HTTP/1.1" 200 756
.127.0.0.1 - - [10/Aug/2021 08:41:53] "GET /stream/4 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46048)
Traceback (most recent call last):
File "/usr/lib64/python3.6/wsgiref/handlers.py", line 138, in run
self.finish_response()
x......................................................................................... [ 56%]
tests/test_structures.py .................... [ 59%]
tests/test_testserver.py ......s....