@patch装饰器在unittest.mock中如何工作?

问题描述

我有一个类,其中有多个方法正在将requests.get()模块的requests方法调用到外部API:

MyClass():
   
   method1(self):

      r = requests.get(...)
      resp = r.json()
      
      plan = resp.get("Meta").get("plan")
      return plan

   method2(self):

      r = requests.get(...)
      resp = r.json()

      return resp.get("data")

现在,我正在使用unittest.mock来尝试模拟响应,但是我对@patch装饰器的工作感到困惑。


import unittest
from unittest.mock import Mock,patch
import requests

class TestBase(unittest.TestCase):

    @patch("requests.get")
    def test(self,mocked_get):

       mocked_response = Mock()
       mocked_response.json.return_value = {"foo": "bar"}
       mocked_get.return_value = mocked_response

       resp = MyClass().method1()
 
       self.assertEqual(resp,{"foo": "bar"})

这到底是怎么回事? @patch是否在requests.get()内寻找method1,并用JSON返回值为{"foo": "bar"}的模拟对象替换它? 此对象是否已替换为整个方法?直到方法达到返回值?

如何知道要在method1中查找它?如何指定要在MyClass中模拟的方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)