栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

allure--常用配置项

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

allure--常用配置项

allure--常用配置选项
  • 参数化动态更新案例名称
  • allure清理上一次的运行记录
  • allure动态生成用例标题
  • 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 = '请求url:{}
' '测试结果:{}
' '请求方法:{}
' '实际结果:{}
' '错误结果:{}
' .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=hcudhciuhiu@qq.com 
freind=Mr.ma
  • 方式二:在allure的result目录下添加一个environment.xml

    
        Browser
        Chrome
    
    
Browser.Version
        63.0
    
    
        Stand
        Production
    

在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()

运行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934929.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号