You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Allure装饰器中传入变量以丰富测试报告数据?

在Allure中给步骤传入动态变量的实现方案

1. 测试函数装饰器场景

@allure.step装饰器是在函数定义阶段解析的,没法直接拿到函数执行时才传入的expected变量,以下两种方式可以解决:

方式一:利用装饰器的自动参数匹配

Allure的@allure.step支持直接使用函数参数名作为占位符,若测试数据能拆为单独参数,直接写参数名即可:

import allure

@allure.title("Do that")
@allure.step("Make sure that some_param == {expected}")
def test_1(expected, real):
    assert expected == real

如果必须保留data_for_test作为参数,也可以直接通过索引访问参数内的元素:

import allure

@allure.title("Do that")
@allure.step("Make sure that some_param == {data_for_test[0]}")
def test_1(data_for_test):
    expected, real = data_for_test
    assert expected == real

方式二:在函数内部使用动态步骤

要是觉得装饰器里写索引不够直观,也可以把步骤逻辑移到函数内部,用f-string动态拼接描述:

import allure

@allure.title("Do that")
def test_1(data_for_test):
    expected, real = data_for_test
    with allure.step(f"Make sure that some_param == {expected}"):
        assert expected == real

2. with代码块场景

这个场景直接用Python的f-string格式化字符串就能插入变量,some_var在执行with语句时已经定义,可直接读取:

def some_func():
    some_var = "qwe"
    with allure.step(f"Some text with some {some_var}"):
        pass

内容的提问来源于stack exchange,提问作者bananacatsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:39:40