python-pytest快速开始

pytest 介绍

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

根据pytest的官方网站介绍,它具有如下特点:

  • 非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
  • 能够支持简单的单元测试和复杂的功能测试
  • 支持参数化
  • 执行测试过程中可以将某些测试跳过,或者对某些预期失败的case标记成失败
  • 支持重复执行失败的case
  • 支持运行由nose, unittest编写的测试case
  • 具有很多第三方插件,并且可以自定义扩展
  • 方便的和持续集成工具集成

为什么要学习单测框架

  • 测试发现:从多个文件中找到测试用例
  • 测试执行:按照一定的顺序和规则去执行用例,并生成结果
  • 测试判断:通过断言判断预期结果和实际结果的差异
  • 测试条件:给定一些前置和后置的条件
  • 测试报告:统计测试进度、耗时、通过率、生成测试报告

pytest 安装

pip install -U pytest

pytest 的使用

Pytest测试样例的命名规则

  • 测试文件: test_*.py或*_test.py(否则用py.test命令行不能自动识别)
  • 测试类: 以Test开头,且不能带有__init__构造函数
  • 测试方法/函数: 以test_开头
  • fixture的文件名必须是conftest.py

创建一个最简单的例子

test_sample.py

def func(x):
    return x + 1


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


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

运行用例:

pytest test_sample.py

运行结果如下:

============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: E:\workspace\python_leaning, inifile:
collected 2 items

test_sample.py .F
test_sample.py:12 (test_answer_wrong)
def test_answer_wrong():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:14: AssertionError
                                                        [100%]

================================== FAILURES ===================================
______________________________ test_answer_wrong ______________________________

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

test_sample.py:14: AssertionError
===================== 1 failed, 1 passed in 0.09 seconds ======================

可以发现,执行了两个用例,一个成功,一个失败。

上述命令可以使pytest自动查找 test_sample.py 文件下所有的格式为:test_*的方法,然后执行用例.执行顺序为方法的顺序.

如果有多个py文件,可以直接使用下面命令

pytest

这个命令会找出当前目录下(包括其所有子目录下)所有格式为test_*.py或 *_test.py 的文件

然后执行用例(文件内格式为test_*的方法)

在类中分组组织用例

test_sample.py

def func(x):
    return x + 1

class TestSample(object):

    def test_answer_right_cls(self):
        print('test_answer_right_cls')
        assert func(3) == 4

    def test_answer_wrong_cls(self):
        print('test_answer_wrong_cls')
        assert func(3) == 5

运行用例:

pytest test_sample.py -s -v

运行结果如下:

================================================================================ test session starts ================================================================================
platform win32 -- Python 3.8.10, pytest-5.4.2, py-1.11.0, pluggy-0.13.1 -- e:\workspace\rftestapi\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\workspace\rftestapi\aitest\demo_pathlib2
plugins: repeat-0.8.0
collected 2 items                                                                                                                                                                    

test_sample.py::TestSample::test_answer_right_cls 测试方法-成功case
PASSED
test_sample.py::TestSample::test_answer_wrong_cls 测试方法-失败case
FAILED

===================================================================================== FAILURES ======================================================================================
_________________________________________________________________________ TestSample.test_answer_wrong_cls __________________________________________________________________________

self = <aitest.demo_pathlib2.test_sample.TestSample object at 0x0000000003E1A430>

    def test_answer_wrong_cls(self):
        print('测试方法-失败case')
>       assert func(3) == 5
E       assert 4 == 5
E         +4
E         -5

test_sample.py:25: AssertionError
============================================================================== short test summary info ==============================================================================
FAILED test_sample.py::TestSample::test_answer_wrong_cls - assert 4 == 5
============================================================================ 1 failed, 1 passed in 0.32s ============================================================================
  • -s: 是为了输出打印日志,如果不输入-s,是没有日志输出的。
  • -v: 显示详细结果
  • -q: 显示简单结果

执行用例的命令

  • 执行包下所有的用例:
pytest [包名]/
  • 执行模块下所有用例
pytest 模块名.py
  • 执行某模块下的某个用例
pytest 模块名.py::函数名
  • 执行某个模块里面某个类:
pytest 模块名.py::类名
  • 执行某个模块里面某个类里面的某个方法
pytest  模块名.py::类名::方法名

Python代码执行pytest

  • 使用python -m pytest 调用pytest
    python -m pytest test_sample.py
  • 使用main函数
    if __name__ == '__main__':
          # 1. 运行当前目录下的所有符合规则的用例,包括子目录(test_*.py 和 *_test.py),同命令行:pytest
          pytest.main()
          # 2. 运行模块中的某一条用例,同命令行:pytest test_sample::test_add_1 -vs
          pytest.main(['test_sample.py::test_add_1','-vs'])
      
    运行方式:python test_sample.py

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
My Show My Code