在 Pytest 断言中覆盖标准断言消息传递
Override Standard Assert Messaging in Pytest Assert
我正在使用 Pytest 测试一些 SQL 我的团队随着时间的推移以编程方式运行的查询。
我的 SQL 查询是 JSON 的列表 - 一个 JSON 对应一行数据。
我有一个函数可以区分 JSON key:value 对,这样我们就可以准确指出给定行的哪些值不同。理想情况下,我会输出这些差异的列表 而不是 assert 语句的标准输出 ,这最终看起来很笨重并且对最终用户不是很有用。
您可以使用 Python 内置功能来显示自定义异常消息:
assert response.status_code == 200, "My custom message: actual status code {}".format(response.status_code)
Pytest 为我们提供了钩子 pytest_assertrepr_compare
以添加关于断言失败原因的自定义解释。
您可以创建一个 class 来包装 JSON 字符串并实现重载等于运算符的比较器算法。
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 测试一些 SQL 我的团队随着时间的推移以编程方式运行的查询。
我的 SQL 查询是 JSON 的列表 - 一个 JSON 对应一行数据。
我有一个函数可以区分 JSON key:value 对,这样我们就可以准确指出给定行的哪些值不同。理想情况下,我会输出这些差异的列表 而不是 assert 语句的标准输出 ,这最终看起来很笨重并且对最终用户不是很有用。
您可以使用 Python 内置功能来显示自定义异常消息:
assert response.status_code == 200, "My custom message: actual status code {}".format(response.status_code)
Pytest 为我们提供了钩子 pytest_assertrepr_compare
以添加关于断言失败原因的自定义解释。
您可以创建一个 class 来包装 JSON 字符串并实现重载等于运算符的比较器算法。
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