一、命名规则
1、初体验
main.py
# -- coding: utf-8 --
import pytest
pytest.main(["-s"])
#pytest 通过 一个 list 接收参数
-s : 开启终端(控制台/输入台)的交互
-v : 让 pytest 的输出结果更加详细
test_case.py
# -- coding: utf-8 --
def test_001():
print("第一个用例被执行")
# test_001() # pytest 解决的是,我可以不写调用语句,也可以执行函数的内容
def test_002():
print("第二个用例被执行")
运行 main.py 文件
2、命名规则
# -- coding: utf-8 --
import pytest
pytest.main(["-s"])
#pytest 通过 一个 list 接收参数
1、当运行了这段指令之后,它就会在你当前的这个运行指令的文件相对同级的目录中找符合 test_ 开头或者 _test 结尾的 .py 文件,或者再往下层找;
2、然后再找文件中 test 开头的函数,或者先在 Test(大写)开头的类,再找类中 test 开头的函数
3、通过上述方式找到所有用例依次执行
3、命令行运行方式
pytest <==> pytest.main([])
pytest -s <==> pytest.main(["-s"])
pytest -s -v <==> pytest.main(["-s","-v"])
pytest -sv <==> pytest.main(["-sv"])
pytest -vs <==> pytest.main(["-vs"])
运行指定方法名:
pytest 文件名.py::类名::方法名 -sv <==> pytest.main(["文件名.py::类名::方法名","-vs"])
运行指定文件:
pytest.main(["地址","-vs"])
二、前置后置操作
Pytest框架 —— setUp()和tearDown()函数_pytest setup teardown-CSDN博客
三、标签
命名方式:
不能以数字开头,一条用例可以添加多个标签
@pytest.mark.名称
# -- coding: utf-8 --
import pytest
@pytest.mark.one
def test_001():
print("第一个用例被执行")
# test_001() # pytest 解决的是,我可以不写调用语句,也可以执行函数的内容
@pytest.mark.two
def test_002():
print("第二个用例被执行")
标签的作用:灵活的管理和运行测试用例
自定义的标签要在pytest.ini文件中声明
内置标签:自动化测试框架pytest教程6-标签(标记) - 简书 (jianshu.com)https://www.jianshu.com/p/1831e22567b4
四、pytest.ini
【pytest】pytest配置文件pytest.ini详解-CSDN博客
五、conftest
pytest使用(3)-conftest_pytest conftest-CSDN博客
六、pytest-html 生成报告
安装插件
pip install pytest-html
运行测试并生成报告
pytest --html=report.html #报告生成为report.html 文件
小案例:
运行之后生成report.html 的文件,查看文件显示如下:
乱码情况:
将External Libraries——site-packages——pytest_html——result.py
大约21行
self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
改为 utf-8
self.test_id = report.nodeid.encode("utf-8").decode("utf-8")
三、钩子函数
pytest提供的钩子函数是pytest自己预留的一些函数,写在conftest里面
@pytest.hookimpl(hookwrapper=True) # 写死的
def pytest_runtest_makerport(item,call): # 写死的
outcome = yield # 一个yield 代表 报告的一个结果
report = outcome.get_result()
if report.when == 'call': # 过滤 前置 和 后置,只保留运行中的状态
print("用例执行结果:", report.outcome) # 用例执行结果
七、allure 生成测试报告
安装方式
1.安装allure
Python自动化之如何利用allure生成测试报告_python allure生成报告-CSDN博客
环境变量的值为 它的bin文件夹的绝对路径
2.安装插件
pip install allure-pytest
使用方式
import pytest pytest.main(["--alluredir", "allure_result","--clean-alluredir"])# 获得测试结果,并以allure的数据格式保存下来 import os os.system("allure generate --clean ./allure_result -o ./allure_report") # 通过allure的数据进行报告的生成
7.2 allure-pytest的行为驱动标记
在Allure报告中,feature(主分类,一般一个类为一个feature) 和 story(次分类) 被称为行为驱动标记,用于描述测试用例所属的功能和故事。
7.3 allure的步骤管理
在方法前添加
@allure.step("步骤")