【发布时间】:2017-01-19 18:29:40
【问题描述】:
我有一个包含代码的文件 testtest.py
import unittest
def add(self, a, b):
return a + b
class Test(unittest.TestCase):
def test_additon(self):
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
#self.assertRaises(TypeError, lambda: add(1 + '1'), msg="Addition failed")
if __name__ == '__main__':
unittest.main()
问题是assertRaises 没有正确捕获异常,并且我的所有测试都因错误而不是基于条件而失败,这是我得到的输出:
E
======================================================================
ERROR: test_additon (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testtest.py", line 9, in test_additon
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
我知道我可以通过使用 lambda(我在代码中将其注释掉)来解决它,以使我的测试正确捕获异常,但根据文档,将可调用对象和参数传递给 assertRaises 应该可以工作,因为它会自行在内部调用该函数并能够捕获引发的任何异常。
assertRaises(*callable*, *args*, *kwargs*)
但它没有
如果我使用 lambda 运行它,它是一个可调用的,稍后将由 assertRaises 评估,它会按预期工作,我明白了
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
I'm running python 3.5
Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
但我也得到与 python2.7 相同的行为
【问题讨论】:
标签: python unit-testing lambda python-3.5 python-unittest