简体   繁体   English

无法捕获Python模拟异常

[英]Python mocked exception not being caught

Struggling to succinctly describe this in the title... 努力在标题中简洁地描述这一点...

I have a module I want to test: 我有一个要测试的模块:

mod.py : mod.py

import subprocess
class MyStuff(object):
    def my_fun(self):
        try:
            print subprocess
            out = subprocess.check_output(["echo", "pirates"])
        except subprocess.CalledProcessError:
            print "caught exception"

And the test module test_mod.py : 和测试模块test_mod.py

import unittest
import mock
from mod import MyStuff
import subprocess

class Tests(unittest.TestCase):
    def setUp(self):
        self.patched_subprocess = mock.patch(
            'mod.subprocess', autospec=True)
        self.mock_subprocess = self.patched_subprocess.start()
        self.my_stuff = MyStuff()

    def tearDown(self):
        self.patched_subprocess.stop()

    def test_my_fun(self):
        self.mock_subprocess.check_output = mock.Mock(
            side_effect=subprocess.CalledProcessError(0, "hi", "no"))
        with self.assertRaises(subprocess.CalledProcessError):
            out = self.my_stuff.my_fun()

if __name__ == '__main__':
    unittest.main()

I then run python test_mod.py and I see the following output: 然后,我运行python test_mod.py ,我看到以下输出:

<NonCallableMagicMock name='subprocess' spec='module' id='140654009377872'>
.
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK

I'm pleased that the subprocess object has been mocked, but why is the print "caught exception" statement not executed? 我很高兴子流程对象已被模拟,但是为什么执行print "caught exception"语句? I'm guessing it's because the real exception getting throw in test_mod.subprocess.CalledProcessException and not subprocess.CalledProcessException as I intend, but I'm not sure how to resolve that. 我猜这是因为真正的例外,在获得罚球test_mod.subprocess.CalledProcessException而不是subprocess.CalledProcessException因为我打算,但我不知道如何解决这个问题。 Any suggestion? 有什么建议吗? Thanks for your time. 谢谢你的时间。

I solved this eventually... 我终于解决了这个...

The problem was I was mocking the entire subprocess module, which included the CalledProcessError exception! 问题是我在CalledProcessError 整个子流程模块,其中包括CalledProcessError异常! That's why it didn't seem to match the exception I was raising in my test module, because it was a completely different object. 这就是为什么它似乎与我在测试模块中提出的异常不匹配的原因,因为它是一个完全不同的对象。

The fix is to mock just subprocess.check_output , D'oh! 解决方法是模拟subprocess.check_output ,哦!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM