星期一, 六月 18, 2007

python 'try/except' in unittest?

起初,我在一个 test function 中定义的测试流程如下:

def setUp(self):
try:
self.head = Tree('root', data='head.data', extra='head.extra')
self.failUnlessEqual(self.head._Tree__node_value, 'root')
self.failUnlessEqual(self.head.data, 'head.data') #(1)
self.failUnlessEqual(self.head.extra, 'head.extra')
except:
seilf.fail(_("Unexpected exception catched"))
然后我运行这个单元测试:
sh$ python tree_ut.py
EEEE
======================================================================
ERROR: test__call__ (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tree_ut.py", line 29, in setUp
self.fail(_("Unexpected exception catched"))
File "/usr/lib/python2.3/unittest.py", line 270, in fail
raise self.failureException, msg
AssertionError: Unexpected exception catched

======================================================================
ERROR: test__setattr__ (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tree_ut.py", line 29, in setUp
self.fail(_("Unexpected exception catched"))
File "/usr/lib/python2.3/unittest.py", line 270, in fail
raise self.failureException, msg
AssertionError: Unexpected exception catched

======================================================================
ERROR: test__sgetitem__ (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tree_ut.py", line 29, in setUp
self.fail(_("Unexpected exception catched"))
File "/usr/lib/python2.3/unittest.py", line 270, in fail
raise self.failureException, msg
AssertionError: Unexpected exception catched

======================================================================
ERROR: test_tree (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tree_ut.py", line 29, in setUp
self.fail(_("Unexpected exception catched"))
File "/usr/lib/python2.3/unittest.py", line 270, in fail
raise self.failureException, msg
AssertionError: Unexpected exception catched

----------------------------------------------------------------------
Ran 4 tests in 0.006s

FAILED (errors=4)
这样的错误信息让人摸不着头脑,怎么会都是 Unexpected exception 呢?用:
def setUp(self):
try:
self.head = Tree('root', data='head.data', extra='head.extra')
self.failUnlessEqual(self.head._Tree__node_value, 'root')
self.failUnlessEqual(self.head.data, 'head.data') #(1)
self.failUnlessEqual(self.head.extra, 'head.extra')
except Exception, ex:
print 'DEBUG:', ex, ex.__class__
seilf.fail(_("Unexpected exception catched"))
分析一下,可以发现是 #(1) 部分抛出的异常被 except 捕捉了,当然这里这个测试用例是不对的,但这也说明在 unittest 使用这种 try/except 语法是行不通的,因为这样就掩盖了真实的错误,让人搞不清方向。

没有评论: