检查两个对象在 Pytest 中是否具有相同的内容
Check if two objects have equal content in Pytest
我正在学习如何使用 Pytest(以及一般的单元测试),我想编写一个测试来检查相同 class 的两个对象是否具有相同的属性。
示例:
class Something(object):
def __init__(self, a, b):
self.a, self.b = a, b
def __repr__(self):
return 'Something(a={}, b={})'.format(self.a, self.b)
def test_equality():
obj1 = Something(1, 2)
obj2 = Something(1, 2)
assert obj1.a == obj2.a
assert obj1 == obj2
此测试因第三个断言出现 AssertionError 而失败:
def test_equality():
obj1 = Something(1, 2)
obj2 = Something(1, 2)
assert obj1.a == obj2.a
assert obj1.b == obj2.b
> assert obj1 == obj2
E assert Something(a=1, b=2) == Something(a=1, b=2)
tests/test_model.py:13: AssertionError
在 Python 或 Pytest 中可以只使用 assert obj1 == obj2
吗?我应该为每个 class 实现 "rich comparison" 方法吗?我想用那种方式测试还是有一些更简单的方法?
覆盖 Something 的 __eq__ 函数。
def __eq__(self, other)
if isinstance(self, other.__class__):
return self.a == other.a and self.b == other.b
return False
还有。
assert obj1 == obj2
实际上是一个两部分的语句。第一个是表达式 obj1 == obj2,它调用 obj1.__eq__(obj2) 和 returns 一个布尔值,第二个断言布尔值为真。
我正在学习如何使用 Pytest(以及一般的单元测试),我想编写一个测试来检查相同 class 的两个对象是否具有相同的属性。
示例:
class Something(object):
def __init__(self, a, b):
self.a, self.b = a, b
def __repr__(self):
return 'Something(a={}, b={})'.format(self.a, self.b)
def test_equality():
obj1 = Something(1, 2)
obj2 = Something(1, 2)
assert obj1.a == obj2.a
assert obj1 == obj2
此测试因第三个断言出现 AssertionError 而失败:
def test_equality():
obj1 = Something(1, 2)
obj2 = Something(1, 2)
assert obj1.a == obj2.a
assert obj1.b == obj2.b
> assert obj1 == obj2
E assert Something(a=1, b=2) == Something(a=1, b=2)
tests/test_model.py:13: AssertionError
在 Python 或 Pytest 中可以只使用 assert obj1 == obj2
吗?我应该为每个 class 实现 "rich comparison" 方法吗?我想用那种方式测试还是有一些更简单的方法?
覆盖 Something 的 __eq__ 函数。
def __eq__(self, other)
if isinstance(self, other.__class__):
return self.a == other.a and self.b == other.b
return False
还有。
assert obj1 == obj2
实际上是一个两部分的语句。第一个是表达式 obj1 == obj2,它调用 obj1.__eq__(obj2) 和 returns 一个布尔值,第二个断言布尔值为真。