【问题标题】:Using request_mock to dynamically set response based on request使用 request_mock 根据请求动态设置响应
【发布时间】:2021-05-03 00:12:13
【问题描述】:

我正在尝试模拟一个简单的 POST 请求,该请求从请求正文创建资源,并返回创建的资源。为简单起见,我们假设创建的资源与传入的完全一样,但在创建时给出了 ID。这是我的代码:

def test_create_resource(requests_mock):
    # Helper function to generate dynamic response
    def get_response(request, context):
        context.status_code = 201
        # I assumed this would contain the request body
        response = request.json()
        response['id'] = 100
        return response

    # Mock the response
    requests_mock.post('test-url/resource', json=get_response)
    resource = function_that_creates_resource()
    assert resource['id'] == 100

我最终遇到运行时错误JSONDecodeError('Expecting value: line 1 column 1 (char 0)')。我认为这是因为request.json() 不包含我要查找的内容。如何访问请求正文?

【问题讨论】:

    标签: python-3.x requests-mock


    【解决方案1】:

    这个例子并不完整,所以我们无法真正看到正在发生的事情。 特别是,查看示例function_that_creates_resource 会很有用。

    也就是说,我认为您的 get_response 代码是有效的。 我相信您在function_that_creates_resource 的发布请求中没有发送有效的 JSON 数据。

    【讨论】:

      【解决方案2】:

      由于缺少一些信息,我不得不稍微修改一下您的示例-但基本想法对我来说很好。我认为如上所述,您创建发布请求的方式有问题。

      import requests
      import requests_mock
      
      
      with requests_mock.mock() as mock:
      
          # Helper function to generate dynamic response
          def get_response(request, context):
              context.status_code = 201
              # I assumed this would contain the request body
              response = request.json()
              response['id'] = 100
              return response
      
          # Mock the response
          mock.post('http://example.com/test-url/resource', json=get_response)
      
          # resource = function_that_creates_resource()
          resp = requests.post('http://example.com/test-url/resource', json={'a': 1})
      
          assert resp.json()['id'] == 100
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-08
        • 2014-09-10
        • 2021-08-10
        • 2019-12-14
        • 2015-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多