2013-03-04 39 views
1

我試圖測試調用不帶參數的外部命令使用python2.7的單元測試模塊,這樣拋出一個異常CalledProcessError:蟒蛇:測試是否子進程調用拋出預期的異常

import unittest 

class MyTest(unittest.TestCase) 
    def testCommand(self): 
     cmd = 'MyCommand' 
     gotLog = 'UndefinedGot' 
     with self.assertRaises(CalledProcessError) as context: 
      gotLog = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).strip() 
     expectedLog = 'some error' 
     self.assertEqual(context.exception.message, expectedLog) 

但是,在運行測試仍然給我

Traceback (most recent call last): File "MyTest.py", line 51, in testCommand 
    gotLog = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).strip() 
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 544, in check_output: 
    raise CalledProcessError(retcode, cmd, output=output) 
CalledProcessError: Command 'MyCommand' returned non-zero exit status 2 

是它的單元測試的異常測試不能處理外部命令,例如,除了得到其他地方攔截?

謝謝!

回答

1

我只能認爲,CalledProcessError名字已經被踐踏,也許明確說明,這將有助於

with self.assertRaises(subprocess.CalledProcessError) as context: 
+0

謝謝!希望錯誤信息可以更直觀一些。 – kakyo 2013-03-04 19:49:51