From: Tom Christie Date: Tue, 23 Apr 2019 10:31:51 +0000 (+0100) Subject: Add SyncResponse.stream X-Git-Tag: 0.2.0^2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c9b9ea07b6ba98eb32bbe01b2ad5c4335f6f3fe1;p=thirdparty%2Fhttpx.git Add SyncResponse.stream --- diff --git a/httpcore/sync.py b/httpcore/sync.py index ac2295c9..477edda3 100644 --- a/httpcore/sync.py +++ b/httpcore/sync.py @@ -30,6 +30,14 @@ class SyncResponse: def read(self) -> bytes: return asyncio_run(self._response.read()) + def stream(self) -> typing.Iterator[bytes]: + inner = self._response.stream() + while True: + try: + yield asyncio_run(inner.__anext__()) + except StopAsyncIteration as exc: + break + class SyncClient: def __init__(self, client: Client): diff --git a/tests/test_sync.py b/tests/test_sync.py index 7768cbc1..372bb920 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -36,3 +36,24 @@ def test_post(server): with httpcore.SyncConnectionPool() as http: response = http.request("POST", "http://127.0.0.1:8000/", body=b"Hello, world!") assert response.status_code == 200 + + +@threadpool +def test_stream_response(server): + with httpcore.SyncConnectionPool() as http: + response = http.request("GET", "http://127.0.0.1:8000/", stream=True) + assert response.status_code == 200 + assert not hasattr(response, "body") + body = response.read() + assert body == b"Hello, world!" + + +@threadpool +def test_stream_iterator(server): + with httpcore.SyncConnectionPool() as http: + response = http.request("GET", "http://127.0.0.1:8000/", stream=True) + assert response.status_code == 200 + body = b'' + for chunk in response.stream(): + body += chunk + assert body == b"Hello, world!"