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

如何用pytest编写校验JSON内容及对应磁盘文件可用性的测试用例

pytest 测试用例实现方案

依赖说明

pytest 没有内置专门用于文件路径、格式校验的专属模块,配合 Python 标准库即可实现全部需求,无需引入额外的外部依赖:

  • 路径存在校验使用标准库 pathlib 实现
  • JSON 格式校验使用标准库 json 模块实现
  • ZIP 格式完整性校验使用标准库 zipfile 模块实现

具体实现步骤

1. 公共逻辑复用:定义 fixture

通过 fixture 预加载待测试的目标 JSON 文件内容,避免每个用例重复编写文件加载逻辑:

import json
import pathlib
import zipfile
import pytest

# 替换为你实际生成的JSON文件路径
TARGET_JSON_PATH = "./output_record.json"

@pytest.fixture(scope="module")
def loaded_json():
    # 先校验生成的JSON本身格式合法
    try:
        with open(TARGET_JSON_PATH, "r", encoding="utf-8") as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        pytest.fail(f"生成的目标JSON格式非法:{str(e)}")

2. 路径存在性校验用例

遍历 JSON 中所有存储的文件路径,校验路径对应文件真实存在:

def test_all_file_paths_exist(loaded_json):
    missing_files = []
    for category, path_list in loaded_json.items():
        for file_path in path_list:
            p = pathlib.Path(file_path)
            if not p.is_file():
                missing_files.append(file_path)
    if missing_files:
        pytest.fail(f"存在缺失的文件:{', '.join(missing_files)}")

3. 文件格式合规性校验用例

根据文件后缀匹配对应的校验规则,可根据实际业务需要扩展其他格式的校验逻辑:

def test_all_file_format_valid(loaded_json):
    invalid_files = []
    for category, path_list in loaded_json.items():
        for file_path in path_list:
            p = pathlib.Path(file_path)
            if not p.exists():
                continue
            suffix = p.suffix.lower()
            try:
                if suffix == ".json":
                    # 校验JSON文件格式合法
                    with open(p, "r", encoding="utf-8") as f:
                        json.load(f)
                elif suffix == ".zip":
                    # 校验ZIP文件无损坏
                    with zipfile.ZipFile(p, "r") as zf:
                        bad_entry = zf.testzip()
                        if bad_entry:
                            invalid_files.append(f"{file_path}:ZIP内文件{bad_entry}损坏")
                # 其他格式校验可在此处扩展,比如图片、文档等
            except Exception as e:
                invalid_files.append(f"{file_path}:校验失败,原因{str(e)}")
    if invalid_files:
        pytest.fail(f"存在格式不合规的文件:{'; '.join(invalid_files)}")

可选优化项

  • 如果需要把每个路径的校验拆分为独立用例,方便快速定位出错路径,可以用 pytest.mark.parametrize 对所有路径做参数化处理
  • 测试函数写入功能时,可以配合 pytest 内置的 tmp_path fixture 生成临时目录做测试,避免污染正式环境的文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:27:03