Created
April 27, 2022 03:31
-
-
Save skshetry/98f6c4b88e4acb40ea8124143f63eada to your computer and use it in GitHub Desktop.
Track history of request, responses in httpx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import httpx | |
import pytest | |
from typing import NamedTuple, Dequeue | |
from unittest import mock | |
class Transaction(NamedTuple): | |
request: httpx.Request | |
response: httpx.Response | |
class ResponseHistory(Deque[Transaction]): | |
pass | |
@pytest.fixture() | |
def response_history() -> ResponseHistory: | |
http_send = httpx.Client.send | |
history = ResponseHistory() | |
def wrap_send(client, req, *args, **kwargs): | |
resp = http_send(client, req, *args, **kwargs) | |
history.append(Transaction(req, resp)) | |
return resp | |
with mock.patch("httpx.Client.send", side_effect=wrap_send, autospec=True): | |
yield history | |
@pytest.fixture(autouse=True) | |
def assert_all_responses_are_closed(response_history: ResponseHistory): | |
yield | |
for transaction in response_history: | |
assert transaction.response.is_closed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment