pytest 测试工具的使用学习

90 阅读3分钟

pytest

pytest 是 python 的一种单元测试框架,和自带的 unittest 测试框架类似,使用更简单,效率更高。

1.安装配置

 pip install pytest  # 安装 

2.使用

1.运行方式

  • 代码执行
 import pytest
 ​
 if __name__ == '__main__':
     pytest.main()   # pytest.main(['-s', '单独执行的文件名.py'])
  • 命令行执行

    命令行窗口直接执行 pytest

2.默认规则

对于直接执行 pytest

  • 模块,从测试目录或者当前目录中,寻找名称以 test_开头或 _test 结尾的 py 文件执行
  • 类,以上模块中以 Test 开头的类 且没有初始化 __init__ 方法
  • 函数及方法, 以上模块或类中,test 开头的函数或方法

3.配置文件

添加 pytest.ini 文件到根目录

 [pytest]
 ;ini文件中的英文分号后面的内容都是注释,未避免编码问题,最好将中文注释全部删除
 addopts = -s    ;选项
 testpaths = ./  ;测试模块所在的目录
 python_files = test_*.py *test.py   ;测试模块名称规则,多个用空格分隔
 python_classes = Test_*     ;测试类名称规则
 python_functions = test_*   ;测试函数或方法名称规则
 ​

4.标记

1.标记跳过测试

 @pytest.mark.skip(reason="因为一些原因,我要跳过")
 def test2():
     print("test2")
     
 @pytest.mark.skipif(condition=True, reason="原因")    # 当condition为true时才会跳过

2.标记失败

 @pytest.mark.xfail(condition=True, reason="原因", raises=Exception)   
 # 标记会出异常的测试,出现异常则正常
 # condition 情况,True标记预期失败,可省略
 # raises 预期抛出的异常类型

5.参数化

 # @pytest.mark.parametrize(self, argnames, argvalues, ids=None)
 # argnames 参数名称,列表或元组
 # argvalues 参数值, 列表套元组
 # ids 测试id, 可省略
 ​
 @pytest.mark.parametrize(['a','b'], [(1,2), (3,4), (10,11)])
 def test_num(a, b):
     assert a * b > 100

6.夹具

在测试之前后之后执行,用于固定测试环境,以及清理回收测试资源

 # 模块级
 def setup_module(args):
     pass
 def teardown_module(args):
     pass
 ​
 # 类级
 def setup_class(self):
     pass
 def teardown_class(self):
     pass
 ​
 # 方法级
 def setup_method(self, args):
     pass
 def teardown_method(self, args):
     pass
 ​
 # 函数级
 def setup_function(args):
     pass
 def teardown_function(args):
     pass
 ​
 # 同方法级别
 def setup(self):
     pass
 def teardown(self):
     pass

7.fixture 装饰器

pytest 提供了 fixture 进行更为强大的 夹具 使用

它也可以具备返回值

定义夹具

 # 无返回值
 @pytest.fixture()
 def before():
     print("before")
     
 # 有返回值
 @pytest.fixture()
 def before():
     print("before")
     return "user"
# 使用方法一
@pytest.mark.usefixtures("before")
def test():
    pass

# 使用方法二
def test(before):
    pass

参数化使用夹具

@pytest.fixture(params=[1,2,3])
def init_data(request):
    print("init_data:", request.param)
    return request.param

def test_2(init_data):
    print("test_2",init_data)
    assert init_data <= 2
fixture(
	scopr="function",
    params=None,
    autouse=False,
    ids=None,
    name=None
)

8.插件

1.html报告

  • 安装

    pip install pytest-html

  • 使用

    1. 命令行方式:pytest --html=存储路径/report.html
    2. 配置文件方式: addopts = -s --html=./report.html

2.指定执行顺序

  • 安装

    pip install pytest-ordering

  • 使用

    添加 @pytest.mark.run(order=x)到测试方法上,x为从0开始的整数,表示顺序,从小到大

3.失败重试

  • 作用:对于有外部依赖,可能会失败的函数,在失败后多试几次

  • 安装

    pip install pytest-rerunfailures

  • 使用

    1. 命令行方式:pytest --return 5
    2. 配置文件方式: addopts = -s --rerun 5