在Pytest声明中覆盖标准声明消息 [英] Override Standard Assert Messaging in Pytest Assert

查看:92
本文介绍了在Pytest声明中覆盖标准声明消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Pytest来测试我的团队随时间以编程方式运行的一些SQL查询.

I'm using Pytest to test some SQL queries my team runs programmatically over time.

我的SQL查询是JSON列表-一个JSON对应于一行数据.

My SQL queries are lists of JSONs - one JSON corresponds to one row of data.

我有一个函数可以区分JSON key:value对,以便我们可以精确地指出给定行中哪些值不同.理想情况下,我将输出assert语句的标准输出的这些差异 的列表,最终对于最终用户而言看起来很笨拙且用处不大.

I've got a function that diffs the JSON key:value pairs so that we can point to exactly which values are different for a given row. Ideally, I'd output a list of these diffs instead of the standard output of an assert statement, which ends up looking clunky and not-very-useful for the end user.

推荐答案

Pytest给了我们

Pytest give us the hook pytest_assertrepr_compare to add a custom explanation about why an assertion failed.

您可以创建一个用于包装JSON字符串的类,并实现重载equal运算符的比较器算法.

You can create a class to wrap the JSON string and implement your comparator algorithm overloading the equal operator.

class JSONComparator:
    def __init__(self, lst):
        self.value = value

    def __eq__(self, other):
        # Here your algorithm to compare two JSON strings
        ...

        # If they are different, save that information
        # We will need it later
        self.diff = "..."

        return True

# Put the hook in conftest.py or import it in order to make pytest aware of the hook.
def pytest_assertrepr_compare(config, op, left, right):

    if isinstance(left, JSONComparator) and op == "==":
        # Return the diff inside an array.
        return [left.diff]

# Create a reference as an alias if you want
compare = JSONComparator

用法

def test_somethig():
    original = '{"cartoon": "bugs"}'
    expected = '{"cartoon": "bugs"}'

    assert compare(original) == expected

这篇关于在Pytest声明中覆盖标准声明消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆