Python pytest对象相等性,并覆盖_eq
我正在为一个项目使用peewee,在测试时遇到了一个问题。我想检查一个函数是否被一个特定的参数调用,这个参数是peewee表达式。这里的问题是peewee.Expression重写了_eq____运算符: 因此,现在,放在Python pytest对象相等性,并覆盖_eq,python,pytest,Python,Pytest,我正在为一个项目使用peewee,在测试时遇到了一个问题。我想检查一个函数是否被一个特定的参数调用,这个参数是peewee表达式。这里的问题是peewee.Expression重写了_eq____运算符: 因此,现在,放在=表达式右侧的任何内容都将返回一个新表达式,并通过pytest计算为True pytest库中是否有某种东西可以通过属性而不是使用=操作符来测试对象的相等性?对于那些感兴趣的人,我找到了一种解决方案,可以轻松地执行该操作 def _extract_call_dict(name,
=
表达式右侧的任何内容都将返回一个新表达式,并通过pytest计算为True
pytest库中是否有某种东西可以通过属性而不是使用
=
操作符来测试对象的相等性?对于那些感兴趣的人,我找到了一种解决方案,可以轻松地执行该操作
def _extract_call_dict(name, args, kwargs=None):
"""Checks if the current element has an overriden __eq__ method"""
if kwargs is None:
# mock._Call is a superclass of Tuple and can have
# 2 or 3 elements. So, I unpack them and ajust my args accordingly
args, kwargs = name, args
# This check can be improved, my use case is pretty simple,
# so I only check types
has_eq_overriden = lambda obj: (isinstance(obj, peewee.Model) or
isinstance(obj, peewee.Expression))
# Replace the object by its dict representation if boolean is True
get_dict = lambda obj: obj.__dict__ if has_eq_overriden(obj) else obj
# apply this treatment for every elements from _Call
args = [get_dict(arg) for arg in args]
kwargs = {key: get_dict(value) for key, value in kwargs.items()}
# return a new instance
return mock.call(args, kwargs)
class _Call(mock._Call):
"""Override the _Call class from mock"""
def __eq__(self, other):
"""This will be use every time you try to compare
mock.call statements
"""
self_replacement = _extract_call_dict(*self)
if isinstance(other, mock._Call):
other = _extract_call_dict(*other)
return super(_Call, self_replacement).__eq__(other)
# Override mock.call to be compliant with peewee __eq__ override
unittest.mock._Call = test.utils._Call
您有许多选项-模拟
表达式
,比较\uuuuuu dict\uuuu
s,显式比较类型和属性值,反转测试,使用您自己的比较器对象适当实现\uuuu eq\uuuu
,…您还可以检查expression对象的lhs和rhs。按照@jonrsharpe的建议显式比较类型和属性将是一种方法,可能会实现一个夹具来为您完成这项工作。thx@jonrsharpe在上进行比较是一个很好的解决方案