1. pytest介绍
1.1 介绍
基于unittest之上的单元测试框架
自动发现测试模块和测试方法
断言使用:assert+表达式即可
可以使用会话级、模块级、类级、函数级的fixtures:数据准备+清理工作
有300个以上的插件库 ==allure
1.2 安装
pip install pytest
pip install pytest-html # html格式报告
1.3 使用
import pytest
1.4 插件
拥有超过300个插件
http://plugincompat.herokuapp.com/
2. pytest-mark
2.1 介绍
对测试用例打标签。在运行测试用例时,可根据标签名来过滤
2.2 方法
在测试用例或测试类前面加上pytest.mark.demo
一个用例可以打多个标签
eg:
@pytest.mark.smoke
def function():
pass
3. pytest-命令行运行
3.1 介绍
pytest通过命令行参数的形式来运行测试用例、设置过滤条件、生成测试报告。
查看命令:
pytest --help
运行:
pytest -m smoke # 仅运行mark为smoke的用例
pytest -m smoke and demo # 表运行smoke和demo的用例
3.2 用例收集
收集规则:当前目录下:模块-->函数、类
默认从当前目录搜索用例
符合命名test_*.py或*_test.py的模块文件
以test_*开头的函数
以Test开头的测试类(不包括__init__函数)中,以test_*开头的文件名
4. pytest-fixture功能
4.1 fixture介绍
测试用例的环境准备与清理。相当于setUp/tearDown、setUpclass/tearDownclass,默认为function级别
目的:提供一种可靠和可重复性的手段去运行那些最基本的内容,如打开浏览器、登录、退出
*** 此功能与unittest不兼容
4.2 定义fixture
1. 定义方法:函数申明之前加上@pytest.fixture,表此函数为测试环境的数据准备和清理。
2. yield关键字前后分别为准备与清理。
4.3 调用fixture
1. 在测试用例中直接调用:
将fixtures的函数名字作为测试用例的参数
如果fixture有返回值,那么测试用例中的fixture函数名字就接收返回值
# eg:
def test_demo(self.myfixture): # fixture函数名作为参数传入
myfixture.find_element_by_xpath('xxx') # 函数名代表了fixture的返回值,即driver
2. 装饰器调用:
定义conftest.py文件,在文件中可定义多个fixture. pytest会自动搜索此文件
在测试用例/类前加上@pytest.mark.usefixtures("fixture函数名字")
3. 用autos调用:
在定义fixture时,有一个参数时autouse,默认未false.
默认为True时,在一个session内所有的test都会自动调用这个fixture.---谨慎使用
5. pytest-参数化
5.1 介绍
在测试用例的前面加上:
@pytest.mark.parametrize("参数名",列表数据)
参数名:用来接收每一项数据,并作为测试用例的参数。
列表数据:一组测试数据
*** 与unittest不兼容
5.2 使用
eg:
@pytest.mark.parametrize("data",data)
def test_demo(self,data):
pass
6. pytest-重运行
6.1 介绍
pytest提供了失败用例重运行机制,当运行某个用例失败后,按照设置的固定等待运行时间、运行次数重运行,之后再运行其他用例。
插件名称:rerunfailures
安装方法:pip install pytest-rerunfailures
6.2 使用
命令行:pytest --reruns 重试次数 --reruns-delay 次数之间的延时设置(s)
eg:pytest --reruns 2 --reruns-delay 5
7. pytest-html报告
7.1 安装
pip install pytest-html
7.2 使用
生成JunitXML格式的测试报告:命令:--junitxml=path
生成result log格式的测试报告:命令:--resultlog=report\log.txt
生成Html格式的测试报告:命令:--html=report\test_one_func.html
eg:
pytest.main([r"--html=Outputs\Reports\report.html", r"--junitxml=Outputs\Reports\report.xml"])
8. pytest-allure测试
9. pytest-jenkins集成
https://blog.csdn.net/akkzhjj/article/details/43990865
课程104、105