python:测试子进程调用是否抛出预期的异常

时间:2013-03-04 16:40:23

标签: python unit-testing exception subprocess

我正在尝试测试一个没有参数的外部命令将使用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

单元测试的异常测试是否无法处理外部命令,例如,异常被其他地方截获?

谢谢!

1 个答案:

答案 0 :(得分:2)

我只能认为CalledProcessError名称已被践踏,可能明确说明它会有所帮助

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