getsentry / responses

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

Add capability for matching non json request bodies #716

Closed TheJacobWalters closed 5 months ago

TheJacobWalters commented 6 months ago

At work I use responses for mocking api responses for the applications I develop. One of the APIs my application is interacting with does not take input in json format.

A call to this api looks like this

'''Curl api.company.com/v1/id --data '12345' '''

I would like to create a matcher for non json in the body.

I am pretty new to open source and only have some bug fixes and documentation fixes so I would like to contribute this feature back to responses. I think I can code this up from looking at the source. But would responses accept this feature?

markstory commented 6 months ago

But would responses accept this feature?

It depends on how general purpose the matcher ends up being. There are matchers for URL encoded, multi-part form and other content types already, and another general purpose matcher could be a good fit.

beliaev-maksim commented 6 months ago

usually you send this kind of data in POST. Then we already cover it

please provide requests snippet that you try to mock

TheJacobWalters commented 6 months ago

Thank you, yes I agree this would make sense that it would be a good design for this API that I'm mocking to have been designed to be a POST request.

Here is the requests snippet I am mocking. This actually returns JSON. Its kind of a strange design.

resp = requests.get("https://123abc.execute-api.us-east-1.amazonaws.com/v1/id", data="123456789", timeout=60)

jwodder commented 6 months ago

I think the simplest and most general-purpose body matcher would be something for matching against the raw bytes in a request like:

def bytes_body_matcher(content: bytes) -> Callable[..., Any]:
    def match(request: PreparedRequest) -> tuple[bool, str]:
        if request.body == content:
            return (True, "")
        else:
            return (False, "Request body does not have expected content")

    return match

Honestly, I'm surprised responses doesn't provide a matcher like this already.

TheJacobWalters commented 5 months ago

Could we get this Issue resolved with this Pull Request https://github.com/getsentry/responses/pull/717