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

Suppress binary output on the command line. #2076

Merged
merged 1 commit into from Feb 9, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions httpx/_main.py
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions tests/conftest.py
Expand Up @@ -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"):
Expand Down Expand Up @@ -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()
Expand Down
16 changes: 16 additions & 0 deletions tests/test_main.py
Expand Up @@ -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()
Expand Down