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

使用moto3 mock_s3上传文件时即便指定绝对路径仍报FileNotFound错误

错误根因

你遇到的报错和mock_s3没有关系:mock_s3仅模拟S3服务端的交互逻辑,upload_file读取本地文件的逻辑走的是真实的操作系统调用,报错本质是你运行测试的环境下,写死的/Absolute/path/test.zip路径对应的文件真实不存在。


两种解决方式

方式1:修复本地文件路径适配测试运行环境

不要写死固定绝对路径,推荐基于测试文件自身路径动态拼接:

import os
def test_head_object(s3_mock, s3, s3_object_header):
    # 获取当前测试脚本所在目录的绝对路径
    test_file_dir = os.path.dirname(os.path.abspath(__file__))
    # 假设test.zip和当前测试脚本放在同一目录下,拼接得到目标文件的绝对路径
    local_zip_path = os.path.join(test_file_dir, "test.zip")
    
    s3_mock.create_bucket(Bucket="my-bucket")
    # 可选:提前校验文件是否存在,方便排查路径问题
    if not os.path.exists(local_zip_path):
        raise ValueError(f"测试文件缺失:{local_zip_path}")
    s3_mock.upload_file(local_zip_path, 'my-bucket', 'test.zip')

方式2:无本地文件依赖的更优测试写法

单元测试尽量不要依赖项目外的本地文件,你可以直接用put_object替代upload_file,直接往模拟S3中写入内容,完全不需要本地真实文件:

def test_head_object(s3_mock, s3, s3_object_header):
    s3_mock.create_bucket(Bucket="my-bucket")
    # 直接写入模拟的文件内容,可根据测试需要自定义内容/大小
    s3_mock.put_object(
        Bucket="my-bucket",
        Key="test.zip",
        Body=b"test zip content"
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:30:04