码迷,mamicode.com
首页 > 编程语言 > 详细

python测试模块-pytest介绍

时间:2018-05-26 13:02:52      阅读:1289      评论:0      收藏:0      [点我收藏+]

标签:and   python   cto   this   集成   测试用例   重复执行   版本   文档   

1、pytest介绍
pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。
它具有如下特点:
?非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
?能够支持简单的单元测试和复杂的功能测试
?支持参数化
?执行测试过程中可以将某些测试跳过,或者对某些预期失败的case标记成失败
?支持重复执行失败的case
?支持运行由nose, unittest编写的测试case
?具有很多第三方插件,并且可以自定义扩展
?方便的和持续集成工具集成

2、pytest的安装
pip install pytest
安装完成后,可以验证安装的版本:
pytest --version

3、pytest的命令格式
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
positional arguments:file_or_dir

4、测试用例
1)编写单个测试函数
编写测试文件sample.py,如下:
def func(x):
return x+1

def test_func():
assert func(3) == 5
定义一个被测试函数func,该函数将传递进来的参数加1后返回。还定义了一个测试函数test_func(可以任意命名,但是必须以test开头)用来对func进行测试。test_func中,我们使用基本的断言语句assert来对结果进行验证。执行测试的时候,我们只需要在测试文件sample.py所在的目录下,运行python -m pytest -v sample.py即可

2)编写测试类
当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中
测试文件dd.py
class TestClass:
def test_one(self):
x = "this"
assert ‘h‘ in x

def test_two(self):  
    x = "hello"  
    assert hasattr(x, ‘check‘) 

运行测试文件pytest dd.py即可

5、如何编写pytest测试样例
规范写法:
?测试文件以test_开头(以_test结尾也可以)
?测试类必须以Test开头,并且不能带有 init 方法(带__init__方法,会报waring)
?测试函数或方法以test_开头,函数体里面使用assert ,调用被测试的函数
?断言使用基本的assert即可

备注:
1、其实测试函数或方法只要以test开头就可以被运行的
2、测试文件的名字,其实可以是任意的文件名,不过以非test_开头的命名时,运行时,必须以指定测试文件名的方式才可以搜索到并执行它,使用pytest,pytest 文件目录,这样的命令,执行测试文件时,是找不到非test_开头的测试文件的

6、如何执行pytest测试样例
pytest # run all tests below current dir
在当前测试文件的目录下,寻找以test开头的文件(即测试文件),找到测试文件之后,进入到测试文件中寻找test_开头的测试函数并执行
pytest test_mod.py # run tests in module 执行某一个指定的测试文件
pytest somepath # run all tests below somepath 运行某一个目录下的所有测试用例
pytest -k stringexpr # only run tests with names that match the
# the "string expression", e.g. "MyClass and not method"
# will select TestMyClass.test_something
# but not TestMyClass.test_method_simple
pytest xxx.py::test_func # 执行某一测试文件中的某一指定函数

7、测试报告
pytest可以方便的生成测试报告,即可以生成HTML的测试报告,也可以生成XML格式的测试报告用来与持续集成工具集成
生成HTML格式报告:
pytest --resultlog=path #默认生成的是html格式

生成XML格式的报告:
pytest --junit-xml=path #不同版本的pytest该命令可能不一样

8、如何获取帮助信息
pytest --version # shows where pytest was imported from
pytest -h | --help # show help on command line and config file options

9、最佳实践
其实对于测试而言,特别是在持续集成环境中,我们的所有测试最好是在虚拟环境中。这样不同的虚拟环境中的测试不会相互干扰的。由于我们的实际工作中,在同一个Jekins中,运行了好多种不同项目册的测试,因此,各个测试项目运行在各自的虚拟环境中。
将pytest安装在虚拟环境中
1、将当前目录创建为虚拟环境
1)virtualenv . # create a virtualenv directory in the current directory
2)source bin/activate # on unix

2、在虚拟环境中安装pytest:
pip install pytest

python测试模块-pytest介绍

标签:and   python   cto   this   集成   测试用例   重复执行   版本   文档   

原文地址:https://www.cnblogs.com/potato-chip/p/9092517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!