在这篇文章中,我们将介绍单元测试的布尔断言方法 assertTrue 和 assertFalse 与身份断言 assertIs 之间的区别。

定义
下面是目前单元测试模块文档中关于 assertTrue 和 assertFalse 的说明,代码进行了高亮:
assertTrue(expr, msg=None)
assertFalse(expr, msg=None)测试该表达式是真值(或假值)。
注:这等价于
bool(expr) is True而不等价于
expr is True(后一种情况请使用
assertIs(expr, True))。
在一个布尔值的上下文环境中能变成“真”的值
在 Python 中等价于:
bool(expr) is True
这个和 assertTrue 的测试目的完全匹配。
因此该文档中已经指出 assertTrue 返回真值,assertFalse 返回假值。这些断言方法从接受到的值构造出一个布尔值,然后判断它。同样文档中也建议我们根本不应该使用 assertTrue 和 assertFalse。
在实践中怎么理解?
我们使用一个非常简单的例子 – 一个名称为 always_true 的函数,它返回 True。我们为它写一些测试用例,然后改变代码,看看测试用例的表现。
作为开始,我们先写两个测试用例。一个是“宽松的”:使用 assertTrue 来测试真值。另外一个是“严格的”:使用文档中建议的 assertIs 函数。
import unittest
from func import always_true
class TestAlwaysTrue(unittest.TestCase):
def test_assertTrue(self):
"""
always_true returns a truthy value
"""
result = always_true()
self.assertTrue(result)
def test_assertIs(self):
"""
always_true returns True
"""
result = always_true()
self.assertIs(result, True)
下面是 func.py 中的非常简单的函数代码:
def always_true():
"""
I'm always True.
Returns:
bool: True
"""
return True
当你运行时,所有测试都通过了:
always_true returns True ... ok
always_true returns a truthy value ... ok
-
Traceback (most recent call last):
File "/tmp/assertttt/test.py", line 22, in test_is_true
self.assertIs(result, True)
AssertionError: 'True' is not True
via: <http://jamescooke.info/python-unittest-asserttrue-is-truthy-assertfalse-is-falsy.html>
作者:[James Cooke](http://jamescooke.info/pages/hello-my-name-is-james.html) 译者:[chunyang-wen](https://github.com/chunyang-wen) 校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出


发表回复