IOError 异常处理的单元测试

Unittest for IOError exception handling

鉴于此代码:

 try:
        #do something
 except IOError as message:
        logging.error(message)
        raise message

我想测试异常处理部分以便全面覆盖。 在我试过的单元测试中:

        with patch(new=Mock(side_effect=IOError(errno.EIO))):
            self.assertRaises(IOError)

但它不起作用。 这种做法正确吗?

实际上您需要启动 Mock 以便 side_effect 启动,例如以下内容:

class Test(unittest.TestCase):

    def test(self):
        mock = m.Mock()
        mock.side_effect = Exception("Big badaboum")
        self.assertRaises(Exception, mock)

self.assertRaises 可以将可调用对象作为第二个参数,使其等效于:

class Test(unittest.TestCase):
    def test(self):
        mock = m.Mock()
        mock.side_effect = Exception("Big badaboum")
        with self.assertRaises(Exception):
            mock()

如果你想在补丁测试中使用它,你可以执行以下操作:

import unittest.mock as m
import unittest

def raise_error():
    try:
        print("Hello") #placeholder for the try clause
    except Exception as e:
        print(e) #placeholder for the exceptclause

class Test(unittest.TestCase):
    @m.patch("__main__.raise_error", side_effect=Exception("Big badaboum")) #replace  __main__ by the name of the module with your function
    def test(self, mock):
        with self.assertRaises(Exception):
            mock()

unittest.main()

编辑:要测试 except 块内错误的引发,您需要在您编写的 try 块内模拟函数调用,例如:

import unittest.mock as m
import unittest

def do_sthing():
    print("Hello")

def raise_error():
    try:
        do_sthing() #this call can be mocked to raise an IOError
    except IOError as e:
        print(e.strerror)
        raise ValueError("Another one")

class Test(unittest.TestCase):
    def test(self):
        with m.patch("__main__.do_sthing", side_effect=IOError("IOError")):
            self.assertRaises(ValueError, raise_error)


unittest.main()

您也可以使用装饰器语法(只是将上面的测试重写以节省一些 CPU 循环):

class Test(unittest.TestCase):
    @m.patch("__main__.do_sthing",side_effect=IOError("IOError"))
    def test(self, mock):
        self.assertRaises(ValueError, raise_error)