pwerth
pwerth

Reputation: 210

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. For simplicity, let's assume the created resource is exactly as passed in, but given an ID when created. 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)'). I assume this is because request.json() does not contain what I am looking for. How can I access the request body?

Upvotes: 0

Views: 1629

Answers (2)

jamielennox
jamielennox

Reputation: 388

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

Upvotes: 2

Adam Dangoor
Adam Dangoor

Reputation: 436

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.

That said, I think your get_response code is valid. I believe that you are not sending valid JSON data in your post request in function_that_creates_resource.

Upvotes: 0

Related Questions