基于Python的JSON与Excel处理工具

187 阅读2分钟

1、背景描述

在我们的实际项目开发中,项目大部分接口测试是采用了自动化契约测试结合手动探索测试的方案。测试流程由测试人员在测试系统中编写用例描述,再将一个接口设计好的全部用例交接给开发人员,由开发人员编写契约测试。遇到一个需求:为了更好地管理用例和规范统计,需要对当前项目中所有的契约测试son文件中的用例和测试系统中的每个用例编号同步。目前系统接口有1950个左右,契约测试中每个用例只有对应的用例描述,没有编号。由于历史原因,还存在的问题是契约测试文件中的描述可能是测试系统中用例描述存在不一致的情况。

2、解决思路

  1. 用程序的思维解决问题,提供处理效率,而不是传统的手工排查方式。
  2. 分析需求,契约测试文件都是json文件,且每个用例格式都是由description,request,response这三个key组成,测试系统中的每个用例可以通过excel的方式导出用例描述和用例编号,只需要将json文件中的用例描述和excel中的用例描述进行匹配,把excel的编号写入json相关的用例中去。
  3. 确定用python的方式去解决问题

3、操作步骤

  1. 分析好需求后,只需要利用python中对excel和json的读写,再结合处理逻辑即可解决。
  2. 开发工具:Pycharm
  3. 安装插件位置: Settings--->Project--->Python Interperter
  4. 代码如下:
import xlrd
import json
from pathlib import Path
import difflib

# json文件路径
json_root_dir = 'xxxxxxxx'  
# excel文件路径
xls_root_dir = 'xxxxxxxx'

# 读取excel文件
def read_excel():
    description_result = []
    data = xlrd.open_workbook(xls_root_dir)
    table = data.sheets()[0]  # 打开第一张表
    nrows = table.nrows  # 获取表的行数
    for i in range(1, nrows):  # 循环逐行打印
        description_result.append(table.row_values(i)[2:4])
    return description_result

# 解析json用例文件
def parse_dir(root_dir):
    description_result = read_excel()
    path = Path(root_dir)
    all_json_file = list(path.glob('*.json'))
    for json_file in all_json_file:
        # 获取所在目录的名称
        with json_file.open() as f:
            json_result = json.load(f)
            for index in range(len(json_result)):
                context = json_result[index]["description"]
                is_match = match_context(description_result, context)
                if is_match:
                    json_result[index]["description"] = is_match
            with open(json_file, "w") as f1:
                json.dump(json_result, f1, ensure_ascii=False, indent=4)
    print("修改json用例完成...")

# 根据用例描述相似度替换-------0.96这个数值可以根据具体需求调整
def match_context(lists, context):
    for temp in lists:
        if get_equal_rate(temp[1], context) > 0.96:
            context = "[" + temp[0] + "]" + temp[1]
    return context


# 字符串的相似度算法
def get_equal_rate(str1, str2):
    return difflib.SequenceMatcher(None, str1, str2).quick_ratio()

if __name__ == '__main__':
    parse_dir(json_root_dir)