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

如何将pytest测试报告直接保存至AWS S3?

直接将pytest测试报告上传至AWS S3的方案

目前你可以通过两种核心方式跳过本地存储,直接把pytest-html生成的测试报告上传到AWS S3:

方法一:通过pytest钩子捕获报告内容直接上传

利用pytest-html提供的pytest_html_report_generated钩子,在报告生成后直接获取HTML内容并上传到S3,无需写入本地文件。

步骤:

  1. 安装依赖:
pip install pytest-html boto3
  1. 在项目的conftest.py中修改配置:
import boto3
import os
from botocore.exceptions import ClientError
from datetime import datetime

def pytest_configure(config):
    config._metadata = None
    # 取消本地路径设置,由钩子处理上传
    config.option.htmlpath = None

def pytest_html_report_generated(report):
    # 从环境变量读取S3配置
    s3_bucket = os.getenv("S3_REPORT_BUCKET")
    # 生成带时间戳的报告路径,避免覆盖旧报告
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    s3_key = os.getenv("S3_REPORT_KEY", f"test-reports/report_{timestamp}.html")

    s3_client = boto3.client("s3")
    try:
        # 直接上传HTML内容到S3
        s3_client.put_object(
            Bucket=s3_bucket,
            Key=s3_key,
            Body=report.html,
            ContentType="text/html"
        )
        print(f"测试报告已上传至S3: s3://{s3_bucket}/{s3_key}")
    except ClientError as e:
        print(f"上传S3失败: {str(e)}")
        # 可选:上传失败时抛出异常终止流程
        raise

方法二:使用S3文件系统直接写入

借助s3fs库将S3挂载为虚拟文件系统,让pytest-html直接把报告写入S3路径,无需额外上传步骤。

步骤:

  1. 安装依赖:
pip install pytest-html s3fs
  1. 在conftest.py中配置:
import s3fs
import os
from datetime import datetime

def pytest_configure(config):
    config._metadata = None
    s3_bucket = os.getenv("S3_REPORT_BUCKET")
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    s3_key = os.getenv("S3_REPORT_KEY", f"test-reports/report_{timestamp}.html")
    
    # 设置pytest-html输出路径为S3地址
    config.option.htmlpath = f"s3://{s3_bucket}/{s3_key}"

    # 初始化S3文件系统,自动读取环境变量或IAM角色凭证
    fs = s3fs.S3FileSystem()
    # 提前创建报告目录(如果不存在)
    report_dir = "/".join(s3_key.split("/")[:-1])
    if not fs.exists(f"{s3_bucket}/{report_dir}"):
        fs.makedirs(f"{s3_bucket}/{report_dir}")

注意事项

  • 权限配置:确保运行测试的实体(EC2实例、容器、本地机器)拥有S3的PutObject权限,可通过IAM策略配置。
  • 凭证管理:避免硬编码AWS凭证,优先使用IAM角色(适用于AWS托管服务)或环境变量AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY。
  • 异常处理:根据业务需求添加上传失败的容错逻辑,比如重试机制或告警通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:16:52