requests-mock
requests-mock copied to clipboard
add support for requests event hooks
Feature request
I would like to call requests_mock.get("http://foo", hook={"response": my_hook_func})
https://2.python-requests.org/en/master/user/advanced/#event-hooks
Why
I'm writing test for a multi thread application (message/queue with a Redis broker). While HTTP requests made from another thread do get handled by requests_mock, tracing history is not working. So my workaround is to increment a counter in redis every time the mock is used.
It would be nice to implement such a workaround by adding support for requests hooks. But currently requests_mock reject the hook option. So my uglier workaround is implemented with callbacks :
def test_foo(redis, requests_mock):
def make_body(request, context):
redis.incr("mock_call_count")
context.status_code = 200
return "foo"
requests_mock.get("http://foo", text=make_body)
for _ in range(3):
requests.get("http://foo") # in my case this would be called in another thread
assert redis.get("mock_call_count") == "3"
Hi, I'm not entirely convinced on this one, just because it's a very edge case.
What's not working from a multi-thread perspective? I've not done this, but from a quick skim of the documentation a requests Session is thread safe, does it make sense to mock the adapter of an individual session here: https://requests-mock.readthedocs.io/en/latest/adapter.html so that they don't interact?