如何实现每次构建生成唯一Allure附件并清理旧附件?
解决Allure附件堆积及自定义附件路径问题
一、构建后清理allure-report/data/attachments(不重置工作区)
如果不想重置整个工作区,只清理附件文件夹,直接在构建流程的收尾步骤里添加清理命令即可:
1. Shell/Linux环境
# 仅删除附件文件夹内的所有文件,保留文件夹本身 rm -rf allure-report/data/attachments/*
2. Windows环境
# 强制删除附件文件夹内的所有文件 del /F /S /Q allure-report\data\attachments\*
3. 测试脚本内集成清理逻辑
如果是在代码里控制,比如Python测试用例:
import os attachments_dir = "allure-report/data/attachments" if os.path.exists(attachments_dir): # 遍历文件夹删除所有文件 for file in os.listdir(attachments_dir): file_path = os.path.join(attachments_dir, file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(f"删除附件失败: {e}")
把这段代码放在测试套件的初始化/前置步骤里,每次运行测试前自动清理旧附件。
二、修复output/文件夹附件无法读取的问题
你遇到的output/文件夹为空、图片不存在的问题,大概率是图片生成路径错误或者生成后被误删,可以按以下步骤排查:
1. 确保图片生成路径正确
测试脚本里生成图片时,必须使用相对于工作区的绝对路径,避免相对路径导致的位置偏差。比如Python示例:
import os import uuid import allure from allure_commons.types import AttachmentType # 生成唯一文件名(避免重复) unique_filename = f"screenshot_{uuid.uuid4().hex}.png" # 构建output文件夹的绝对路径 output_dir = os.path.join(os.getcwd(), "output") # 确保文件夹存在(不存在则创建) os.makedirs(output_dir, exist_ok=True) # 图片的完整路径 img_full_path = os.path.join(output_dir, unique_filename) # 这里替换成你的截图/生成图片逻辑,比如用selenium截图: # driver.save_screenshot(img_full_path) # 确认图片存在后再添加到Allure if os.path.exists(img_full_path): allure.attach.file(img_full_path, name="测试截图", attachment_type=AttachmentType.PNG) else: print(f"图片不存在: {img_full_path}")
2. 检查CI环境的路径配置
如果是在Jenkins/GitLab CI等环境运行:
- 确认工作区路径是否正确,避免output文件夹被创建到了其他目录
- 检查是否有构建步骤(比如clean命令)误删了output文件夹
- 确保测试执行用户有output文件夹的读写权限
3. 验证Allure附件添加逻辑
Allure添加本地文件附件时,必须确保文件在测试执行的机器上存在,且路径可访问。如果是分布式执行,要确保output文件夹在各个节点都能被访问到(比如用共享存储)。
内容的提问来源于stack exchange,提问作者Crunchy
相关产品推荐
相关产品推荐

