一、环境安装
一).安装allure包
-
下载allure,下载网址 https://github.com/allure-framework/allure2/releases
-
解压到电脑本地(此目录后续使用,不要动),配置环境变量(把allure目录下的bin目录配置到系统环境变量中的path路径)
1)高级系统设置-> 环境变量->系统环境变量-> Path, 编辑
2)新建,添加allure-2.22.1\bin目录到环境变量中 F:allure-2.22.1\bin
3)验证安装成功
a、 先在dos窗口验证
cmd 命令行输入 allure --version
返回allure的版本则安装成功。
b、dos窗口成功后再在pycharm中验证
输入 allure --version
返回allure的版本则安装成功,如果不成功重启pycharm,还不行重启电脑。
二)安装allure-pytest插件
pip安装
pip install allure-pytest
该命令将安装 allure-pytest 包与 allure-python-commons 两个第三方包。
二、生成allure报告
一)生成临时json报告
使用命令
–alluredir=./文件路径 --clean-alluredir
–alluredir 表示指定测试报告数据的生成路径
文件路径 为保存json数据的文件夹目录
–clean-alluredir 表示每次生成临时报告清空之前的内容,避免内容过多占用存储空间 在pytest.ini文件中加上addopts 命令:
- 可以在pytest.ini中添加:
addopts = -vs --alluredir=./temps --clean-alluredir
- 可以在运行代码中添加:
def run():
pytest.main(['-vs', '--alluredir=%s' % json文件路径, '--clean-alluredir'])
二)生成正式的allure报告
使用命令
allure generate ./json文件路径 -o ./报告文件路径 --clean
./json文件路径 临时的json格式报告的路径
-o 输出output
./报告文件路径 生成的allure报告的路径
–clean 清空./reports 目录中原来的报告
注意: 在命令行中,通常等号左右不允许有空格,否则会导致解析错误。
如果allure没有添加到系统环境变量中,会有乱码
三)allure报告环境变量
可以将测试环境变量信息,运行期及统计信息一并生成到json目录中,与测试结果一并生成allure报告。
新建allure_des.py,代码如下:
import json
import os
import platform
import pytest
from config.config import cm
def set_report_env_on_results():
"""
在json报告的目录下生成一个写入环境信息的文件:environment.properties(注意:不能放置中文,否则会出现乱码)
"""
# 需要写入的环境信息,根据实际工程填写
allure_env = {
'OperatingEnvironment': 'mcx DC',
'PythonVersion': platform.python_version(),
'PytestVersion': pytest.__version__,
'Platform': platform.platform(),
'selenium': '4.10.0',
'Browser': 'Chrome',
'BrowserVersion': "112.0.5615.50",
'DiverVersion': "112.0.5615.49"
}
allure_env_file = os.path.join(cm.dir_report_json, 'environment.properties')
with open(allure_env_file, 'w', encoding='utf-8') as f:
for _k, _v in allure_env.items():
f.write(f'{_k}={_v}\n')
def set_report_executer_on_results():
"""
在json报告的目录下生成一个写入执行人的文件:executor.json
"""
# 需要写入的运行信息
allure_executor = {
"name": "张三",
"type": "jenkins",
"url": "http://helloqa.com", # allure报告的地址
"buildOrder": 3,
"buildName": "allure-report_deploy#1",
"buildUrl": "http://helloqa.com#1",
"reportUrl": "http://helloqa.com#1/AllureReport",
"reportName": "张三 Allure Report"
}
allure_env_file = os.path.join(cm.dir_report_json, 'executor.json')
with open(allure_env_file, 'w', encoding='utf-8') as f:
f.write(str(json.dumps(allure_executor, ensure_ascii=False, indent=4)))
def set_report_categories_on_results():
"""
在json报告的目录下生成一个写入统计类型的文件:categories.json
"""
# 需要写入的运行信息
allure_categories = [
{
"name": "Ignored tests",
"matchedStatuses": ["skipped"]
},
{
"name": "Infrastructure problems",
"matchedStatuses": ["broken", "failed"],
"messageRegex": ".*bye-bye.*"
},
{
"name": "Outdated tests",
"matchedStatuses": ["broken"],
"traceRegex": ".*FileNotFoundException.*"
},
{
"name": "Product defects",
"matchedStatuses": ["failed"]
},
{
"name": "Test defects",
"matchedStatuses": ["broken"]
}
]
allure_cat_file = os.path.join(cm.dir_report_json, 'categories.json')
with open(allure_cat_file, 'w', encoding='utf-8') as f:
f.write(str(json.dumps(allure_categories, ensure_ascii=False, indent=4)))
运行后json目录下除了用例测试结果的json文件,同时生成上述三个文件,如图:
四)运行用例生成allure报告
在执行用例时,生成json数据,环境信息,之后生成allure报告。
在runtest.py(测试用例执行入口文件)中编写下列代码:
import os
import pytest
from allure_des import set_report_env_on_results, \
set_report_executer_on_results, \
set_report_categories_on_results
from config.config import cm # 目录结构的配置文件
from utils.timer import sleep
def run():
pytest.main(['--allure-features=app登录功能', '--alluredir=%s' % cm.dir_report_json])
# 在json 目录下创建 categories.json 文件
set_report_categories_on_results()
# 在json 目录下创建 environment.properties文件
set_report_env_on_results()
# 在json 目录下创建 executor.json文件
set_report_executer_on_results()
sleep(3)
os.system("allure generate %s -o %s --clean" % (cm.dir_report_json, cm.dir_report_html))
if __name__ == '__main__':
run()
运行后,在report目录下产生allure报告文件,注意如果环境是独立的,这里文件只能在当前环境中打开。
打开后显示的测试报告展示如下:
环境信息,运行期显示为allure_des.py中描述的信息。
三、allure报告失败截图
测试用例失败时,有时需要截图附到allure报告中,可以使用pytest框架的钩子函数来实现。
在conftest.py中添加如下方法:
#conftest.py
"""
失败截图保存到allure测试报告中
"""
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# 后置,获取测试结果
outcome = yield
reps = outcome.get_result()
if reps.when == 'call' and reps.failed:
# 在测试失败时进行截图, 添加到allure报告中
img = web_driver.get_screenshot_as_png()
name = '_'.join([reps.nodeid.replace('testcases/', '').replace('::', '_'), dt_strftime('%Y%m%d %H%M%S')]) # 为截图文件命名
allure.attach(img, name=name, attachment_type=allure.attachment_type.PNG)
测试执行完成后,使用用例贴图到对应测试用例结果的附件中。
四、allure报告生成框架
在编写测试用例过程中,可以套用allure报告生成框架中的装饰器,使得allure报告更已读,装饰器说明如下表所示:
装饰器 | 名称 | 功能描述 |
---|---|---|
@allure.epic("测试模块_demo1") | 史诗 | 功能块,往下再分feature,story |
@allure.feature("测试模块_demo2") | 功能 | 标注功能模块,往下分story (测试类) |
@allure.story("测试模块_demo3") | 故事 | 标注feature下的分支功能模块,(测试方法) 具有相同feature或story的用例将规整到相同模块下,执行时可用于筛选 |
@allure.issue("BUG编号:123") | 问题 | 问题标识,关联标识已有的问题,可为一个URL链接地址 |
@allure.testcase("用例名:测试正确用户名密码登录成功") | 用例 | 用例标识,关联标识用例,可为一个URL链接地址 |
@allure.severity("critical") | 严重级别 | 优先级,包含blocker,critical,normal,minor,trivial几个不同的等级 |
@allure.step("测试步骤") | 测试步骤 | 测试步骤 |
@allure.description("用例描述") | 用例描述 | 用于为测试用例添加描述信息 |
@allure.title("用例标题") | 用例标题 | 用于定义测试用例标题 |
@allure.link('链接',name="") | 链接 | URL链接地址 |
对装饰器使用的方法及位置说明举例如下:
"""
@File: allure_demo.py
@Author: Sarah
@Time : 2024/1/10
@Description: allure使用示例
"""
import pytest
import allure
from utils.logger import log
# 测试步骤
@allure.step("步骤1")
def step_1():
log.info("用例操作步骤1")
return True
@allure.step("步骤2")
def step_2():
log.info("用例操作步骤2")
return False
@allure.step("步骤3")
def step_3():
log.info("用例操作步骤3")
return True
# 封装测试用例
@allure.epic("对用例或用例集进行描述分类(若出现多个时,内容一致则自动归为一类)")
@allure.feature("对用例集或用例进行描述分类---与epic类似,比epic级别低")
@allure.story("对用例集或用例进行描述分类---与epic类似,比feature级别低")
class TestDemo1:
@allure.testcase("https://xxx/testcase/list", name='用例链接testcase') # 为了更好的链接到问题分类或者bug、测试用例地址中(url、name两个参数,可不填写name;可以用@allure.link)
@allure.link("https://xxx/testcase/list", name='用例链接link') # 与testcase没有多大区别,从可读性角度还是建议选择@allure.link
@allure.issue("https://xxx/testcase/list", name='用例链接issue') # 与testcase区别在于有小虫子图标
@allure.title("用例的标题") # 可参数化标题
@allure.story("用例分类:1") # 可参数化标题
@allure.severity("critical") # 用例等级(blocker critical normal minor trivial)
def test_case_1(self):
log.info("测试用例1")
assert step_1()
assert step_2()
@allure.story("用例分类:2")
def test_case_2(self):
log.info("测试用例2")
assert step_1()
assert step_3()
@allure.epic("冒烟自动化用例")
class TestDemo2:
@allure.story("用例分类:3")
def test_case_3(self):
log.info("测试用例3")
step_1()
@allure.story("用例分类:4")
def test_case_4(self):
log.info("测试用例4")
step_3()
在web自动化框架中,使用示例代码如下:
"""
@File: allure_demo.py
@Author: Sarah
@Time : 2023/7/18
@Description: allure使用示例
"""
import pytest
import allure
from utils.logger import log
# conftest.py 在胶水文件中定义用例前后置操作
@pytest.fixture(scope="session",autouse=True)
def drivers():
# 获取浏览器驱动
return web_driver
# page_login.py 在page封装中定义操作步骤
class PageLogin(Base):
"""登录页面 """
def page_get_error_info(self):
"""获取异常提示信息"""
return error_info
def page_login(self, username, password):
with allure.step(f"输入用户名: {username}"):
# 输入用户名操作
with allure.step(f"输入密码: {password}"):
# 输入密码操作
with allure.step("点击登录按钮"):
# 点击登录按钮操作
# test_login.py 测试用例中调用页面操作步骤
from test_data import login_para_fail, login_para_succ # 参数化测试数据
@allure.feature("登录功能")
class TestLogin(Common):
"""登录测试 """
@allure.story("登录失败")
@allure.title("登录异常检测-{username}-{password}-{expect_text}")
@allure.description("测试登录时的各种异常情况")
@allure.severity("minor")
@pytest.mark.parametrize("username, password, expect_text", login_para_fail)
def test_login_fail(self, drivers, username, password, expect_text):
PageLogin(drivers).page_login(username, password) # 调用页面方法
with allure.step("捕获提示信息"):
error_info = PageLogin(drivers).page_get_error_info()
with allure.step("开始断言"):
assert expect_text in error_info
@allure.story("登录成功")
@allure.title("登录成功-{username}-{password}-{expect_text}")
@allure.description("输入正确合法的用户名和密码登录成功")
@allure.severity("critical")
@pytest.mark.parametrize("username, password, expect_text", login_para_succ)
def test_login_suc(self, drivers, username, password, expect_text):
PageLogin(drivers).page_login(username, password) # 调用页面方法
with allure.step("获取当前页面tile"):
title_info = drivers.title
with allure.step("开始断言"):
assert expect_text in title_info
step装饰器可以使用@allure.stet(“测试步骤”),也可以使用with allure.step(“测试步骤”)。
本文结束。