简体   繁体   English

使用 request_mock 根据请求动态设置响应

[英]Using request_mock to dynamically set response based on request

I am trying to mock a simple POST request that creates a resource from the request body, and returns the resource that was created.我正在尝试模拟一个简单的 POST 请求,该请求从请求正文创建资源,并返回创建的资源。 For simplicity, let's assume the created resource is exactly as passed in, but given an ID when created.为简单起见,我们假设创建的资源与传入的完全相同,但在创建时给出了 ID。 Here is my code:这是我的代码:

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

I end up with runtime error JSONDecodeError('Expecting value: line 1 column 1 (char 0)') .我最终得到运行时错误JSONDecodeError('Expecting value: line 1 column 1 (char 0)') I assume this is because request.json() does not contain what I am looking for.我认为这是因为request.json()不包含我要查找的内容。 How can I access the request body?如何访问请求正文?

This example is not complete and so we cannot truly see what is happening.这个例子并不完整,因此我们无法真正看到正在发生的事情。 In particular, it would be useful to see a sample function_that_creates_resource .特别是,查看示例function_that_creates_resource会很有用。

That said, I think your get_response code is valid.也就是说,我认为您的get_response代码是有效的。 I believe that you are not sending valid JSON data in your post request in function_that_creates_resource .我相信您在function_that_creates_resource的发布请求中没有发送有效的 JSON 数据。

I had to hack up your example a little bit as there is some information missing - but the basic idea works fine for me.由于缺少一些信息,我不得不稍微修改一下您的示例-但基本想法对我来说很好。 I think as mentioned something is wrong with the way you're creating the post request.我认为如上所述,您创建发布请求的方式有问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM