我正在尝试测试两个对象是否相等。这个对象的类型是Point,是ROS(Robot Operating System)定义的一个类。我有以下测试:
def test_when_getting_position_after_2s_then_position_at_2s_is_returned(self):
self.expected_position.x = -self.radius
self.expected_position.y = 0
self.assertAlmostEqual(
self.expected_position,
self.trajectory.get_position_at(2))
我正在使用 unittest
,当我尝试断言它们是否几乎相等时,我收到一条错误消息:
TypeError: unsupported operand type(s) for -: 'Point' and 'Point'
我在使用 assertEqual
时遇到同样的错误,我知道我可以这样做:
self.assertAlmostEqual(self.expected_position.x, self.trajectory.get_position_at(1).x)
self.assertAlmostEqual(self.expected_position.y, self.trajectory.get_position_at(1).y)
但是,我希望能够断言位置而不是特定字段。我怎样才能做到这一点?
编辑:异常的完整回溯是:
Error
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/case.py", line 329, in run
testMethod()
File "/home/m/turtlebot_ws/src/trajectory_tracking/src/test/trajectory/test_astroid_trajectory.py", line 26, in test_when_getting_position_after_1s_then_position_at_1s_is_returned
self.assertAlmostEqual(self.expected_position, self.trajectory.get_position_at(1))
File "/usr/lib/python2.7/unittest/case.py", line 554, in assertAlmostEqual
if round(abs(second-first), places) == 0:
TypeError: unsupported operand type(s) for -: 'Point' and 'Point'
最佳答案
assertAlmostEqual(a, b)
要求 abs(a - b)
有效,但您没有为 Point 类型定义减法运算符,因此出现错误.
class Point(object):
...
def __sub__(self, other): # <-- define the subtraction operator so `a - b` is valid
return Vector(self.x - other.x, self.y - other.y)
class Vector(object):
...
def __abs__(self): # <-- define the absolute function so `abs(v)` is valid
return (self.x*self.x + self.y*self.y)**0.5
如果您不能在类定义中提供 __sub__
,您可以使用 monkey-patching 在您的测试用例中提供它。
def sub_point(self, other):
return complex(self.x - other.x, self.y - other.y)
# ^ for simplicity we abuse a complex number as a 2D vector.
Point.__sub__ = sub_point
关于python - 尝试 assertAlmostEqual/assertEqual 时不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40916547/