Python unittest 成功断言 None 为 False [英] Python unittest successfully asserts None is False
问题描述
为什么 assertFalse
在 None
上成功?
导入单元测试类 TestNoneIsFalse(unittest.TestCase):def test_none_is_false(self):self.assertFalse(无)
结果:
<代码>>python -m unittest temp.----------------------------------------------------------------------在 0.001 秒内运行 1 次测试好的
似乎这种行为会导致函数不总是返回值的错误.例如:
def is_lower_than_5(x):如果 x <5:返回真elif x >5:返回错误....def test_5_is_not_lower_than_5(self):self.assertFalse(is_lower_than_5(5))
即使上面的测试应该失败,它也会通过.它在代码中遗漏了一个应该被捕获的错误.
我们应该如何断言该值是字面上的 False
而不仅仅是布尔上下文中的 false?例如
self.assertEquals(False, None) # 断言失败.好的!
None
是假的,还有 0
, ""
,[]
, ...
assertFalse
不会通过身份检查给定值是否为 False
.此行为与 if
语句一致:
如果不是 None:打印('假值!')
类似地,assertTrue
不会检查一个值是否为 True
,而是像 1
、"abc"<这样的值/code>,
[1, 2, 3]
测试通过.有关详细信息,请参阅真值测试.
此行为也明确记录:
<块引用>assertTrue(expr, msg=None)assertFalse(expr, msg=None)
测试 expr 为真(或假).
注意这等价于 bool(expr) is True
而不是 expr is True
如果您真的想确定某个值是 True
还是 False
,请使用 assertIs
.
Why does assertFalse
succeed on None
?
import unittest
class TestNoneIsFalse(unittest.TestCase):
def test_none_is_false(self):
self.assertFalse(None)
Results:
> python -m unittest temp
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
It seems as if this behaviour invites errors where a function does not always return a value. For example:
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))
The above test would pass even though it should fail. It is missing an error in the code that should be caught.
How should we assert that the value is literally False
and not merely false in a boolean context? e.g.
self.assertEquals(False, None) # assert fails. good!
None
is falsy, as well as 0
, ""
, []
, ...
assertFalse
does not check whether the given value is False
by identity. This behavior is consistent with the if
statement:
if not None:
print('falsy value!')
Similarly, assertTrue
does not check whether a value is True
, and as such values like 1
, "abc"
, [1, 2, 3]
pass the test. See Truth Value Testing for more information.
This behavior is also explicitly documented:
assertTrue(expr, msg=None) assertFalse(expr, msg=None)Test that expr is true (or false).
Note that this is equivalent to
bool(expr) is True
and not toexpr is True
If you really want to be sure that a value is True
or False
, use assertIs
.
这篇关于Python unittest 成功断言 None 为 False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!