最全的Pytest+Allure使用教程,建议收藏

Allure是开源的免费的自动化测试报告,支持Java,Python,我们来看看如何使用Python pytest与Allure整合,输出漂亮的测试报告。

一.Allure安装

windows:下载,解压,并配置环境变量:https://github.com/allure-framework/allure2/releases
mac:brew install allure

二.Allure报告结构

1.Overview:整体数据显示。

2.Suites:用例集合,按照套件和类分组的已执行测试的标准结构表示形式。

3.Behaviors:对于行为驱动的方法,此选项卡根据Epic、Feature和Story标记对测试结果进行分组。

4.Categories:“类别”选项卡提供了创建自定义缺陷分类以应用测试结果的方法。

5.Graphs:用图表显示测试数据中收集的不同统计数据,状态分解或严重性和持续时间图。

6.Packages:软件包选项卡表示测试结果的树状布局,按不同的包名分组。

7.Timeline:时间轴选项卡可视化测试执行的回顾,allure适配器收集测试的精确时间,在这个选项卡上,它们相应地按照顺序或并行的时间结构排列。

三.安装Python依赖

windows:pip install allure-pytest
mac:pip3 install allure-pytest

这将安装Allure-pytest和Allure-python-commons包,以生成与Allure 2兼容的报告数据。

1.Windows

2.Mac

四.基本用法

Allure监听器在测试执行期间会收集结果,只需添加alluredir选项,并选择输出的文件路径即可。

pytest --alluredir=./allure-results

# 执行此命令,将在默认浏览器中显示生成的报告
allure serve ./allure-results

五.Allure注解说明:

六.具体使用方法(以Mac系统为例)

基本报告:可以在Allure报告中看到所有默认的pytest状态: 只有由于断言错误而未成功的测试才会被标记为失败,任何其他异常都会导致测试状态失败。

import allure
import pytest

@allure.feature('test_success')
def test_success():
    """this test succeeds"""
    assert True

@allure.feature('test_failure')
def test_failure():
    """this test fails"""
    assert False

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

@allure.feature('test_broken')
def test_broken():
    raise Exception('oops')

if __name__ == '__main__':
    # pytest.main(["-s","allure-test.py"])
    '''
    -q: 安静模式, 不输出环境信息
    -v: 丰富信息模式, 输出更详细的用例执行信息
    -s: 显示程序中的print/logging输出
    '''
    pytest.main(['-s', '-q','test_allure02.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

命令行输入allure generate -c -o allure-reports,即可在当前路径下生成测试报告。(-c:清空历史数据,-o:指定输出测试报告路径),如果使用allure serve allure-results,则会在系统默认目录下生成测试报告

七.支持Pytest特性

Allure报告支持的一些常见Pytest特性,包括xfails、fixture和finalizers、marks、条件跳过和参数化。

1.xfail

功能未实现或者有Bug尚未修复,当测试通过时尽管会失败,它是一个xpass,将在测试摘要中报告。

import allure
import pytest

@allure.feature('test_xfail_expected_failure')
@pytest.mark.xfail(reason='该功能尚未实现')
def test_xfail_expected_failure():
    print("该功能尚未实现")
    assert False

@allure.feature('test_xfail_unexpected_pass')
@pytest.mark.xfail(reason='该Bug尚未修复')
def test_xfail_unexpected_pass():
    print("该Bug尚未修复")
    assert True

if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure02.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

2.skipif

当条件为True,跳过执行

import sys
import allure
import pytest

'''当条件为True则跳过执行'''
@allure.feature("test_skipif")
@pytest.mark.skipif("darwin" in sys.platform,reason="如果操作系统是Mac则跳过执行")
def test_skipif():
    print("操作系统是Mac,test_skipif()函数跳过执行")

# --clean-alluredir:每次执行前清空数据,这样在生成的报告中就不会追加,只显示当前执行的用例
if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure02.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

3.parametrize

可以使用@Pytest.mark.paramtrize进行参数化,所有参数名称和值都将被捕获到报告中。

import os
import allure
import pytest

@allure.step
def simple_step(step_param1, step_param2 = None):
    pass

@pytest.mark.parametrize('param1', [True, False], ids=['1', '2'])
def test_parameterize_with_id(param1):
    simple_step(param1)

@pytest.mark.parametrize('param1', [True, False])
@pytest.mark.parametrize('param2', ['1', '2'])
def test_parametrize_with_two_parameters(param1, param2):
    simple_step(param1, param2)

# --clean-alluredir:每次执行前清空数据,这样在生成的报告中就不会追加,只显示当前执行的用例
if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure03.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

4.feature

模块名称,功能点描述

5.step

Allure生成的测试报告最重要的一点就是,它允许对每个测试用例进行非常详细的步骤说明

import os
import allure
import pytest

@allure.step("步骤二")
def passing_step():
    pass


@allure.step("步骤三")
def step_with_nested_steps():
    nested_step()


@allure.step("步骤四")
def nested_step():
    nested_step_with_arguments(1, 'abc')


@allure.step("步骤五")
def nested_step_with_arguments(arg1, arg2):
    pass


@allure.step("步骤一")
def test_with_nested_steps():
    passing_step()
    step_with_nested_steps()


if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure04.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

6.attach

Allure测试报告可以显示许多不同类型的附件,这些附件可以补充测试、步骤或结果。可以使用allure.attach(body、name、attachment_type、extension)调用来创建附件。

  • body:要显示的内容(附件)
  • name:附件名字
  • attachment_type:附件类型,是allure.attachment_type里面的其中一种
  • extension:附件的扩展名
  • source:文件路径

语法一:allure.attach(body,name,attachment_type,extension)

语法二:allure.attach.file(source,name,attachment_type,extension)

import os
import allure
import pytest

@pytest.fixture
def attach_file_in_module_scope_fixture_with_finalizer(request):
    allure.attach('在fixture前置操作里面添加一个附件txt', 'fixture前置附件', allure.attachment_type.TEXT)

    def finalizer_module_scope_fixture():
        allure.attach('在fixture后置操作里面添加一个附件txt', 'fixture后置附件',allure.attachment_type.TEXT)
    request.addfinalizer(finalizer_module_scope_fixture)


def test_with_attacments_in_fixture_and_finalizer(attach_file_in_module_scope_fixture_with_finalizer):
    pass


def test_multiple_attachments():
    allure.attach('<head></head><body>html page</body>', 'Attach with HTML type', allure.attachment_type.HTML)
    allure.attach.file('/Users/mrjade/Downloads/happy-new-year.html', attachment_type=allure.attachment_type.HTML)


if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure05.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

7.description

描述类信息,比如对函数的描述,说明这个函数的作用,如:注册接口。

语法一:@allure.description()

语法二:@allure.description_html()

import os
import allure
import pytest

@allure.description_html("""
<h1>这是html描述</h1>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr align="center">
    <td>jade</td>
    <td>mr</td>
    <td>18</td>
  </tr>
  <tr align="center">
    <td>road</td>
    <td>Tester</td>
    <td>18</td>
  </tr>
</table>
""")
def test_html_description():
    assert True

@allure.description("""多行描述""")
def test_description_from_decorator():
    assert 42 == int(6 * 7)

def test_unicode_in_docstring_description():
    """在函数下方描述也可"""
    assert 42 == int(6 * 7)


if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure06.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

8.title

  • 添加测试用例标题,通俗来讲就是将函数名直接改成我们想要的,使得测试用例的标题更具有可读性
  • 支持占位符传递关键字参数(动态标题,结合@pytest.mark.parametrize使用)
import os
import allure
import pytest

@allure.title("断言2+2=4")
def test_with_a_title():
    assert 2 + 2 == 4

@allure.title("动态标题: {param1} + {param2} = {expected}")
@pytest.mark.parametrize('param1,param2,expected', [(2, 2, 4),(1, 2, 5)])
def test_with_parameterized_title(param1, param2, expected):
    assert param1 + param2 == expected

@allure.title("这是个动态标题,会被替换")
def test_with_dynamic_title():
    assert 2 + 2 == 4
    allure.dynamic.title('测试结束,做为标题')


if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure07.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

9.link

将测试报告与缺陷跟踪或测试管理系统整合,@allure.link、@allure.issue和@allure.testcase。

import os
import allure
import pytest

@allure.link('https://www.cnblogs.com/mrjade/')
def test_with_link():
    pass


@allure.link('https://www.cnblogs.com/mrjade/', name='点击进入mrjade博客园')
def test_with_named_link():
    pass


@allure.issue('https://github.com/allure-framework/allure-python/issues/642', 'bug issue链接')
def test_with_issue_link():
    pass


@allure.testcase("https://www.cnblogs.com/mrjade/", '测试用例地址')
def test_with_testcase_link():
    pass

if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure08.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

10.Retries

Allure允许测试报告中显示单个测试运行期间重新执行的测试的信息,以及一段时间内测试执行的历史,需与Pytest插件结合使用。

windows:pip install pytest-rerunfailures
mac:pip3 install pytest-rerunfailures


import os
import allure
import random
import time
import pytest


@allure.step
def passing_step():
    pass


@allure.step
def flaky_broken_step():
    if random.randint(1, 5) != 1:
        raise Exception('Broken!')


"""需安装【pip3 install pytest-rerunfailures】"""
@pytest.mark.flaky(reruns=3, reruns_delay=1)  # 如果失败则延迟1s后重试
def test_broken_with_randomized_time():
    passing_step()
    time.sleep(random.randint(1, 3))
    flaky_broken_step()

if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure09.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

11.tags

我们希望对执行的测试用例保持灵活性。Pytest允许使用标记修饰符@pytest.mark,Allure提供了3种类型的标记装饰符

  • BDD样式的标记装饰器
  • @allure.epic:敏捷里面的概念,定义史诗,往下是feature
  • @allure.feature:功能点的描述,理解成模块往下是story
  • @allure.story:故事,往下是title
  • 优先级(严重程度)标记装饰器 根据严重程度来标记你的测试。严重程度装饰器,它使用一个allure.severity_level enum值作为参数。如:@allure.severity(allure.severity_level.TRIVIAL)
  • 自定义标记装饰器
import os
import allure
import pytest

@pytest.fixture(scope="session")
def login_fixture():
    print("前置登录")


@allure.step("步骤1")
def step_1():
    print("操作步骤1")


@allure.step("步骤2")
def step_2():
    print("操作步骤2")


@allure.step("步骤3")
def step_3():
    print("操作步骤3")


@allure.step("步骤4")
def step_4():
    print("操作步骤4")

@allure.epic("会员项目")
@allure.feature("登录")
class TestAllureALL:

    @allure.testcase("https://www.cnblogs.com/mrjade/", '测试用例,点我一下')
    @allure.issue("https://github.com/allure-framework/allure-python/issues/642", 'Bug 链接,点我一下')
    @allure.title("用户名错误")
    @allure.story("登录测试用例1")
    @allure.severity(allure.severity_level.TRIVIAL) # 不重要的
    # @allure.severity(allure.severity_level.MINOR) # 轻微的
    # @allure.severity(allure.severity_level.BLOCKER)  # 阻塞的
    # @allure.severity(allure.severity_level.CRITICAL)  # 严重的
    # @allure.severity(allure.severity_level.NORMAL)  # 普通的
    def test_case_1(self):
        """
        公众号:测试工程师成长之路
        """
        print("测试用例1")
        step_1()
        step_2()

    @allure.title("用户名正确,密码错误")
    @allure.story("登录测试用例2")
    def test_case_2(self):
        print("测试用例2")
        step_1()
        step_3()


@allure.epic("订单项目")
@allure.feature("支付")
class TestAllureALL2:
    @allure.title("支付成功")
    @allure.story("支付测试用例例1")
    def test_case_1(self, login_fixture):
        print("支付测试用例例1")
        step_3()

    @allure.title("支付失败")
    @allure.story("支付测试用例例2")
    def test_case_2(self, login_fixture):
        print("支付测试用例例2")
        step_4()

if __name__ == '__main__':
    pytest.main(['-s', '-q','test_allure10.py','--clean-alluredir','--alluredir=allure-results'])
    os.system(r"allure generate -c -o allure-report")

12.environment:环境信息

  • 新建environment.properties文件
  • 编写如下环境信息
systemVersion=mac
pythonVersion=3.9
allureVersion=2.10.0
baseUrl=http://192.168.1.1:8080
projectName=SIT
author=TesterRoad

  • 将environment.properties放在项目根目录或其它目录,在执行测试用例时将其复制到allure-results目录下
# coding=utf-8 

import pytest
import os

if __name__ == '__main__':
    pytest.main(['-s', '-q','./','--clean-alluredir','--alluredir=allure-results'])
    os.system('cp environment.properties ./allure-results/environment.properties')
    os.system("allure generate -c -o allure-report")

八.Pytest执行所有.py文件

1.新建run.py文件,编写如下代码

# coding=utf-8 

import pytest
import os

if __name__ == '__main__':
    pytest.main(['-s', '-q','./','--clean-alluredir','--alluredir=allure-results'])
    os.system('cp environment.properties ./allure-results/environment.properties')
    os.system("allure generate -c -o allure-report")

2.查看报告

九.参考链接

https://docs.qameta.io/allure-report/

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值