IOError异常处理的Unittest

时间:2017-08-01 11:35:39

标签: python unit-testing mocking ioerror

鉴于此代码:

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

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

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

但它不起作用。 这种方法是否正确?

1 个答案:

答案 0 :(得分:1)

实际上你需要启动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可以将callable作为第二个参数,使其等效于:

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)