python 单元测试示范卷_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报告

5. 常用参数

-s : 打印测试案例中print信息

-q : 只显示结果[. F E S], 不展示过程

-x : 遇到失败案例,停止测试

--maxfail=num: 失败num个案例后,停止测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值