getsentry / responses

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

No access to request query string, body, etc. on mock object #680

Closed ThiefMaster closed 8 months ago

ThiefMaster commented 8 months ago
In [1]: with responses.RequestsMock() as rsps:
    ...:     req = rsps.add(
    ...:         responses.POST,
    ...:         'http://example.com/foobar',
    ...:         body='{"foo": "bar"}',
    ...:         status=200,
    ...:         content_type='application/json',
    ...:     )
    ...:     resp = requests.post('http://example.com/foobar', json={'hello': 'world'}, params={'query': 'string'})
    ...:     print('response body', resp.json())
    ...:     print('request body', req.body)
    ...:     print('request url', req.url)
    ...:     pprint(req.__dict__)

response body {'foo': 'bar'}
request body {"foo": "bar"}
request url http://example.com/foobar
{'auto_calculate_content_length': False,
 'body': '{"foo": "bar"}',
 'call_count': 1,
 'content_type': 'application/json',
 'headers': None,
 'match': (),
 'method': 'POST',
 'passthrough': False,
 'status': 200,
 'stream': None,
 'url': 'http://example.com/foobar'}

I would have expected to be able to access the query string and body of the original request via the mock object. This would allow more complex assertions in a more imperative way than the (pretty declarative) matcher approach (which is great for simple cases though).

Since a single mocked response can be called multiple times, maybe it'd be nice to have something like req.calls[...] = with request objects (similar to the requests.Request class) that contain the original data from the request that was intercepted by this library.

beliaev-maksim commented 8 months ago

I think this is conceptual mistake. rsps.add returns Response object and not request although, you can use resp.request which will return you requests.models.PreparedRequest

ThiefMaster commented 8 months ago

Sure, but I do not have access to resp when I call a function from my application that makes an HTTP request I'm mocking.

So basically I'm looking for a way to access the resp.request through without having access to resp. A bit like stdlib Mock objects give you access to all calls made on its methods.

beliaev-maksim commented 8 months ago

then #664 should address your issue

ThiefMaster commented 8 months ago

indeed, thanks!