
- 1 准备
- 2 基础方法
- 3 使用钩子函数
- 安装python
- 安装pytest:pip install pytest
- 安装allure-pytest:pip install allure-pytest
- 安装allure的命令行工具:https://docs.qameta.io/allure/#_installing_a_commandline
安装完成后记得配环境变量,校验如下:
- 安装pycharm
- 要做web自动化:安装chrome浏览器、下载chromedriver驱动
- 安装selenium:pip install selenium
- 创建项目,写脚本
- 当测试用例失败时完成截图并添加到allure附件中
(1)如何识别每一条测试用例失败的情况:使用pytest中的钩子函数:pytest_runtest_makereport(item, call)
(2)conftest.py 在这个文件中实现钩子函数
test_case\test.screenshot.py文件:
import allure
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_baidu():
# 创建webdriver
wd = webdriver.Chrome()
# 打开百度
wd.get('http://www.baidu.com')
try:
# 错误代码, 故意失败
wd.find_element(By.ID, 'xxx')
except Exception as e:
# 如果 *** 作步骤过程中有异常,那么用例失败,在这里完成截图 *** 作
img = wd.get_screenshot_as_png()
# 将截图展示在allure测试报告上
allure.attach(img, '失败截图', allure.attachment_type.PNG)
# 在命令行依次输入以下命令:
# 运行pytest测试用例,在./report/allure-results下生成测试数据
# pytest -sv test_case/test_screenshot.py --alluredir ./report/allure-results --clean-alluredir
# 找到测试数据, 在./reports/allure-report下生成测试报告
# allure generate ./report/allure-results -o ./report/allure-report --clean
3 使用钩子函数
conftest.py文件:
import allure
import pytest
from selenium import webdriver
driver = None # 定义一个全局driver对象
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# 什么时候去识别用例的执行结果呢?
# 后置处理 yield:表示测试用例执行完了
outcome = yield
rep = outcome.get_result() # 获取测试用例执行完成之后的结果
if rep.when == 'call' and rep.failed: # 判断用例执行情况:被调用并且失败
# 实现失败截图并添加到allure附件。截图方法需要使用driver对象,想办法把driver传过来
# 如果 *** 作步骤过程中有异常,那么用例失败,在这里完成截图 *** 作
img = driver.get_screenshot_as_png()
# 将截图展示在allure测试报告上
allure.attach(img, '失败截图', allure.attachment_type.PNG)
# 自定义fixture实现driver初始化及赋值并且返回
@pytest.fixture(scope='session', autouse=True)
def init_driver():
global driver # global变量,相当于给上面driver = None赋值了
if driver is None:
driver = webdriver.Chrome()
return driver
test_case\test.screenshot.py文件:
from selenium.webdriver.common.by import By
def test_baidu(init_driver):
init_driver.get('http://www.baidu.com')
init_driver.find_element(By.ID, 'xxx')
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)