pytest结合allure

发布于:2025-03-07 ⋅ 阅读:(86) ⋅ 点赞:(0)

一、文档

allure文档

二、指令

1、运行测试并生成 allure 数据

pytest --alluredir=./allure_results

2、生成并打开报告

allure serve ./allure_results

三、装饰器

3.1 @allure.step装饰器

将函数或方法标记为测试步骤,并在 Allure 报告中展示步骤层级。
直接在测试方法或函数上添加 @allure.step 装饰器,并可自定义步骤名称,支持使用{}占位符。

import allure

@allure.step("打开应用首页")
def open_homepage():
    print("-----------open--------------")
    pass

# 使用 {} 占位符将变量嵌入步骤名称,参数自动填充。
@allure.step("输入用户名和密码: {username},{password}")
def input_username(username, password):
    print(f"-----------{username}--------------")
    pass

# 步骤可以嵌套,形成清晰的逻辑层级
def test_login():
    open_homepage()
    input_username("test_user","1234")

conftest.py与@allure.step结合,显示单独的“前置/后置”树,用于配置初始化和销毁。
conftest.py:

import pytest
import allure

@allure.step("step in conftest.py for setup")
def conftest_test():
    pass

@allure.step("step in conftest.py for teardown")
def conftest_test_of_teardown():
    pass

@pytest.fixture(autouse=True)
def fixture_with_conftest_test():
    conftest_test()
    yield
    conftest_test_of_teardown()

运行结果:
在这里插入图片描述

3.2 @allure.description装饰器

为测试用例添加详细描述

1、@allure.description提供描述字符串
2、@allure.description_html添加html格式的描述
3、仅从测试方法的文档字符串获取描述

import pytest
import allure

def test_unicode_in_description():
    """
    unicode描述使用不同的国家语言
    hello
    こんにちは
    你好伙计
    """
    assert 42 == int(6 * 7)


@pytest.mark.parametrize("username", ["user1", "user2"])
@allure.description("测试不同用户名的登录兼容性:username={username}")
def test_login_compatibility(username):
    pass

@allure.description_html("""
<h1>添加html格式的描述</h1>
""")
def test_description_html():
    pass


@allure.description("动态描述,可替换开始的描述")
def test_login_change():
    pass
    allure.dynamic.description("测试用例执行完了,更改描述")

在这里插入图片描述

3.3 @allure.title装饰器

使测试标题更具可读性,标题支持占位符并支持动态替换

import pytest
import allure

@allure.title("@allure.title使测试标题更具可读性,标题支持占位符并支持动态替换")
def test_with_a_title():
    assert 2 + 2 == 4


@pytest.mark.parametrize("param1,param2,expected", [(1, 1, 2), (1, 3, 5)])
@allure.title("标题包含动态参数:{param1},{param2}")
def test_with_parametrize_title(param1, param2, expected):
    assert param1 + param2 == expected

@allure.title("动态描述,可替换开始的描述")
def test_title_update():
    pass
    allure.dynamic.title("测试用例执行完了,更改标题")

运行结果:
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到