首页 > 解决方案 > 抛出显示差异的异常

问题描述

我正在创建一个在生成输出文件的一些测试之后执行的函数。我想检查进程在内存中的输出与之前的测试运行是否存在差异,如果有任何差异,则显示测试日志中的差异并且测试失败。

with open(os.path.join(path, f"{test_name}.json"), "r") as local_file:
     local_data = json.loads(local_file.read())
     differences = jsondiff.diff(local_data, payload["args"][1])
     if differences:
        print(differences)
        raise ValueError("There are some differences with {test_name}.json file")

这在测试日志中向我显示了以下输出。 在此处输入图像描述

但我不想展示这一点,我想展示差异和 test_name。

我是否需要在此方法中添加断言或创建客户异常?

标签: pythonjsonpytest

解决方案


你希望你的字符串是一个f 字符串

with open(os.path.join(path, f"{test_name}.json"), "r") as local_file:
     local_data = json.loads(local_file.read())
     differences = jsondiff.diff(local_data, payload["args"][1])
     if differences:
        print(differences)
        raise ValueError(f"There are some differences with {test_name}.json file")
#This                    ^
#Is what you were missing

推荐阅读