2016-12-01 72 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

相關問題