Python Unittest如何检查函数返回的浮点数是否在0-100范围内?
Python Unittest 检查浮点数是否在0-100区间内
下面是直接可用的Unittest用例示例,覆盖了边界值、正常区间值、区间外值三类核心测试场景:
假设你要测试的目标函数为get_target_float(),它返回一个浮点数,替换成你实际要测试的函数即可:
import unittest def get_target_float(): # 示例函数,需替换为你的目标函数 return 62.3 class TestFloatInRange(unittest.TestCase): def test_normal_in_range(self): # 测试处于0-100之间的正常数值 result = get_target_float() self.assertGreaterEqual(result, 0.0) self.assertLessEqual(result, 100.0) def test_lower_bound(self): # 测试刚好等于下边界0.0的情况 result = 0.0 self.assertGreaterEqual(result, 0.0) self.assertLessEqual(result, 100.0) def test_upper_bound(self): # 测试刚好等于上边界100.0的情况 result = 100.0 self.assertGreaterEqual(result, 0.0) self.assertLessEqual(result, 100.0) def test_below_range(self): # 测试低于0的数值,预期触发断言失败 result = -0.001 with self.assertRaises(AssertionError): self.assertGreaterEqual(result, 0.0) self.assertLessEqual(result, 100.0) def test_above_range(self): # 测试高于100的数值,预期触发断言失败 result = 100.001 with self.assertRaises(AssertionError): self.assertGreaterEqual(result, 0.0) self.assertLessEqual(result, 100.0) if __name__ == '__main__': unittest.main()
关键细节说明:
- 使用
assertGreaterEqual和assertLessEqual比self.assertTrue(0 <= result <= 100)的可读性更强,断言失败时的错误提示也更明确,能直接看出是超出上界还是下界。 - 必须覆盖边界值:0.0和100.0是区间临界点,很多函数容易在边界逻辑上出错。
- 如果目标函数返回的浮点数存在精度误差(比如计算后得到
100.0000000001或-0.0000000001),可以添加微小容差避免误判:self.assertGreaterEqual(result, -1e-9) self.assertLessEqual(result, 100.0 + 1e-9)
内容的提问来源于stack exchange,提问作者naseweis
相关产品推荐
相关产品推荐

