Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Httpx Human Readable Responses #788

Merged
merged 7 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions tests/integration/test_httpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,3 +285,31 @@ def test_stream(tmpdir, httpbin, do_request):
assert cassette_content == response_content
assert len(cassette_content) == 512
assert cassette.play_count == 1


@pytest.mark.online
def test_text_content_type(tmpdir, httpbin, do_request):
url = httpbin.url + "/json"

with vcr.use_cassette(str(tmpdir.join("json_type.yaml"))):
response = do_request()("GET", url)

with vcr.use_cassette(str(tmpdir.join("json_type.yaml"))) as cassette:
cassette_response = do_request()("GET", url)
assert cassette_response.content == response.content
assert cassette.play_count == 1
assert isinstance(cassette.responses[0]["content"], str)


@pytest.mark.online
def test_binary_content_type(tmpdir, httpbin, do_request):
url = httpbin.url + "/bytes/1024"

with vcr.use_cassette(str(tmpdir.join("json_type.yaml"))):
response = do_request()("GET", url)

with vcr.use_cassette(str(tmpdir.join("json_type.yaml"))) as cassette:
cassette_response = do_request()("GET", url)
assert cassette_response.content == response.content
assert cassette.play_count == 1
assert isinstance(cassette.responses[0]["content"], bytes)
9 changes: 8 additions & 1 deletion vcr/stubs/httpx_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,16 @@ def _transform_headers(httpx_response):


def _to_serialized_response(httpx_response):
try:
content = httpx_response.content.decode("utf-8")
except UnicodeDecodeError:
content = httpx_response.content

return {
"status_code": httpx_response.status_code,
"http_version": httpx_response.http_version,
"headers": _transform_headers(httpx_response),
"content": httpx_response.content,
"content": content,
}


Expand All @@ -58,6 +63,8 @@ def _from_serialized_headers(headers):
@patch("httpx.Response.read", MagicMock())
def _from_serialized_response(request, serialized_response, history=None):
content = serialized_response.get("content")
if isinstance(content, str):
content = content.encode("utf-8")
response = httpx.Response(
status_code=serialized_response.get("status_code"),
request=request,
Expand Down
Loading