Close responses when on cancellations occur during reading. (#2156)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Test case for clean stream closing on cancellations * Test case for clean stream closing on cancellations * Linting on tests * responses should close on any BaseException
authored by Tom Christie · committed by GitHub · parent 67c2970 · Browse files · 2 files·+46 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+46 added−6 removed
- tests:+40 added−0 removed
- other:+6 added−6 removed
Provenance
- Commit
3350d7e- Tree
5a2f4ab- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
67c2970
2 files changed+46 added−6 removed
modified:httpx/_client.py+6 added-6 removed
898 unmodified lines899 response.read()900 901 return response902 903- except Exception as exc:903+ except BaseException as exc:904 response.close()905 raise exc906 907 def _send_handling_auth(23 unmodified lines931 response.read()932 request = next_request933 history.append(response)934 935- except Exception as exc:935+ except BaseException as exc:936 response.close()937 raise exc938 finally:939 auth_flow.close()30 unmodified lines970 else:971 response.next_request = request972 return response973 974- except Exception as exc:974+ except BaseException as exc:975 response.close()976 raise exc977 978 def _send_single_request(self, request: Request) -> Response:624 unmodified lines1603 await response.aread()1604 1605 return response1606 1607- except Exception as exc: # pragma: no cover1607+ except BaseException as exc: # pragma: no cover1608 await response.aclose()1609 raise exc1610 1611 async def _send_handling_auth(23 unmodified lines1635 await response.aread()1636 request = next_request1637 history.append(response)1638 1639- except Exception as exc:1639+ except BaseException as exc:1640 await response.aclose()1641 raise exc1642 finally:1643 await auth_flow.aclose()31 unmodified lines1675 else:1676 response.next_request = request1677 return response1678 1679- except Exception as exc:1679+ except BaseException as exc:1680 await response.aclose()1681 raise exc1682 1683 async def _send_single_request(self, request: Request) -> Response:297 unmodified linesmodified:tests/client/test_async_client.py+40 added
323 unmodified lines324 assert response.text == "Hello, world!"325 326 327 @pytest.mark.usefixtures("async_environment")328+async def test_cancellation_during_stream():329+ """330+ If any BaseException is raised during streaming the response, then the331+ stream should be closed.332+333+ This includes:334+335+ * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.)336+ * `trio.Cancelled`337+ * `KeyboardInterrupt`338+ * `SystemExit`339+340+ See https://github.com/encode/httpx/issues/2139341+ """342+ stream_was_closed = False343+344+ def response_with_cancel_during_stream(request):345+ class CancelledStream(httpx.AsyncByteStream):346+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:347+ yield b"Hello"348+ raise KeyboardInterrupt()349+ yield b", world" # pragma: nocover350+351+ async def aclose(self) -> None:352+ nonlocal stream_was_closed353+ stream_was_closed = True354+355+ return httpx.Response(356+ 200, headers={"Content-Length": "12"}, stream=CancelledStream()357+ )358+359+ transport = httpx.MockTransport(response_with_cancel_during_stream)360+361+ async with httpx.AsyncClient(transport=transport) as client:362+ with pytest.raises(KeyboardInterrupt):363+ await client.get("https://www.example.com")364+ assert stream_was_closed365+366+367+@pytest.mark.usefixtures("async_environment")368 async def test_server_extensions(server):369 url = server.url370 async with httpx.AsyncClient(http2=True) as client:371 response = await client.get(url)2 unmodified lines