Skip to content

Pytest

Pytest是一款Python测试框架,支持参数化与测试编排功能,对其他测试框架(例如Nose、UnitTest等)也能完全兼容。

支持第三方插件

1、pytest-html用于生成完善的HTML测试报告

2、pytest-rerunfailures用于重试失败的测试

3、pytest-xdist用于多CPU并发执行等

安装

shell
pip install pytest

示例

python
class TestClass:
   def test_char_in_string(self):
       string = "this"
       char = "h"
       assert char in string

   def test_calculation(self):
       result = 20 + 21
       assert 41 == result

编写规则说明

  • 测试文件的名称以test开头(或以_test结尾)
  • 测试类的名称以Test开头,并且不能带有__init__方法,例如“class Testxxxx:”
  • 测试函数的名称以test_开头,例如“def test_xxxx():”
  • 断言使用基本的assert {表达式}即可

执行测试用例

1、执行所有测试用例

shell
pytest

2、执行指定测试文件中的所有测试

shell
pytest test_example.py

3、执行指定测试类中的所有测试

shell
pytest test_example.py::Testxxx

4、执行指定测试函数

shell
pytest test_example.py::Testxxx::test_xxx

常用命令

1、查看所有测试用例的结果

shell
pytest -v

2、查看整体测试结果

shell
pytest -q

3、输出测试函数中print打印的结果

python
pytest -s