gpt4 book ai didi

python模拟异常处理

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:12 25 4
gpt4 key购买 nike

我的工作流程中有几个任务。现在,我想模拟 Task1 返回异常的输出,并且只测试 task2.run 方法未被调用。

class Task1():
def run(self):
try:
return 2,2
except Exception as e:
print e
raise Exception('Task1 Exception')

class Task2():
def run(self,x,y):
try:
return 2 * (x*y)
except Exception as e:
print e
raise Exception('Task2 Exception')

class Workflow():
def run(self,task1, task2):
x,y = task1.run()
print task2.run(x,y)


task1 = Task1()
task2 = Task2()

w = Workflow()
w.run(task1,task2)

这是我的单元测试 -

import unittest
import mock
from test2 import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
def test_workflow(self):
self.task1 = mock.MagicMock(Task1()) # mocking task1
self.task2 = mock.MagicMock(Task2())
self.task1.side_effect = Exception() # setting task1 exception to an exception object

self.workflow = Workflow()
self.workflow.run(self.task1, self.task2)
self.task2.run.assert_not_called() # checking task2 is not called.


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

异常(exception):-

    x,y = task1.run()
ValueError: need more than 0 values to unpack

最佳答案

根据语法,您使用的是 Python 2,但我将引用 Python 3 official documentation anyway. 中的文档。我相信该解决方案适用。

第一个例子是:

from unittest.mock import MagicMock

thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
#prints 3

thing.method.assert_called_with(3, 4, 5, key='value')

如果你遇到这个问题,你将得到下面的代码,而不是当前的代码。请注意,我正在将 Task1.run 和 Task2.run 方法分配给 MagicMock 实例。

import unittest
import mock
from t import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
def test_workflow(self):
self.task1 = Task1()
self.task1.run = mock.MagicMock() # mocking run from task1
self.task2 = Task2()
self.task2.run = mock.MagicMock()
self.task1.run.side_effect = Exception() # setting task1 exception to an exception object

self.workflow = Workflow()
self.workflow.run(self.task1, self.task2)
self.task2.run.assert_not_called() # checking task2 is not called.


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

关于python模拟异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com