#πŸ”’ Requests-mock library and `content=` question

4 messages Β· Page 1 of 1 (latest)

velvet citrus
#

Hey folks, trying to be specific as I can about my issue, and have not been able to find resources online specifically about content=, as opposed to json=, text=, etc

My question relates to the requests-mock library, and why content= works differently depending on if you simply call get(...) vs register_uri(...). I want to use register_uri(...) to (eventually) use the feature response lists allowing the ability to provide multiple data sets per api call. For now, I cannot get even this more simple setup to work, seen below:

For example, this is how to do a mock for a request:

json_blob = json.dumps([{'foo': 'bar'},{'fizz': 'buzz'}]).encode()
# m is a Mocker object
m.get(
     "https://my-api-endpoint.com/path/to/endpoint",
    content=json_blob # this is a JSON encoded Byte String
) 

^ this code works just fine

However, if you want to register the URI so you dont have to pass in content:

m.register_uri(
    "GET",
    "https://my-api-endpoint.com/path/to/endpoint",
    content=json_blob
)
m.get("https://my-api-endpoint.com/path/to/endpoint")

you actually get an error when it gets called:

response.json()
^^^^^^^^^^^^^^^

FAILED tests/test_my_api_endpoint.py::test_endpoint - requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have printed out the response object I got from the mock, and it shows that the content on the response object = b'', in other words, it's empty, whereas the simple get(URL, content=json_blob) version provides an actual object. Can anyone help me figure this one out? Thank you!

vale masonBOT
#

@velvet citrus

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

vale masonBOT
#

@velvet citrus

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.