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

Lambda中pytest首次运行成功,后续触发报KeyError:'total_fail'问题

问题分析与解决方案

问题原因

AWS Lambda的执行容器是可复用的,第一次运行测试后,pytest_html_reporter插件生成的报告存档数据会留在/tmp目录中。第二次触发测试时,插件会尝试加载旧的存档数据,但新测试的报告数据结构与旧存档不匹配,导致读取'total_fail'键时抛出KeyError。

解决方法

1. 禁用报告存档功能

直接通过pytest命令参数禁用存档,避免插件读取旧数据。修改pytest启动参数,添加--html-report-no-archive:

import json
import pytest

def lambda_handler(event, context):
    print(f'{event}')
    event_raw_path = event['rawPath']

    if event_raw_path == '/run/test':
        # 禁用存档功能,避免加载旧报告数据
        test_run = pytest.main(["--html-report=/tmp/report.html", "--html-report-no-archive"])
        if test_run == pytest.ExitCode.OK:
            result = "PASS"
        else:
            result = "FAIL"
        return {
            'statusCode': 200,
            'body': json.dumps('Test Complete, Result - ' + result),
            "headers": {
                "Content-Type": "application/json"
            }
        }

    else:
        return {
            'statusCode': 400,
            'body': json.dumps('Wrong Url Entered'),
            "headers": {
                "Content-Type": "application/json"
            }
        }

2. 每次运行前清理/tmp目录的报告文件

如果需要保留存档功能,可以在运行测试前删除旧的报告及存档文件:

import json
import pytest
import os
import shutil

def lambda_handler(event, context):
    print(f'{event}')
    event_raw_path = event['rawPath']

    if event_raw_path == '/run/test':
        # 清理旧报告文件和存档目录
        report_path = "/tmp/report.html"
        archive_dir = "/tmp/pytest_html_reporter_archive"
        if os.path.exists(report_path):
            os.remove(report_path)
        if os.path.exists(archive_dir):
            shutil.rmtree(archive_dir)
        
        test_run = pytest.main(["--html-report=/tmp/report.html"])
        if test_run == pytest.ExitCode.OK:
            result = "PASS"
        else:
            result = "FAIL"
        return {
            'statusCode': 200,
            'body': json.dumps('Test Complete, Result - ' + result),
            "headers": {
                "Content-Type": "application/json"
            }
        }

    else:
        return {
            'statusCode': 400,
            'body': json.dumps('Wrong Url Entered'),
            "headers": {
                "Content-Type": "application/json"
            }
        }

补充说明

Lambda的/tmp目录在容器复用期间会保留文件,因此任何依赖本地文件状态的工具都需要处理残留数据问题。禁用存档是最简单直接的方案,若需要历史报告,可以将生成的报告上传到S3等持久化存储,而不是依赖Lambda的本地目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:02:34