1、pytest 的特点
(1) 非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
(2) 能够支持简单的单元测试和复杂的功能测试
(3) 支持参数化
(4) 执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记成失败
(5) 支持重复执行(rerun)失败的 case
(6) 支持运行由 nose, unittest 编写的测试 case
(7) 可生成 html 报告
(8) 方便的和持续集成工具 jenkins 集成
(9) 可支持执行部分用例
(10) 具有很多第三方插件,并且可以自定义扩展
2、pytest 的安装
执行如下命令进行安装
pip install pytest
使用如下命令查看安装pytest的版本
pytest --version
如下:

3、创建第一个测试用例
- 新建一个test_example.pywenjian ,内容编写如下:
def add(a,b):
return a+b
def test_add():
assert(add(10,20)==50)
-
在命令行执行 pytest
执行结果如下:
(demo) (base) [[email protected] demo]# pytest
========================================================================== test session starts ==========================================================================
platform linux -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /opt/demo
plugins: metadata-1.11.0, html-3.1.1
collected 1 item
test_example.py F [100%]
=============================================================================== FAILURES ================================================================================
_______________________________________________________________________________ test_add ________________________________________________________________________________
def test_add():
> assert(add(10,20)==50)
E assert 30 == 50
E + where 30 = add(10, 20)
test_example.py:5: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_example.py::test_add - assert 30 == 50
=========================================================================== 1 failed in 0.02s ===========================================================================
(demo) (base) [[email protected] demo]#