Assert an integer is within range
我正在用Python编写一些UnitTests,这些测试是在测试是否接收到整数。然而,有时这个整数可以被1或2去掉,我真的不在乎。本质上,我希望能够断言接收到的整数在某个范围内,比如:
1 | self.assertBetween(998, 1000, my_integer) |
有没有一种公认的方法可以做到这一点?或者我必须这样做:
1 2 | self.assertTrue(998 <= my_integer) self.assertTrue(my_integer <= 1000) |
编辑迄今为止的答案表明:
1 | self.assertTrue(998 <= my_integer <= 1000) |
在我的示例中,使用2个断言是否有任何好处?
您可以使用"链接比较":
1 | self.assertTrue(998 <= my_integer <= 1000) |
python有一个内置函数,您可以使用它:
1 2 3 4 | self.assertAlmostEqual(myinteger, 999, delta=1) # is equivalent to self.assertTrue(998 <= myinteger <= 1000) # ... but gives better error messages. |
可选参数delta指定与要测试的值的允许距离。
我不认为用
1 | AssertionError: False is not true |
这根本没有帮助,你基本上回到了"原始"的
我建议:
创建自己的自定义断言您可以在其中打印更有意义的消息。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import unittest class BetweenAssertMixin(object): def assertBetween(self, x, lo, hi): if not (lo <= x <= hi): raise AssertionError('%r not between %r and %r' % (x, lo, hi)) class Test1(unittest.TestCase, BetweenAssertMixin): def test_between(self): self.assertBetween(999, 998, 1000) def test_too_low(self): self.assertBetween(997, 998, 1000) def test_too_high(self): self.assertBetween(1001, 998, 1000) if __name__ == '__main__': unittest.main() |
然后您将得到以下输出(缩短):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ====================================================================== FAIL: test_too_high (__main__.Test1) ---------------------------------------------------------------------- Traceback (most recent call last): File"example.py", line 19, in test_too_high self.assertBetween(1001, 998, 1000) File"example.py", line 8, in assertBetween raise AssertionError('%r is not between %r and %r' % (x, lo, hi)) AssertionError: 1001 is not between 998 and 1000 ====================================================================== FAIL: test_too_low (__main__.Test1) ---------------------------------------------------------------------- Traceback (most recent call last): File"example.py", line 16, in test_too_low self.assertBetween(997, 998, 1000) File"example.py", line 8, in assertBetween raise AssertionError('%r is not between %r and %r' % (x, lo, hi)) AssertionError: 997 is not between 998 and 1000 ---------------------------------------------------------------------- |
或使用
如果不需要自定义断言(这会添加另一个回溯记录和多行代码):
1 2 3 4 5 6 | ... def test_no_custom_assert(self): my_integer = 100 self.assertGreaterEqual(my_integer, 998) self.assertLessEqual(my_integer, 1000) ... |
它比
1 2 3 4 5 6 7 | ====================================================================== FAIL: test_no_custom_assert (__main__.Test1) ---------------------------------------------------------------------- Traceback (most recent call last): File"example.py", line 23, in test_no_custom_assert self.assertGreaterEqual(my_integer, 998) AssertionError: 100 not greater than or equal to 998 |
1 | self.assertTrue(998 <= my_integer <= 1000) |