From: waterfountain1996 <71171892+waterfountain1996@users.noreply.github.com> Date: Wed, 9 Feb 2022 15:40:39 +0000 (+0200) Subject: Suppress binary output on the command line (#2049) (#2076) X-Git-Tag: 0.23.0~41 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4c307488cd1e1d934aedd60bfcace18a18baeaab;p=thirdparty%2Fhttpx.git Suppress binary output on the command line (#2049) (#2076) --- diff --git a/httpx/_main.py b/httpx/_main.py index 24ca30dd..7bd6b908 100644 --- a/httpx/_main.py +++ b/httpx/_main.py @@ -172,10 +172,11 @@ def print_response(response: Response) -> None: text = response.text else: text = response.text + syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) console.print(syntax) - else: # pragma: nocover - console.print(rich.markup.escape(response.text)) + else: + console.print(f"<{len(response.content)} bytes of binary data>") def format_certificate(cert: dict) -> str: # pragma: nocover diff --git a/tests/conftest.py b/tests/conftest.py index c40df097..970c3535 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -80,6 +80,8 @@ async def app(scope, receive, send): await status_code(scope, receive, send) elif scope["path"].startswith("/echo_body"): await echo_body(scope, receive, send) + elif scope["path"].startswith("/echo_binary"): + await echo_binary(scope, receive, send) elif scope["path"].startswith("/echo_headers"): await echo_headers(scope, receive, send) elif scope["path"].startswith("/redirect_301"): @@ -155,6 +157,25 @@ async def echo_body(scope, receive, send): await send({"type": "http.response.body", "body": body}) +async def echo_binary(scope, receive, send): + body = b"" + more_body = True + + while more_body: + message = await receive() + body += message.get("body", b"") + more_body = message.get("more_body", False) + + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"application/octet-stream"]], + } + ) + await send({"type": "http.response.body", "body": body}) + + async def echo_headers(scope, receive, send): body = { name.capitalize().decode(): value.decode() diff --git a/tests/test_main.py b/tests/test_main.py index e9f56df8..3a202224 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -52,6 +52,22 @@ def test_json(server): ] +def test_binary(server): + url = str(server.url.copy_with(path="/echo_binary")) + runner = CliRunner() + content = "Hello, world!" + result = runner.invoke(httpx.main, [url, "-c", content]) + assert result.exit_code == 0 + assert remove_date_header(splitlines(result.output)) == [ + "HTTP/1.1 200 OK", + "server: uvicorn", + "content-type: application/octet-stream", + "Transfer-Encoding: chunked", + "", + f"<{len(content)} bytes of binary data>", + ] + + def test_redirects(server): url = str(server.url.copy_with(path="/redirect_301")) runner = CliRunner()