これがあなたのニーズに合うかどうかはわかりませんが、2つの操作をテストしてみませんか。つまり、テスト if :object1 == object2
そしてobject2 == object1
、オブジェクトの1つがメソッドを上書きしていない限り、通常は同じ値になるはず__eq__
なので、実行しますこの新しい__eq__
メソッドは true であるメソッドを返します。例は words よりも優れています:
def _assert_just_now(first, second):
"""A Dump function to simulate if two dates are almost equal.
N.B: In this Dump function i will just test if the two datetime object have the
same hour
"""
from datetime import datetime
assert isinstance(first, datetime) and isinstance(second, datetime), \
"This function only accept datetime objects"
return first.hour == second.hour
class Expectation(object):
def __init__(self, assertion, first):
self.assertion = assertion
self.first = first
def __eq__(self, other):
return self.assertion(self.first, other)
def assert_equal(first, second):
"""Usage :
>>> from datetime import datetime
>>> t1 = datetime(year=2007, hour=1, month=3, day=12)
>>> t2 = datetime(year=2011, hour=1, month=5, day=12)
Without using Expectation it's False.
>>> assert_equal(t1, t2)
False
Use the Expectation object.
>>> assert_equal(t1, Expectation(_assert_just_now, t2))
True
Can use Expectation in the first argument too.
>>> assert_equal(Expectation(_assert_just_now, t2), t1)
True
Work also in Container object.
>>> assert_equal({'a': 1, 'b': Expectation(_assert_just_now, t2)},
... {'a': 1, 'b': t1})
True
We change a little bit the values to make the assert equal fail.
>>> t3 = datetime(year=2011, hour=2, month=5, day=12)
>>> assert_equal(t1, t3)
False
This just to make sure that the _assert_just_now doesn't accept object
other than datetime:
>>> assert_equal(t1, Expectation(_assert_just_now, "str"))
Traceback (most recent call last):
...
AssertionError: This function only accept datetime objects
"""
return first == second or second == first
if __name__ == '__main__':
import doctest
doctest.testmod()
これが役立つことを願っています。