Python 1.Pytest 介绍和安装

Maple · 2020年12月24日 · 1336 次阅读

pytest 介绍

pytest 是 python 的一种单元测试框架,与 python 自带的 unittest 测试框架类似,但是比 unittest 框架使用起来更简洁,效率更高

  1. 非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考

  2. 能够支持简单的单元测试和复杂的功能测试

  3. 支持参数化

  4. 执行测试过程中可以将某些测试跳过,或者对某些预期失败的 case 标记成失败

  5. 支持重复执行失败的 case

  6. 支持运行由 nose, unittest 编写的测试 case

  7. 具有很多第三方插件,并且可以自定义扩展

pytest 安装

执行命令pip install pytest

安装完成后,查看 pytest 版本:pytest --version

能够看到 pytest 版本,表示安装成功

第一个 pytest 案例

# filename:test_01.py
import pytest


def func(x):
    return x + 1


def test_answer():
    assert func(3) == 4

def test_answer1():
    assert func(3) == 5

if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])

在 test_01.py 同级目录下,直接执行pytest

============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\auto-pytest
collected 2 items

test_01.py .F

================================== FAILURES ===================================
________________________________ test_answer1 _________________________________

    def test_answer1():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_01.py:13: AssertionError
=========================== short test summary info ===========================
FAILED test_01.py::test_answer1 - assert 4 == 5
========================= 1 failed, 1 passed in 0.08s =========================

第一个测试用例 passed,第二个测试用例 failed

也可使用命令行运行:pytest test_01.py,同样可以执行测试

pytest 注意

命名原则

  • 测试用例文件名必须以test_*.py*_test.py开头或结尾
  • 如果有类名,必须以 Test 开头,没有__init__函数,测试方法名以 test_开头的函数
  • 没有类,那么以函数为单位的函数名必须以 test_开头
  • 文件夹(包名)名可以随意命名
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册