Python 单元测试 - pytest

pytest是python的一种单元测试框架,需要手动安装。与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高, 用法更丰富。

安装及查看版本

  • 使用pip 安装

pip install pytest

  • 查看安装版本
$ pytest --version
This is pytest version 3.5.1, imported from /home/tafan/.local/lib/python2.7/site-packages/pytest.pyc
  • pytest包含了丰富的用法

pytest --help

pytest 用法

已知被测对象demo.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

def add(a, b):
    return a+b

def minus(a, b):
    return a-b

1. 测试函数案例 test_demo_module.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from demo import add, minus

def setup_module(self):
    print "this setup method only called once.\n"

def teardown_module(self):
    print "this teardown method only called once too.\n"

def setup_function(self):
    print "do something before test : prepare environment.\n"

def teardown_function(self):
    print "do something after test : clean up.\n"

def test_add():
    assert add(1, 2) == 3

def test_minus():
    assert minus(3, 2) == 1
  • 文件必须要test_*.py*_test.py来命名
  • 测试case命名必须要test开头,最好是test_
  • 判断使用assert
  • setup_module, 所有case执行的前置条件,只运行一次
  • teardown_module, 所有case执行的后置条件,只运行一次
  • setup_function, 每个测试用例的前置条件
  • teardown_function, 每个测试用例的后置条件

2. 测试类案例 test_demo_class.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from demo import add, minus


class TestDemo(object):
    def setup_class(self):
        print "this setup method only called once.\n"

    def teardown_class(self):
        print "this teardown method only called once too.\n"

    def setup(self):
        print "do something before test : prepare environment.\n"

    def teardown(self):
        print "do something after test : clean up.\n"

    def test_add(self):
        assert add(1, 2) == 3

    def test_minus(self):
        assert minus(3, 2) == 1
  • 文件必须要test_*.py*_test.py来命名
  • 测试类命名必须要Test开头
  • 测试case命名必须要test开头,最好是test_
  • 判断使用assert
  • setup_class, 所有case执行的前置条件,只运行一次
  • teardown_class, 所有case执行的后置条件,只运行一次
  • setup, 每个测试用例的前置条件
  • teardown, 每个测试用例的后置条件

3. pytest执行命令:
  • pytest: 查找当前目录及子目录下所有test_*.py*_test.py的测试文件,然后一一执行文件内以test开头的函数
  • pytest ut/: 查找ut目录及子目录下所有test_*.py*_test.py的测试文件,然后一一执行文件内以test开头的函数
  • pytest test_demo_class.py: 可以指定测试文件
  • pytest test_demo_module.py::test_add: 执行指定测试文件中的测试case
  • pytest test_demo_class.py::TestDemo[::test_add]: 执行指定测试文件中的测试类[中的测试case]
  • pytest -k EXPRESSION: 执行和表达式匹配的测试案例,详见pytest --help

4. 生成html报告

Python 单元测试 - report


5. 常用参数

-s : 打印测试案例中print信息
-q : 只显示结果[. F E S], 不展示过程
-x : 遇到失败案例,停止测试
--maxfail=num: 失败num个案例后,停止测试

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容