[英]Python unittest successfully asserts None is False
为什么assertFalse
在None
成功?
import unittest
class TestNoneIsFalse(unittest.TestCase):
def test_none_is_false(self):
self.assertFalse(None)
结果:
> python -m unittest temp
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
似乎这种行为会引发错误,而函数并不总是返回值。 例如:
def is_lower_than_5(x):
if x < 5:
return True
elif x > 5:
return False
....
def test_5_is_not_lower_than_5(self):
self.assertFalse(is_lower_than_5(5))
即使它失败,上述测试也会通过。 它缺少应该捕获的代码中的错误。
我们应该如何断言值在字面上是False
而不仅仅是布尔上下文中的false? 例如
self.assertEquals(False, None) # assert fails. good!
None
是假的,还有0
, ""
, []
,......
assertFalse
不会通过标识检查给定值是否为False
。 此行为与if
语句一致:
if not None:
print('falsy value!')
类似地, assertTrue
不检查值是否为True
,并且像1
, "abc"
, [1, 2, 3]
这样的值通过测试。 有关详细信息,请参阅真值测试 。
此行为也明确记录 :
assertTrue (expr,msg = None)\n assertFalse (expr,msg = None)测试expr是否为真(或假)。
请注意,这相当于
bool(expr) is True
而不是expr is True
如果您确实想要确保值为True
或False
,请使用assertIs
。
您的案例实际上在文档中指出:
请注意,这相当于bool(expr)为True,而expr为True(对后者使用assertIs(expr,True))。
资料来源: https : //docs.python.org/2/library/unittest.html#unittest.TestCase.assertFalse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.