2016-12-01 71 views
2

我想测试两个对象是否相等。该对象的类型是由ROS(机器人操作系统)定义的类Point。我有以下测试:尝试assertAlmostEqual/assertEqual时不支持的操作数类型(s)

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' 
+0

什么是异常的*完整回溯* –

+0

@MartijnPieters,我刚刚编辑我的问题提供完整的追溯。 – lmiguelvargasf

回答

3

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__,你可以使用猴子打补丁提供它在你的测试用例。

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 
+0

不错!在绝对值函数的'return'上输错。 –

+0

@kennytm,如果这个类是由框架提供的呢?我该如何做到这一点,我是否应该使用继承并在其上实现此方法,或者有什么方法可以对类进行扩展? – lmiguelvargasf

+0

@ Ev.Kounis谢谢,修正:) – kennytm

相关问题