python assertRaise未捕获MagicMock异常

2024-09-27 23:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个单元测试来检查python3.4代码的错误处理。我使用mock中的MagicMock替换子函数并将异常作为副作用引发,然后使用unittest中的assertRaises来检查是否引发了异常。在

不幸的是,虽然代码似乎正在处理异常,但测试似乎因为异常而崩溃。我曾尝试重写测试以使用try/except循环,但没有效果,我尝试将其转换为nose2@raise AttributeError,但没有成功。在

代码中的错误处理是否以某种方式阻止了测试捕获引发的异常?在

代码:

import unittest2 as unittest
from mock import MagicMock

class Service():

    def _execute(self, entity, destport):

        print("setting format to json")
        self.format = "json"

        try:
            print("call _reply_in_json")
            getattr(self, "_reply_in_%s" % self.format)(entity, destport)
            return ""
        except AttributeError:
            print("Invalid format requested")
            err = "invalid format requested"
            return err


class TestService(unittest.TestCase):

    def test_executeAttributeError(self):
        self.entity = "butter"
        self.destport = 54
        self.ret = False

        print("## Starting test_executeAttributeError for CsvDs")

        # Set up test objects
        testDS = Service()
        testDS._reply_in_json = MagicMock(name='_reply_in_json', side_effect=Exception(AttributeError))

        # Run the test
        with self.assertRaises(AttributeError):
            print("Execute new request")
            self.ret = testDS._execute(self.entity, self.destport)

        if self.ret:
            self.assertEqual(self.ret, "invalid format requested")

            # Check the call was made correctly.
            testDS._reply_in_json.assert_called_once_with(self.entity, self.destport)
        else:
            print("nothing returned")

        print("test_executeAttributeError for CsvDs completed successfully\n")

if __name__ == '__main__':
   suite = unittest.TestLoader().loadTestsFromTestCase(TestService)
   unittest.TextTestRunner(verbosity=2).run(suite)

输出:

^{pr2}$

Tags: 代码intestselfjsonformatunittestreply
1条回答
网友
1楼 · 发布于 2024-09-27 23:27:49

您并不是在副作用中引发AttributeError,而是引发一个以AttributeError作为参数的基异常。直接使用实际的异常:

testDS._reply_in_json = MagicMock(name='_reply_in_json', side_effect=AttributeError)

还要注意,assertRaises将失败,因为_execute捕捉到该异常并返回错误消息,因此测试用例本身不会看到任何异常。在

相关问题 更多 >

    热门问题