我构建了一个几何变换的类。当我运行单元测试时,由于方法内部的操作产生了舍入误差,导致测试失败。
在我的测试中,我比较了其中一个方法的结果,该方法应返回点(2,2,0),但由于舍入误差,它返回了(1.9999999999999996, 1.9999999999999996, 0.0)。
但我需要以某种方式自动化它,因为后来我需要测试一系列元组作为向量场的样本点坐标。作为重复的解决方案建议的解决方案只是半成品,因为如果列表中有100个元组,则编写300个以上的比较会有些繁琐。
在我的测试中,我比较了其中一个方法的结果,该方法应返回点(2,2,0),但由于舍入误差,它返回了(1.9999999999999996, 1.9999999999999996, 0.0)。
Finding files... done.
Importing test modules ... done.
** DEBUG_45 from the method point=(1.9999999999999996, 1.9999999999999996, 0.0)
======================================================================
FAIL: testPointCoord (vectOper.test.TestNearestPoint.TestNearestPoint)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\src\vectOper\test\TestNearestPoint.py", line 14, in testPointCoord
self.assertEqual(pointCoord, (2,2,0), "nearest point failed")
AssertionError: nearest point failed
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
从计算的角度来看是可以接受的,但我不希望我的代码在简单的单元测试中失败。
import unittest
from vectOper.nearestPoint import NearestPoint
class TestNearestPoint(unittest.TestCase):
def testPointCoord(self):
nearestPoint = NearestPoint()
pointCoord = nearestPoint.pointCoord(samplePoint=(2,2,2),lineStart=(0,0,0), lineVect=(1,1,0))
self.assertEqual(pointCoord, (2,2,0), "nearest point failed")
如何正确解决这样的问题?显然我不能将输出数字四舍五入或转换为整数,因为通常情况下不是这种情况。 是否有一种编写单元测试来忽略舍入误差的方法? 还有其他解决问题的方法吗?
编辑:
正如another的答案所建议的那样,可以使用self.assertAlmostEqual
来解决这个问题,但问题在于我需要测试一个元组的输入。在所有建议之后,我试图做到:
def testPointCoord(self):
nearestPoint = NearestPoint()
pointCoord = nearestPoint.pointCoord(samplePoint=(2,2,2),lineStart=(0,0,0), lineVect=(1,1,0))
self.assertAlmostEqual(pointCoord[0], 2, places=7, msg="nearest point x-coodr failed")
self.assertAlmostEqual(pointCoord[1], 2, places=7, msg="nearest point y-coodr failed")
self.assertAlmostEqual(pointCoord[2], 0, places=7, msg="nearest point z-coodr failed")
但我需要以某种方式自动化它,因为后来我需要测试一系列元组作为向量场的样本点坐标。作为重复的解决方案建议的解决方案只是半成品,因为如果列表中有100个元组,则编写300个以上的比较会有些繁琐。
assertAlmostEqual
没有比较元组的魔法,因此您需要单独测试每个三维坐标) - WoobleassertRaises
的任何用途。 - WoobleassertAlmostEqual
来比较元组中的元素。 - tomasz74