2

我正在尝试使用 python2.7 的 unittest 模块测试调用不带参数的外部命令会引发 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

是不是unittest的异常测试无法处理外部命令,例如异常在别处被截获?

谢谢!

4

1 回答 1

2

我只能认为这个CalledProcessError名字被践踏了,也许明确说明它会有所帮助

with self.assertRaises(subprocess.CalledProcessError) as context:
于 2013-03-04T16:53:43.803 回答