一、Allure 装饰器全面解析

1.@allure.feature - 功能模块标记
用于标记测试用例所属的功能模块,在报告中会按feature分组展示

@allure.feature("用户管理模块")
class TestUserManagement:
    
    def test_create_user(self):
        """创建用户测试"""
        pass
        
    def test_delete_user(self):
        """删除用户测试"""
        pass

2.@allure.story - 用户故事标记
作用:在feature下进一步细分测试场景,通常对应一个用户故事

@allure.feature("订单模块")
@allure.story("订单创建流程")
def test_create_order_with_single_item():
    """测试创建包含单个商品的订单"""
    pass

@allure.feature("订单模块")  
@allure.story("订单创建流程")
def test_create_order_with_multiple_items():
    """测试创建包含多个商品的订单"""
    pass

3.@allure.title - 自定义测试标题
为测试用例设置更易读的标题,支持动态生成

@pytest.mark.parametrize("username", ["admin", "test_user"])
@allure.title("登录测试:使用用户名 {username}")
def test_login_with_different_users(username):
    pass

# 或者在测试方法内动态设置
def test_dynamic_title():
    allure.dynamic.title("动态生成的测试标题 - " + str(datetime.now()))

4.@allure.description / @allure.description_html
为测试添加详细描述,支持纯文本和HTML格式

@allure.description("""
这是一个详细的测试描述:
1. 首先执行A操作
2. 然后验证B结果
3. 最后检查C状态
""")
def test_with_text_description():
    pass

@allure.description_html("""
<h1>HTML 描述示例</h1>
<table style="width:100%">
  <tr>
    <th>步骤</th>
    <th>预期</th>
  </tr>
  <tr>
    <td>输入用户名</td>
    <td>用户名框显示内容</td>
  </tr>
</table>
""")
def test_with_html_description():
    pass

5.@allure.severity - 优先级标记
标记测试用例的重要程度,共5个级别

@allure.severity(allure.severity_level.BLOCKER)
def test_critical_function():
    """阻塞性缺陷,系统无法运行"""
    pass

@allure.severity(allure.severity_level.CRITICAL) 
def test_important_feature():
    """关键功能缺陷"""
    pass

@allure.severity(allure.severity_level.NORMAL)
def test_regular_case():
    """普通测试用例"""
    pass

@allure.severity(allure.severity_level.MINOR)
def test_secondary_feature():
    """次要功能测试"""
    pass

@allure.severity(allure.severity_level.TRIVIAL)
def test_ui_details():
    """UI细节测试"""
    pass

6.@allure.step - 测试步骤分解
将测试分解为多个步骤,使报告更易读

def test_complex_workflow():
    login()
    navigate_to_dashboard()
    create_order()
    verify_order()
    
@allure.step("登录系统")
def login():
    with allure.step("输入用户名"):
        pass
    with allure.step("输入密码"):
        pass
    with allure.step("点击登录按钮"):
        pass

@allure.step("导航到仪表盘")  
def navigate_to_dashboard():
    pass

7.@allure.link / @allure.issue / @allure.testcase
添加外部链接,关联需求/缺陷/测试用例

@allure.link("https://www.yourproject.com", name="项目主页")
@allure.issue("BUG-123", "https://bugtracker/bug/123") 
@allure.testcase("TC-456", "https://testmanagement/testcase/456")
def test_with_external_links():
    pass

8.@allure.tag / @allure.label - 自定义标签
为测试添加自定义分类标签

@allure.tag("smoke", "regression")
@allure.label("owner", "tester1")
@allure.label("layer", "UI")
def test_with_custom_tags():
    pass

9.@allure.attach - 添加附件
在报告中附加测试数据、截图、日志等

def test_with_attachments():
    # 附加文本
    allure.attach("测试数据内容", name="测试数据", attachment_type=allure.attachment_type.TEXT)
    
    # 附加JSON
    allure.attach('{"name": "value"}', name="JSON数据", attachment_type=allure.attachment_type.JSON)
    
    # 附加图片(需要实际文件)
    # allure.attach.file("./screenshot.png", name="页面截图", attachment_type=allure.attachment_type.PNG)
    
    # 附加HTML
    allure.attach("<h1>HTML内容</h1>", name="HTML附件", attachment_type=allure.attachment_type.HTML)

10.@allure.parent_suite / @allure.suite / @allure.sub_suite
组织测试套件的层级关系

@allure.parent_suite("电商平台测试")
@allure.suite("订单模块")
@allure.sub_suite("创建订单")
class TestOrderCreation:
    pass

11.@allure.flaky - 标记不稳定测试
标记可能随机失败的测试用例

@allure.flaky
def test_unstable_feature():
    import random
    assert random.choice([True, False])

12.@allure.epic / @allure.feature / @allure.story
Agile测试中的层级关系标记

@allure.epic("电商平台")
@allure.feature("支付系统")
@allure.story("信用卡支付")
def test_credit_card_payment():
    pass

二、完整测试案例演示

# 生成HTML报告
allure generate ./results -o ./report --clean
import pytest
import allure
import random

@allure.epic("电商平台")
@allure.feature("订单管理")
class TestOrderManagement:
    
    @allure.story("创建订单")
    @allure.title("验证普通用户创建订单流程")
    @allure.severity(allure.severity_level.CRITICAL)
    @allure.tag("smoke", "order")
    @allure.label("owner", "teamA")
    def test_create_order_normal_user(self):
        """测试普通用户创建标准订单的完整流程"""
        with allure.step("用户登录"):
            self.login("normal_user", "password123")
            
        with allure.step("添加商品到购物车"):
            items = ["商品A", "商品B"]
            for item in items:
                self.add_to_cart(item)
                allure.attach(f"已添加{item}", name="添加商品")
                
        with allure.step("结算订单"):
            order_id = self.checkout()
            allure.attach(str(order_id), name="生成的订单ID", attachment_type=allure.attachment_type.TEXT)
            
        with allure.step("验证订单状态"):
            status = self.get_order_status(order_id)
            assert status == "待付款", f"订单状态应为'待付款', 实际为'{status}'"
            
    @allure.story("订单取消")
    @allure.title("验证VIP用户取消订单的特殊流程")
    @allure.severity(allure.severity_level.NORMAL)
    def test_vip_cancel_order(self):
        with allure.step("VIP用户登录"):
            self.login("vip_user", "vip_password")
            
        with allure.step("创建测试订单"):
            order_id = self.create_test_order()
            
        with allure.step("取消订单"):
            result = self.cancel_order(order_id)
            
        with allure.step("验证取消结果"):
            assert result["status"] == "success"
            assert "取消成功" in result["message"]
            
    @allure.story("异常流程")
    @allure.title("验证库存不足时的订单创建")
    @allure.severity(allure.severity_level.MINOR)
    def test_create_order_with_low_stock(self):
        with allure.step("设置测试商品库存为1"):
            self.set_stock("限量商品", 1)
            
        with allure.step("用户A购买商品"):
            self.login("userA", "passA")
            self.add_to_cart("限量商品")
            order_id_A = self.checkout()
            
        with allure.step("用户B尝试购买同一商品"):
            self.login("userB", "passB")
            self.add_to_cart("限量商品")
            with pytest.raises(InventoryException) as e:
                self.checkout()
                allure.attach(str(e.value), name="库存不足错误信息")
                
    @allure.step("用户登录 {username}")
    def login(self, username, password):
        print(f"模拟登录: {username}/{password}")
        return True
        
    @allure.step("添加商品 {item_name} 到购物车")
    def add_to_cart(self, item_name):
        print(f"添加商品: {item_name}")
        return True
        
    @allure.step("结算订单")
    def checkout(self):
        order_id = f"ORDER_{random.randint(1000,9999)}"
        print(f"生成订单: {order_id}")
        return order_id
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐