getsentry / responses

A utility for mocking out the Python Requests library.
Apache License 2.0
4.08k stars 347 forks source link

Body value in query string format instead of json when asserting request calls data #700

Closed eduardo-boutiquenumerique closed 6 months ago

eduardo-boutiquenumerique commented 6 months ago

Describe the bug

When trying to assert that a post call was made with certain data (json) as in the docs , the body attribute that should return un json in strung format is returning a url formated data as it was a query parameter in a get call.

Additional context

No response

Version of responses

0.24.1

Steps to Reproduce

# your code goes here
import responses
import requests
import json
with responses.RequestsMock() as resp:
    mocked_response = resp.post("https://example.com", json={"test":"12345"}, status=200)
    requests.post("https://example.com", data={"request": "abcdef"})
    assert len(mocked_response.calls) == 1
    print(mocked_response.calls[0].request.body)
    assert json.loads(mocked_response.calls[0].request.body) == {"request": "abcdef"}

Expected Result

printing should be: '{"request": "abcdef"}' and the asserting should not raise an error

Actual Result

printing is request=abcdef assertion is raising an error in json.loads json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

beliaev-maksim commented 6 months ago

why do you think that the data should be json ?

here is a python example with native request:

import requests

r = requests.post("https://example.com", data={"request": "abcdef"})

here is the request data attached to r:

r.request.body
PyDev console: starting.
'request=abcdef'
eduardo-boutiquenumerique commented 6 months ago

Thanks for you quick reply.

I've got 2 reasons to think it should be a json:

  1. because it's a post call not a get one and the data is being sent in the body as a json.
  2. this is what is stated in the docs as shown below. It seems logical for me because of the reason 1. above. image

What do you think ?

beliaev-maksim commented 6 months ago

the point here is that we just mock requests, we do not invent new stuff

as you see my example above, that the request without responses library, and the output that you see with it. Response that is mocked with responses complies with it

eduardo-boutiquenumerique commented 6 months ago

I see. You are right. Thanks a lot.

My mistake what that I was using data keyword instead of json in requests.post.

I'll close this issue.