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

pytest断言返回false无详细失败信息,如何获取不匹配的数据?

解决方法

你现在的写法用all()批量判断,会把具体不匹配的项包裹在迭代逻辑里,pytest没法直接解析输出具体差异,可以用以下两种方案调整:

方案1:先收集不匹配项再断言

提前遍历对比两个数据集,把所有不匹配的行号、源数据、目标数据都收集起来,再判断是否有不匹配项,断言时直接把收集到的差异塞到错误提示里:

def test_content_database():
    records_src = [(1,"James","smith",123),(2,"Granpa","smith",124),(3,"Linda","smith",123)]
    records_trg = [(1,"James","smith",124),(2,"Granpa","ron",124),(3,"Linda","smith",123)]
    # 收集不匹配项
    diffs = []
    for idx, (a, b) in enumerate(zip(records_src, records_trg)):
        if a != b:
            diffs.append(f"行号{idx+1}:源数据{a} vs 目标数据{b}")
    # 兼容两个数据集长度不一致的场景
    if len(records_src) != len(records_trg):
        diffs.append(f"数据集长度不一致:源数据共{len(records_src)}行,目标数据共{len(records_trg)}行")
    # 断言时输出所有差异
    assert len(diffs) == 0, "数据不匹配,差异如下:\n" + "\n".join(diffs)

断言失败时控制台会直接输出所有不匹配的行和对应数据。

方案2:直接断言两个列表相等(更简便)

pytest自带断言重写能力,你不需要自己写all()判断逻辑,直接断言两个列表相等即可,pytest会自动格式化输出差异内容:

def test_content_database():
    records_src = [(1,"James","smith",123),(2,"Granpa","smith",124),(3,"Linda","smith",123)]
    records_trg = [(1,"James","smith",124),(2,"Granpa","ron",124),(3,"Linda","smith",123)]
    assert records_src == records_trg, "数据不匹配"

运行后pytest会自动输出类似以下的差异提示:

E       AssertionError: 数据不匹配
E       assert [(1, 'James', 'smith', 123), (2, 'Granpa', 'smith', 124), (3, 'Linda', 'smith', 123)] == [(1, 'James', 'smith', 124), (2, 'Granpa', 'ron', 124), (3, 'Linda', 'smith', 123)]
E         At index 0 diff: (1, 'James', 'smith', 123) != (1, 'James', 'smith', 124)
E         At index 1 diff: (2, 'Granpa', 'smith', 124) != (2, 'Granpa', 'ron', 124)
E         Use -v to get more diff

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:36:10