当前位置: 首页 > 知识库问答 >
问题:

如何模拟请求和响应?

卢志行
2023-03-14

在我的views.py中,我有一个函数,它每次使用不同的响应来调用各种requests.get()

def myview(request):
  res1 = requests.get('aurl')
  res2 = request.get('burl')
  res3 = request.get('curl')

在我的测试类中,我想做这样的事情,但无法计算出确切的方法调用

步骤1:

# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'

验证响应包含“a response”、“b response”、“c response”

如何完成步骤1(模拟请求模块)?

共有1个答案

陈功
2023-03-14

这就是您可以做的方法(您可以按原样运行此文件):

import requests
import unittest
from unittest import mock

# This is the class we want to test
class MyGreatClass:
    def fetch_json(self, url):
        response = requests.get(url)
        return response.json()

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    class MockResponse:
        def __init__(self, json_data, status_code):
            self.json_data = json_data
            self.status_code = status_code

        def json(self):
            return self.json_data

    if args[0] == 'http://someurl.com/test.json':
        return MockResponse({"key1": "value1"}, 200)
    elif args[0] == 'http://someotherurl.com/anothertest.json':
        return MockResponse({"key2": "value2"}, 200)

    return MockResponse(None, 404)

# Our test case class
class MyGreatClassTestCase(unittest.TestCase):

    # We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
    @mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Assert requests.get calls
        mgc = MyGreatClass()
        json_data = mgc.fetch_json('http://someurl.com/test.json')
        self.assertEqual(json_data, {"key1": "value1"})
        json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
        self.assertEqual(json_data, {"key2": "value2"})
        json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
        self.assertIsNone(json_data)

        # We can even assert that our mocked method was called with the right parameters
        self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
        self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)

        self.assertEqual(len(mock_get.call_args_list), 3)

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

重要提示:如果您的MyGreatClass类位于不同的包中,例如My.Great.package,则必须模拟My.Great.package.Requests.Get,而不是只模拟“Request.Get”。在这种情况下,您的测试用例将如下所示:

import unittest
from unittest import mock
from my.great.package import MyGreatClass

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    # Same as above


class MyGreatClassTestCase(unittest.TestCase):

    # Now we must patch 'my.great.package.requests.get'
    @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Same as above

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

好好享受!

 类似资料:
  • 我在JUnit中使用Mockito,并且我有一个使用RestTemboard向微服务发出请求的方法。 此方法返回一个JSON对象,该对象将在TokenRequestorPayload类中反序列化。 当我执行单元测试时,它们会失败,因为mock不起作用,我得到了一个org.springframework.web.client.ResourceAccessExcure。我怎么能嘲笑我的RestTem板

  • 我有一些python代码,它使用请求成功地从URL下载图像,并将其保存到中。我想测试一下,它应该做什么。我使用响应来测试JSON文件的获取,但我不确定如何模拟获取文件的行为。 我假设这类似于嘲笑一个标准的响应,就像下面一样,但是我想我忽略了如何将设置为文件... 更新:在Ashafix的评论之后,我正在尝试这个(python 3): 但随后,当我正在测试的代码尝试执行我得到的请求时: 感觉几乎是对

  • 问题内容: 我有与请求对象或用户对象进行交互的Django代码。例如: 如果要使用django python shell进行测试或在单元测试中进行测试,您将在其中传递什么?这里只是一个User对象即可,但是对模拟请求对象的需求也经常出现。 对于外壳或单元测试: 您如何嘲笑用户? 您如何模拟请求? 问题答案: 对于请求,我将使用Django随附的RequestFactory。 对于用户,我将按照@o

  • 似乎有很多不同的方法可以做到这一点,但我试图只使用sinon,sinon-test,chai/mocha,axios,httpmock模块。我无法成功模拟使用axios进行的GET调用。我希望能够模拟来自axios调用的响应,这样单元测试实际上就不必发出外部API请求。 我尝试过通过创建沙箱来建立一个基本的单元测试,并使用sinon stub来建立一个GET调用并指定预期的响应。我不熟悉JavaS

  • 我正在编写一些单元测试代码,我想模拟在我的函数中使用的模块:

  • 我正在使用API,我是PHP SOAP的新手。我正在尝试创建一个请求来获取车辆值,并希望获得响应值。 以下是示例SOAP 1.1请求。显示的占位符需要替换为实际值。 这是SOAP客户端URL调用- 这是我尝试过的,但没有结果- 我尝试了另一种方法,但在解析WSDL时出错 这是我得到的错误- SOAP-ERROR:解析WSDL:无法从'POST /vehicles/vehicle.asmxHTTP/