【发布时间】:2019-04-08 17:36:43
【问题描述】:
假设我有这个功能:
def to_upper(var):
assert type(var) is str, 'The input for to_upper should be a string'
return var.upper()
还有一个使用unittest进行单元测试的文件:
class Test(unittest.TestCase):
def test_1(self):
-- Code here --
if __name__ == '__main__':
unittest.main()
如何测试如果我调用 to_upper(9) 会引发断言错误?
【问题讨论】:
-
附带说明,您可能希望将
type(var) is str更改为isinstance(var, str)以更符合习惯并处理str的子类 -
鉴于可以在运行时禁用断言,这似乎是一个无用的测试。
-
@chepner 可能是对的。随它去吧。如果
var不是str,to_upper将自动提升AttributeError(假设它没有实现upper)
标签: python testing assert python-unittest