首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于IOError异常处理的统一测试

用于IOError异常处理的统一测试
EN

Stack Overflow用户
提问于 2017-08-01 11:35:38
回答 1查看 2.8K关注 0票数 3

鉴于这一守则:

代码语言:javascript
运行
复制
 try:
        #do something
 except IOError as message:
        logging.error(message)
        raise message

我想测试异常处理部分,以便有全面的覆盖。在我尝试过的统一测试中:

代码语言:javascript
运行
复制
        with patch(new=Mock(side_effect=IOError(errno.EIO))):
            self.assertRaises(IOError)

但它不起作用。这个方法正确吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-01 13:50:41

实际上,您需要启动模拟,以便启动side_effect,例如:

代码语言:javascript
运行
复制
class Test(unittest.TestCase):

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

self.assertRaises可以将一个可调用的参数作为第二个参数,使其等价于:

代码语言:javascript
运行
复制
class Test(unittest.TestCase):
    def test(self):
        mock = m.Mock()
        mock.side_effect = Exception("Big badaboum")
        with self.assertRaises(Exception):
            mock()

如果您想在带有修补程序的测试中使用它,可以执行以下操作:

代码语言:javascript
运行
复制
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()

编辑:为了测试除了块内错误的引发,您需要在您编写的try块中模拟一个函数调用,例如:

代码语言:javascript
运行
复制
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周期):

代码语言:javascript
运行
复制
class Test(unittest.TestCase):
    @m.patch("__main__.do_sthing",side_effect=IOError("IOError"))
    def test(self, mock):
        self.assertRaises(ValueError, raise_error)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45436705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档