Python自带difflib模块

官方文档:https://docs.python.org/3/library/difflib.html

difflib模块的作用是比对文本之间的差异,且支持输出可读性比较强的HTML文档,与Linux下的vimdiff命令相似。

vimdiff效果如下:

在接口测试时,常常需要对不同版本的同一个接口的response进行比对,来验证新版本的功能可靠性。接口数量多,加之vimdiff命令输出的结果读起来不是很友好,这时python自带的difflib模块就可以发挥作用了。

difflib.Differ

import difflib
text1 = '''  yi hang
            er hang
     '''.splitlines(keepends=True)

text2 = '''  yi hang
            er han
            san hang
     '''.splitlines(keepends=True)

d = difflib.Differ()             # 创建Differ 对象
result = list(d.compare(text1, text2))
result = "".join(result)
print(result)

结果:

注释:

difflib.HtmlDiff 

import difflib
import sys
import argparse

# 读取要比较的文件
def read_file(file_name):
    try:
        file_desc = open(file_name, 'r')
        # 读取后按行分割
        text = file_desc.read().splitlines()
        file_desc.close()
        return text
    except IOError as error:
        print('Read input file Error: {0}'.format(error))
        sys.exit()

# 比较两个文件并把结果生成一个html文件
def compare_file(file_1, file_2):
    if file_1 == "" or file_2 == "":
        print('文件路径不能为空:第一个文件的路径:{0}, 第二个文件的路径:{1} .'.format(file_1, file_2))
        sys.exit()
    else:
        print("正在比较文件{0} 和 {1}".format(file_1, file_2))
    text1_lines = read_file(file_1)
    text2_lines = read_file(file_2)
    diff = difflib.HtmlDiff()           # 创建HtmlDiff 对象
    result = diff.make_file(text1_lines, text2_lines)   # 通过make_file 方法输出 html 格式的对比结果
    # 将结果写入到result_compare.html文件中
    try:
        with open('result_compare.html', 'w') as result_file:
            result_file.write(result)
            print("比较完成")
    except IOError as error:
        print('写入html文件错误:{0}'.format(error))

if __name__ == "__main__":
    # To define two arguments should be passed in, and usage: -f1 f_name1 -f2 f_name2
    my_parser = argparse.ArgumentParser(description="传入两个文件参数")
    my_parser.add_argument('-f1', action='store', dest='f_name1', required=True)
    my_parser.add_argument('-f2', action='store', dest='f_name2', required=True)
    # retrieve all input arguments
    given_args = my_parser.parse_args()
    file1 = given_args.f_name1
    file2 = given_args.f_name2
    compare_file(file1, file2)

result_compare.html效果:

注意:当接口response返回的行数很多,difflib可能会发生比对错行,导致比对结果不准确,不妨去试一试xmldiff和json-diff

原文地址:https://www.cnblogs.com/ailiailan/p/13921490.html