Python unittest 成功断言 None 为 False

Python unittest successfully asserts None is False

为什么 assertFalseNone 上成功?

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

似乎这种行为会引发错误,其中函数并不总是 return 一个值。例如:

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] 这样的值会通过测试.有关详细信息,请参阅 Truth Value Testing

这种行为也是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 to expr is True

如果您真的想确定某个值是 TrueFalse,请使用 assertIs

Python 函数的默认 return 值为 None

Python 也实现了 Duck typing,所以一些值被威胁为 falsey,那些是

  • 空字符串
  • 整数零
  • 布尔值假
  • 空列表
  • 空元组

所以是的,如果您想明确检查 False 布尔值,您应该将其实现为 self.assertEquals(False, None)。这不是一个好主意,在 python 中你可以做

if my_value:
    print 'truthy value'
else:
    print 'falsey value'

您可以使用 boundary-value analysis 来设计您的测试用例来检查您的极端情况。

你的情况实际上在文档中指出:

Note that this is equivalent to bool(expr) is True and not to expr is True (use assertIs(expr, True) for the latter).

来源:https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertFalse