我正在编写一些代码,它适用于非常大的和非常小的浮点数(例如,1e-150可能是一个有效的答案)。为了对此进行单元测试,我想将浮点数与许多重要数字进行比较,而不是小数位,因此我有以下内容。
import unittest as ut
from numpy.testing import assert_approx_equal
class newTestCase(ut.TestCase):
"""Extends the basic unittest TestCase."""
def assertSFAlmostEqual(self, a, b, places=7):
"""Uses numpy to test if two floats are the same but to a defined
number of significant figures rather than decimal places.
Args:
a: float to be compared
b: float to be compared
places: number of significant figures to match. unittest default
for assertAlmostEqual is 7, so 7 is the default here
"""
if isinstance(a, float) != True or isinstance(b, float) != True:
raise TypeError
raised = False
try:
assert_approx_equal(a, b, significant=places)
except:
raised = True
self.assertFalse(raised, "FLoats %g and %g are not equal to %i "
"significant figures" % (a, b, places))
这似乎很好,但我计划在很多地方使用它,所以我想确定它确实正确工作。我的问题是,我怎样才能最明智地做到这一点?是否有适当的机制来测试单元测试?
我在这里找到了答案,
How to unittest unittest TestCases
但我不明白这是怎么回事。
非常感谢提前!
发布于 2013-09-09 09:35:32
unittest.TestCase
的子类和任何其他类一样,因此您可以编写一个unittest.TestCase
来检查它的方法是否正常工作。
特别是,您应该构建一组数字对,这些数字应该通过测试并失败,然后使用这些输入调用assertSFAlmostEqual
方法,查看测试是否通过。
您所链接的答案可以做到这一点,尽管它可能是一个比所需的更复杂的解决方案。例如,我本可以简单地编写如下内容:
import unittest
class MyBaseTestCase(unittest.TestCase):
def assertSpec(self, thing):
assert thing == 123
class TestMyTest(MyBaseTestCase):
def test_failures(self):
self.assertRaises(AssertionError, self.assertSpec, 121)
def test_successes(self):
self.assertSpec(123)
if __name__ == "__main__":
unittest.main()
您只需子类测试用例,测试只需调用您编写的带有特定参数的assert*
方法,您知道这些参数应该通过/不通过测试。
关于assert*
方法当前实现的一些注意事项:
if isinstance(a, float) != True or isinstance(b, float) != True:
避免与True
或False
进行比较。在您的情况下,您可以简单地写:
if not isinstance(a, float) or not isinstance(b, float):
# or:
if not (isinstance(a, float) and isinstance(b, float))
读起来也更清楚。
raised = False
try:
assert_approx_equal(a, b, significant=places)
except:
raised = True
从不使用普通except:
捕获异常。在这种情况下,您确实希望只捕获由AssertionError
引发的assert_approx_equal
,因此您应该使用:
raised = False
try:
assert_approx_equal(a, b, significant=places)
except AssertionError:
raised = True
其次,您可以避免使用raised
标志。try-except
语句允许只在未引发异常时执行else
子句:
try:
assert_approx_equal(a, b, significant=places)
except AssertionError:
# here put the code to be executed when the assertion fails.
else:
# here put the code to be executed when *no* exception was raised.
发布于 2014-01-10 18:24:26
一种方法是TDD (测试驱动开发):
这里的关键是先写一个失败的测试。
https://stackoverflow.com/questions/18695042
复制相似问题