如何用Python实现基于配置动态更新JSON测试文件?
实现方案
核心思路
通过对比配置列表start_values和测试JSON文件中的前缀条目,自动完成前缀替换、测试语句更新、冗余条目清理三个核心操作,确保两者同步。
假设的文件结构
- 配置列表:可直接在代码中定义,或从单独配置文件导入,示例:
start_values = ["cows", "cats"] # 修改后的目标前缀列表 - 测试JSON文件(
test_cases.json)初始内容:{ "dogs": [ "dogs are loyal pets", "dogs love chasing balls" ], "cats": [ "cats like napping in sun" ] }
Python实现代码
import json import shutil def sync_test_cases(start_values, test_file_path): # 先备份旧测试文件,防止数据丢失 shutil.copy(test_file_path, f"{test_file_path}.bak") # 1. 读取现有测试用例JSON with open(test_file_path, 'r', encoding='utf-8') as f: test_cases = json.load(f) old_prefixes = set(test_cases.keys()) new_prefixes = set(start_values) new_test_cases = {} # 遍历新前缀,处理每个条目 for prefix in start_values: # 查找需要替换的旧前缀(旧前缀不在新列表,且测试语句以该旧前缀开头) matched_old_prefix = None for old_p in old_prefixes: if old_p not in new_prefixes and test_cases[old_p] and test_cases[old_p][0].startswith(old_p): matched_old_prefix = old_p break if matched_old_prefix: # 替换测试语句中的旧前缀为新前缀(仅替换开头的一次) updated_tests = [test.replace(matched_old_prefix, prefix, 1) for test in test_cases[matched_old_prefix]] new_test_cases[prefix] = updated_tests old_prefixes.remove(matched_old_prefix) else: # 新前缀已存在则保留原用例,否则生成默认测试语句 new_test_cases[prefix] = test_cases.get(prefix, [f"{prefix} is a test case", f"{prefix} example"]) # 3. 写入更新后的测试用例到JSON文件 with open(test_file_path, 'w', encoding='utf-8') as f: json.dump(new_test_cases, f, indent=2, ensure_ascii=False) # 调用示例 if __name__ == "__main__": target_start_values = ["cows", "cats"] sync_test_cases(target_start_values, "test_cases.json")
代码说明
- 备份机制:先复制旧测试文件作为备份,避免修改失误导致数据丢失。
- 读取与对比:加载现有测试用例,提取新旧前缀集合,明确需要更新的内容。
- 前缀替换:针对被移除的旧前缀,匹配对应的测试语句并替换开头的前缀为新值,确保测试用例逻辑同步。
- 生成新用例:新前缀若已有对应测试用例则保留,无则生成默认语句,可根据需求自定义默认内容。
- 写入文件:将更新后的内容格式化写入原文件,覆盖旧数据。
扩展优化
- 精准映射替换:如果需要批量指定替换关系,可维护映射字典(如
prefix_map = {"dogs": "cows", "birds": "ducks"}),代码中优先使用映射关系处理,避免自动匹配的误差。 - 配置分离:将
start_values放在单独的config.py或config.json中,避免硬编码,方便日常维护。
内容的提问来源于stack exchange,提问作者Satyen Singh
相关产品推荐
相关产品推荐

