diff --git a/tests/integration/test_httpx.py b/tests/integration/test_httpx.py index 22b3e6933..723daed7b 100644 --- a/tests/integration/test_httpx.py +++ b/tests/integration/test_httpx.py @@ -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) diff --git a/vcr/stubs/httpx_stubs.py b/vcr/stubs/httpx_stubs.py index aa5e05a40..4d4b96a07 100644 --- a/vcr/stubs/httpx_stubs.py +++ b/vcr/stubs/httpx_stubs.py @@ -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, } @@ -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,