gpt4 book ai didi

python - 我如何模拟在我的类中使用 requests.get 的方法?

转载 作者:行者123 更新时间:2023-12-01 22:25:23 24 4
gpt4 key购买 nike

我正在尝试为我的类(class)创建一些单元测试。我想模拟这些,这样我就不会耗尽运行其中一些测试的 API 配额。我有多个将调用 fetch 方法的测试用例,根据传递的 URL,我会得到不同的结果。

我的示例类如下所示:

import requests
class ExampleAPI(object):
def fetch(self, url, params=None, key=None, token=None, **kwargs):
return requests.get(url).json() # Returns a JSON string

tutorial我正在看表明我可以做这样的事情的节目:

import unittest
from mock import patch

def fake_fetch_test_one(url):
...

class TestExampleAPI(unittest.TestCase):
@patch('mymodule.ExampleAPI.fetch', fake_fetch_test_one)
def test_fetch(self):
e = ExampleAPI()
self.assertEqual(e.fetch('http://my.api.url.example.com'), """{'result': 'True'}""")

但是,当我这样做时,我收到一条错误消息:

TypeError: fake_fetch_test_one() takes exactly 1 argument (3 given)

模拟类方法中的 requests.get 调用的正确方法是什么?我需要能够更改每次测试的模拟响应,因为不同的 URL 可以提供不同的响应类型。

最佳答案

您的虚假提取需要接受与原始提取相同的参数:

def fake_fetch(self, url, params=None, key=None, token=None, **kwargs):

请注意,最好只模拟外部接口(interface),这意味着让 fetch 调用 requests.get(或者至少,它认为是 requests。获取):

@patch('mymodule.requests.get')
def test_fetch(self, fake_get):
# It would probably be better to just construct
# a valid fake response object whose `json` method
# would return the right thing, but this is a easier
# for demonstration purposes. I'm assuming nothing else
# is done with the response.
expected = {"result": "True"}
fake_get.return_value.json.return_value = expected
e = ExampleAPI()
self.assertEqual(e.fetch('http://my.api.url.example.com'), expected)

关于python - 我如何模拟在我的类中使用 requests.get 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732487/

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