python断言assertequal_python-尝试断言AlmostEqual / assertEqual时,不受支持的操作数类型...
我試圖測試兩個對象是否相等.該對象的類型是Point,它是由ROS(機器人操作系統)定義的類.我有以下測試:
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-unittest,python
來源: https://codeday.me/bug/20191112/2023827.html
總結
以上是生活随笔為你收集整理的python断言assertequal_python-尝试断言AlmostEqual / assertEqual时,不受支持的操作数类型...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 滑动窗口算法_有点难度,几道和「滑动窗口
- 下一篇: python3类的继承详解_python