当前位置:网站首页>allure--常用配置项
allure--常用配置项
2022-07-02 06:36:00 【迷途~知返】
allure--常用配置选项
参数化动态更新案例名称
- parametrize参数中添加ids实现:用ids修改用例标题时,不要添加@allure.title()
# conftest.py
# Hook函数,解决控制台乱码问题
def pytest_collection_modifyitems(items):
""" 测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上 """
for item in items:
item.name = item.name.encode('utf-8').decode('unicode_escape')
item._nodeid = item.nodeid.encode('utf-8').decode('unicode_escape')
# coding:utf-8
# pytest用例函数
import os
import allure
import pytest
# 测试数据
test_datas = [
# {} 放测试数据,
# success:预期结果
({
'username': 'zz', 'pwd': '123456'}, 'success'),
({
'username': 'xu', 'pwd': '127654'}, 'failed'),
({
'username': 'qb_10', 'pwd': '123456'}, 'success')
]
# @allure.title('登录模块')
# @pytest.mark.parametrize('test_input, expeted', test_datas)
# def test_login(test_input, expeted):
# """测试用例登录"""
# print('获取输入数据')
# print(test_input['username'], test_input['pwd'])
# print('获取预期结果')
# print(expeted)
# print('登录')
# 模拟一个登录接口
def login(username, pwd):
"""login"""
print('输入账户:{}'.format(username))
print('输入密码:{}'.format(pwd))
# 返回
return {
'code': 0, 'msg': 'success'}
# ids:作用,修改函数名,便于查看
# @allure.title('登录模块')
@pytest.mark.parametrize('test_input, expeted', test_datas,
ids=['输入正确的账号A, 密码, 登录',
'输入正确的账号B, 密码, 登录',
'输入正确的账号C, 密码, 登录'
]
)
def test_login(test_input, expeted):
"""测试用例登录"""
result = login(test_input['username'], test_input['pwd'])
# 断言
assert result['msg'] == expeted
if __name__ == '__main__':
pytest.main(['./test_ids.py', '--alluredir', './result2/', '--clean-alluredir'])
os.system('allure generate ./result2/ -o ./report_2/ --clean')

参数化用例名称,进阶,通过@allure.title()实现
# coding:utf-8
# pytest用例函数
import os
import allure
import pytest
# 测试数据
test_datas = [
# {} 放测试数据,
# success:预期结果
({
'username': 'zz', 'pwd': '123456'}, 'success', '输入正确的账号,密码登录'),
({
'username': 'xu', 'pwd': '127654'}, 'failed', '输入正确的账号,密码登录'),
({
'username': 'qb_10', 'pwd': '123456'}, 'success', '输入正确的账号,密码登录')
]
# @allure.title('登录模块')
# @pytest.mark.parametrize('test_input, expeted', test_datas)
# def test_login(test_input, expeted):
# """测试用例登录"""
# print('获取输入数据')
# print(test_input['username'], test_input['pwd'])
# print('获取预期结果')
# print(expeted)
# print('登录')
# 模拟一个登录接口
def login(username, pwd):
"""login"""
print('输入账户:{}'.format(username))
print('输入密码:{}'.format(pwd))
# 返回
return {
'code': 0, 'msg': 'success'}
@allure.title('{title}:{test_input}')
@pytest.mark.parametrize('test_input, expeted, title', test_datas)
def test_login(test_input, expeted, title):
"""测试用例登录"""
result = login(test_input['username'], test_input['pwd'])
# 断言
assert result['msg'] == expeted
if __name__ == '__main__':
pytest.main(['./test_b_title.py', '--alluredir', './result4/', '--clean-alluredir'])
os.system('allure generate ./result4/ -o ./report4/ --clean')

allure清理上一次的运行记录
- allure报告可以记录用例每次的执行情况,方便跟踪用例的成功率,数据保留在 json文件中
- 会带来一个问题,当你代码里的用例删除或者更换名称后,依然会记录之前的用例报告
pytest.main(['./test_b_title.py', '--alluredir', './result4/'])
清理历史数据
pytest.main(['./test_b_title.py', '--alluredir', './result4/', '--clean-alluredir'])
- 输出报告中的clean:只是让报告重新生成,生成的结果会保留之前的用例执行记录
os.system('allure generate ./result4/ -o ./report4/ --clean')
allure动态生成用例标题
@allure.title 描述用例标题
@allure.description 描述用例的详情 在用例可以动态更新,使用allure.dynamic方法实现
# coding:utf-8
import os
import allure
import pytest
desc = '<font color="red">请求url:</font>{}<Br/>'\
'<font color="red">测试结果:</font>{}<Br/>'\
'<font color="red">请求方法:</font>{}<Br/>'\
'<font color="red">实际结果:</font>{}<Br/>'\
'<font color="red">错误结果:</font>{}<Br/>'\
.format('http://www.baidu.com', 'pass', 'post', '200', '404')
@allure.description('简单描述')
def test_dynamic():
"""description"""
assert 1 == 1
allure.dynamic.description(desc)
@allure.title('更新标题')
def test_dynamic_title():
assert 2 + 2 == 4
allure.dynamic.title('当断言成功时,标题会被修改')
@allure.title('参数化用例标题,添加{param1}和{param2}')
@pytest.mark.parametrize('param1, param2, expected', [(1, 2, 3), (2, 2, 5)])
def test_with_parm_title(param1, param2, expected):
assert param1 + param2 == expected
allure.dynamic.title('变更标题')
if __name__ == '__main__':
pytest.main(['./test_dynamic_allure.py', '--alluredir', './result/', '--clean-alluredir'])
os.system('allure generate ./result/ -o ./report/ --clean')

执行结果
allure-添加环境信息
在result目录中增加environment.properties
systemVersion=win10
pythonVersion=3.6.0
allureVersion=2.18.0
baseUrl=http:www.baidu.com
projectName=test
author=zz
email=[email protected].com
freind=Mr.ma
- 方式二:在allure的result目录下添加一个environment.xml
<environment>
<parameter>
<key>Browser</key>
<value>Chrome</value>
</parameter>
<parameter>
<key>Browser.Version</key>
<value>63.0</value>
</parameter>
<parameter>
<key>Stand</key>
<value>Production</value>
</parameter>
</environment>
在result之外创建上述两个文件,然后,生成测试报告前,将文件内容导入
if __name__ == '__main__':
pytest.main(['./test_env.py', '--alluredir', './result/', '--clean-alluredir'])
os.system('copy environment.properties result\\environment.properties')
os.system('allure generate ./result/ -o ./report/ --clean')

测试用例失败截图
# conftest代码
# coding:utf-8
import allure
import pytest
from selenium import webdriver
@pytest.fixture(scope='session')
def browser():
print('browser init')
global driver
driver = webdriver.Chrome()
yield driver
driver.quit()
print('browser quit')
""" 装饰器@pytest,hookimpl(hookwrapper=True)等价于@pytest.mark.hookwrapper 作用:可以获取测试用例的信息,比如用例函数的描述 可以获取测试用例的执行结果,yield,返回一个result对象 """
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport():
# 可以获取测试用例的执行结果,yield,返回一个result对象
out = yield
""" 从返回一个result对象(out)获取调用结果的测试报告,返回一个report对象 report对象的属性 包括when(setup,call,teardown三个值)、nodeid(测试用例的名字)、 outcome(用例的执行结果:passed,failed) """
report = out.get_result()
# 仅仅获取用例call阶段的执行结果,不包含setup和teardown
if report.when == 'call':
# 获取用例call执行结果为结果为失败的情况
xfail = hasattr(report,"wasxfail")
if(report.skipped and xfail) or (report.failed and not xfail):
# 添加allure报告截图
with allure.step("添加失败截图。。"):
# 使用allure自带的添加附件的方法:三个参数分别为:源文件、文件名、文件类型
allure.attach(driver.get_screenshot_as_png(),"失败截图",
allure.attachment_type.PNG)
测试代码
# coding:utf-8
from time import sleep
def test_baidu_case01(browser):
driver = browser
driver.get("http://www.baidu.com")
sleep(2)
# 定位到百度搜索框,然后输入关键字
driver.find_element_by_id('kw').send_keys('狗狗币')
sleep(2)
# 定位到搜索按钮,点击搜索
driver.find_element_by_id('su').click()
sleep(2)
assert driver.title == "11狗狗币_百度搜索"
入口函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
def run():
pytest.main(['-v',
'--alluredir','./result','--clean-alluredir'])
os.system('allure generate ./result/ -o ./report_allure/ --clean')
if __name__ == '__main__':
run()
运行结果
边栏推荐
- Pycaret | a few lines of code to solve machine learning modeling
- [ue5] animation redirection: how to import magic tower characters into the game
- Metaclass type and using metaclass to implement model class ORM
- Error reporting on the first day of work (incomplete awvs unloading)
- 2837xd代码生成模块学习(2)——ADC、ePWM模块、Timer0
- Mobile mall app solution: how much is it to make an app? Detailed explanation of APP mall development content
- Blender camera surround motion, animation rendering, video synthesis
- ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
- Mixed development of uni app -- Taking wechat applet as an example
- Eslint reports an error
猜你喜欢

Aiphacode is not a substitute for programmers, but a tool for developers

2837xd code generation - stateflow (1)

Record the interesting process of using Xray for the first time

2.14 is it Valentine's day or Valentine's day when the mainstream market continues to fluctuate and wait for changes?

Illusion -- Animation blueprint, state machine production, character walking, running and jumping action

Alibaba cloud Prometheus monitoring service

渗透测试的介绍和防范

Message mechanism -- getting to know messages and message queues for the first time

虚幻AI蓝图基础笔记(万字整理)

2837xd Code Generation - Supplement (1)
随机推荐
C language: making barrels
2837xd code generation - stateflow (1)
Project practice, redis cluster technology learning (13)
This article takes you to learn in detail what is fiber to home FTTH
Blender多鏡頭(多機比特)切換
How does {} prevent SQL injection? What is its underlying principle?
Deep understanding of redis cache avalanche / cache breakdown / cache penetration
2837xd code generation - Supplement (3)
Eslint reports an error
Edge computing accelerates live video scenes: clearer, smoother, and more real-time
2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
Translation d30 (with AC code POJ 28:sum number)
Mobile mall app solution: how much is it to make an app? Detailed explanation of APP mall development content
Unreal material editor foundation - how to connect a basic material
Centos7 one click compilation and installation of PHP script
【避坑指南】使用UGUI遇到的坑:Text组件无法首行缩进两格
Project practice, redis cluster technology learning (IX)
How to handle error logic gracefully
Ue5 - AI pursuit (blueprint, behavior tree)
阿里云Prometheus监控服务