【发布时间】:2022-01-08 02:14:51
【问题描述】:
是否可以在一种方法中模拟更多请求类型(GET、POST、PUT 等...)?我可以使用 mock.patch 装饰器模拟一种类型的请求。但是,如何在一种测试方法中模拟更多类型?我正在为它寻找一个 Pythonic 和优雅的解决方案(我更喜欢 mock.patch 装饰器,但我也愿意接受其他解决方案)。
您可以在下面看到我的问题的示例:
source.py
import requests
def source_function():
x = requests.get("get_url.com")
requests.post("post_url.com/{}".format(x.text))
test.py
import unittest
from unittest import mock
from source import source_function
class TestCases(unittest.TestCase):
@mock.patch("requests.get")
def test_source_function(self, mocked_get):
mocked_get.return_value = mock.Mock(status_code=201, json=lambda: {"data": {"id": "test"}})
source_function() # The POST request is not mocked.
【问题讨论】:
-
你需要修补
source.requests.get,所以是实际调用发生的地方。 -
当然,我在生产代码中这样做,但它不能解决我的问题。如何在一种测试方法中模拟 GET 和 POST 请求类型?这是我的问题。
-
您可以随意模拟。尝试模拟
post方法并得到错误? -
我可以分别模拟 GET/POST/PUT 等...但我不知道如何在一种测试方法中模拟更多。
标签: python python-3.x unit-testing python-requests