百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

pytest + allure生成测试报告 pytest-allure

zhezhongyun 2024-12-15 17:54 26 浏览

Allure 是一款轻量级、支持多语言的开源自动化测试报告生成框架,由Java语言开发,可以集成到 Jenkins。 pytest 测试框架支持Allure 报告生成。

pytest也可以生成junit格式的xml报告和HTML报告,命令如下:

pytest test_demo.py --junitxml=report.xml
pytest test_demo.py --html=report.html #需要安装插件:pip install pytest-html

Allure 报告更加灵活美观,本文介绍如何使用pytest 生成 allure测试报告

环境安装

安装allure

  1. allure包下载:https://github.com/allure-framework/allure2/releases
  2. 解压 -> 进入bin目录 -> 运行allure.bat,
  3. 把bin目录加入PATH环境变量

allure官网 : http://allure.qatools.ru/

allure文档 : https://docs.qameta.io/allure/#

安装 allure-pytest插件

pip install allure-pytest

生成Allure报告

运行

pytest [测试文件] -s -q --alluredir=./result #--alluredir用于指定存储测试结果的路径)

查看测试报告

方式一:直接打开默认浏览器展示报告

allure serve ./result/

方式二:从结果生成报告

  • 生成报告allure generate ./result/ -o ./report/ --clean (覆盖路径加--clean)
  • 打开报告allure open -h 127.0.0.1 -p 8883 ./report/

实例代码:https://docs.qameta.io/allure/#_pytest

test_allure.py:

import pytest

def test_success():
    """this test succeeds"""
    assert True

def test_failure():
    """this test fails"""
    assert False

def test_skip():
    """this test is skipped"""
    pytest.skip('for a reason!')

def test_broken():
    raise Exception('oops')

方法1

执行测试用例:

pytest test_allure.py --alluredir=./result/1

打开报告:

> allure serve ./result/1
Generating report to temp directory...
Report successfully generated to C:\Users\10287\AppData\Local\Temp\6968593833275403330\allure-report
Starting web server...
2020-10-25 20:59:42.368:INFO::main: Logging initialized @4873ms to org.eclipse.jetty.util.log.StdErrLog
Server started at <http://169.254.57.162:60084/>. Press <Ctrl+C> to exit

方法2

allure generate ./result/1 -o ./report/1/ --clean
allure open -h 127.0.0.1 -p 8883 ./report/1

浏览器访问地址 http://127.0.0.1:8883/ ,会显示跟上图一样的报告。

allure特性—feature, storry, step

可以在报告中添加用例描述信息,比如测试功能,子功能或场景,测试步骤以及测试附加信息:

  • @allure.feature(‘功能名称’):相当于 testsuite
  • @allure.story(’子功能名称‘):对应这个功能或者模块下的不同场景,相当于 testcase
  • @allure.step('步骤'):测试过程中的每个步骤,放在具体逻辑方法中allure.step('步骤') 只能以装饰器的形式放在类或者方法上面with allure.step:可以放在测试用例方法里面
  • @allure.attach('具体文本信息')附加信息:数据,文本,图片,视频,网页

测试用例 test_feature_story_step.py:

import pytest
import allure

@allure.feature("登录")
class TestLogin():
    @allure.story("登录成功")
    def test_login_success(self):
        print("登录成功")
        pass

    @allure.story("密码错误")
    def test_login_failure(self):
        with allure.step("输入用户名"):
            print("输入用户名")
        with allure.step("输入密码"):
            print("输入密码")
        print("点击登录")
        with allure.step("登录失败"):
            assert '1' == 1
            print("登录失败")
        pass

    @allure.story("用户名密码错误")
    def test_login_failure_a(self):
        print("用户名或者密码错误,登录失败")
        pass


@allure.feature("注册")
class TestRegister():
    @allure.story("注册成功")
    def test_register_success(self):
        print("测试用例:注册成功")
        pass

    @allure.story("注册失败")
    def test_register_failure(self):
        with allure.step("输入用户名"):
            print("输入用户名")
        with allure.step("输入密码"):
            print("输入密码")
        with allure.step("再次输入密码"):
            print("再次输入密码")
        print("点击注册")
        with allure.step("注册失败"):
            assert 1 + 1 == 2
            print("注册失败")
        pass

用例执行、生成报告

pytest test_feature_story.py --alluredir=./result/2 
allure generate ./result/2 -o ./report/2/ --clean
allure open -h 127.0.0.1 -p 8883 ./report/2

报告:

allure特性—link, issue, testcase

可以在测试报告中添加链接、bug地址、测试用例地址。

关联bug需要在用例执行时添加参数:

  • --allure-link-pattern=issue:[bug地址]{}
  • 例如:--allure-link-pattern=issue:http://www.bugfree.com/issue/{}

test_allure_link_issue.py:

import allure

@allure.link("http://www.baidu.com", name="baidu link")
def test_with_link():
    pass

@allure.issue("140","this is a issue")
def test_with_issue_link():
    pass

TEST_CASE_LINK = 'https://github.com'
@allure.testcase(TEST_CASE_LINK, 'Test case title')
def test_with_testcase_link():
    pass

用例执行:

pytest test_allure_link_issue.py --allure-link-pattern=issue:http://www.bugfree.com/issue/{} --alluredir=./result/3
allure serve ./result/3

报告:

点击 this is a issue,页面会跳转到bug页面:http://www.bugfree.com/issue/140

allure特性—severity

有时候在上线前,由于时间关系,我们只需要把重要模块测试一遍,在这样的场景下我们怎么实现呢?主要有三种方法:

  1. 可以使用pytest.mark来标记用例,Pytest测试框架(一):pytest安装及用例执行 介绍了这种方法。@pytest.mark.webtest # 添加标签 @pytest.mark.sec pytest -m "webtest and not sec"
  2. 通过 allure.feature, allure.story来实现pytest test_feature_story_step.py --allure-features "登录" //只运行登录模块 pytest test_feature_story_step.py --allure-stories "登录成功" //只运行登录成功子模块
  3. 通过 allure.severity按重要性级别来标记,有5种级别:Blocker级别:阻塞Critical级别:严重Normal级别:正常Minor级别:不太重要Trivial级别:不重要

test_allure_severity.py:

import allure
import pytest

def test_with_no_severity_label():
    pass

@allure.severity(allure.severity_level.TRIVIAL)
def test_with_trivial_severity():
    pass

@allure.severity(allure.severity_level.NORMAL)
def test_with_normal_severity():
    pass

@allure.severity(allure.severity_level.NORMAL)
class TestclassWithNormalSeverity(object):
    def test_inside_the_normalseverity_test_class(self):
        pass

    @allure.severity(allure.severity_level.CRITICAL)
    def test_inside_the_normal_severity_test_class_with_overriding_critical_severity(self):
        pass

用例执行:

pytest test_allure_severity.py --alluredir=./result/4 --allure-severities normal,critical
allure serve ./result/4

结果:

allure.attach()

可以在报告中附加文本、图片以及html网页,用来补充测试步骤或测试结果,比如错误截图或者关键步骤的截图。

test_allure_attach.py:

import allure
import pytest

def test_attach_text():
    allure.attach("纯文本", attachment_type=allure.attachment_type.TEXT)

def test_attach_html():
    allure.attach("<body>这是一段htmlbody块</body>", "html页面", attachment_type=allure.attachment_type.HTML)

def test_attach_photo():
    allure.attach.file("test.jpg", name="图片", attachment_tye=allure.attachment_type.JPG)

用例执行:

pytest test_allure_attach.py --alluredir=./result/5
allure serve ./result/5

结果:

pytest+selenium+allure报告

测试步骤:

  1. 打开百度
  2. 搜索关键词
  3. 搜索结果截图,保存到报告中
  4. 退出浏览器

test_allure_baidu.py:

import allure
import pytest
from selenium import webdriver
import time

@allure.testcase("http://www.github.com")
@allure.feature("百度搜索")
@pytest.mark.parametrize('test_data1', ['allure', 'pytest', 'unittest'])
def test_steps_demo(test_data1):
    with allure.step("打开百度网页"):
        driver = webdriver.Chrome("D:/testing_tools/chromedriver85/chromedriver.exe")
        driver.get("http://www.baidu.com")

    with allure.step("搜索关键词"):
        driver.find_element_by_id("kw").send_keys(test_data1)
        time.sleep(2)
        driver.find_element_by_id("su").click()
        time.sleep(2)

    with allure.step("保存图片"):
        driver.save_screenshot("./result/b.png")
        allure.attach.file("./result/b.png", attachment_type=allure.attachment_type.PNG)
        allure.attach('<head></head><body>首页</body>', 'Attach with HTML type', allure.attachment_type.HTML)

    with allure.step("退出浏览器"):
        driver.quit()

用例执行:

pytest test_allure_baidu.py --alluredir=./result/6
allure serve ./result/6

结果:

--THE END--


本文作者:hiyo
本文链接:https://www.cnblogs.com/hiyong/p/14163298.html

相关推荐

JPA实体类注解,看这篇就全会了

基本注解@Entity标注于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。name(可选):实体名称。缺省为实体类的非限定名称。该名称用于引用查询中的实体。不与@Tab...

Dify教程02 - Dify+Deepseek零代码赋能,普通人也能开发AI应用

开始今天的教程之前,先解决昨天遇到的一个问题,docker安装Dify的时候有个报错,进入Dify面板的时候会出现“InternalServerError”的提示,log日志报错:S3_USE_A...

用离散标记重塑人体姿态:VQ-VAE实现关键点组合关系编码

在人体姿态估计领域,传统方法通常将关键点作为基本处理单元,这些关键点在人体骨架结构上代表关节位置(如肘部、膝盖和头部)的空间坐标。现有模型对这些关键点的预测主要采用两种范式:直接通过坐标回归或间接通过...

B 客户端流RPC (clientstream Client Stream)

客户端编写一系列消息并将其发送到服务器,同样使用提供的流。一旦客户端写完消息,它就等待服务器读取消息并返回响应gRPC再次保证了单个RPC调用中的消息排序在客户端流RPC模式中,客户端会发送多个请...

我的模型我做主02——训练自己的大模型:简易入门指南

模型训练往往需要较高的配置,为了满足友友们的好奇心,这里我们不要内存,不要gpu,用最简单的方式,让大家感受一下什么是模型训练。基于你的硬件配置,我们可以设计一个完全在CPU上运行的简易模型训练方案。...

开源项目MessageNest打造个性化消息推送平台多种通知方式

今天介绍一个开源项目,MessageNest-可以打造个性化消息推送平台,整合邮件、钉钉、企业微信等多种通知方式。定制你的消息,让通知方式更灵活多样。开源地址:https://github.c...

使用投机规则API加快页面加载速度

当今的网络用户要求快速导航,从一个页面移动到另一个页面时应尽量减少延迟。投机规则应用程序接口(SpeculationRulesAPI)的出现改变了网络应用程序接口(WebAPI)领域的游戏规则。...

JSONP安全攻防技术

关于JSONPJSONP全称是JSONwithPadding,是基于JSON格式的为解决跨域请求资源而产生的解决方案。它的基本原理是利用HTML的元素标签,远程调用JSON文件来实现数据传递。如果...

大数据Doris(六):编译 Doris遇到的问题

编译Doris遇到的问题一、js_generator.cc:(.text+0xfc3c):undefinedreferenceto`well_known_types_js’查找Doris...

网页内嵌PDF获取的办法

最近女王大人为了通过某认证考试,交了2000RMB,官方居然没有给线下教材资料,直接给的是在线教材,教材是PDF的但是是内嵌在网页内,可惜却没有给具体的PDF地址,无法下载,看到女王大人一点点的截图保...

印度女孩被邻居家客人性骚扰,父亲上门警告,反被围殴致死

微信的规则进行了调整希望大家看完故事多点“在看”,喜欢的话也点个分享和赞这样事儿君的推送才能继续出现在你的订阅列表里才能继续跟大家分享每个开怀大笑或拍案惊奇的好故事啦~话说只要稍微关注新闻的人,应该...

下周重要财经数据日程一览 (1229-0103)

下周焦点全球制造业PMI美国消费者信心指数美国首申失业救济人数值得注意的是,下周一希腊还将举行第三轮总统选举需要谷歌日历同步及部分智能手机(安卓,iPhone)同步日历功能的朋友请点击此链接,数据公布...

PyTorch 深度学习实战(38):注意力机制全面解析

在上一篇文章中,我们探讨了分布式训练实战。本文将深入解析注意力机制的完整发展历程,从最初的Seq2Seq模型到革命性的Transformer架构。我们将使用PyTorch实现2个关键阶段的注意力机制变...

聊聊Spring AI的EmbeddingModel

序本文主要研究一下SpringAI的EmbeddingModelEmbeddingModelspring-ai-core/src/main/java/org/springframework/ai/e...

前端分享-少年了解过iframe么

iframe就像是HTML的「内嵌画布」,允许在页面中加载独立网页,如同在画布上叠加另一幅动态画卷。核心特性包括:独立上下文:每个iframe都拥有独立的DOM/CSS/JS环境(类似浏...