簡體   English   中英

帶有__eq__的pytest對象相等

[英]pytest object equality with __eq__ overriden

我正在將peewee用於一個項目,並且在測試時遇到問題。 我想檢查是否已使用特定參數(即peewee表達式)調用了函數。 這里的問題是peewee.Expression會覆蓋__eq__運算符: https : //github.com/coleifer/peewee/blob/master/peewee.py#L379

因此,現在放在==表達式右側的任何內容都將返回一個新表達式,並由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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM