Skip to content
Myr

Stricter enforcement of either 'with httpx.Client() as client' or 'client = httpx.Client()' lifespan styles. (#1800)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent 77193b2 · Browse files · 3 files+27 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+27 added−0 removed

  • tests:+13 added−0 removed
  • other:+14 added−0 removed

3 files+27 added−0 removed

modified:httpx/_client.py+14 added
1230 unmodified lines
1231 if transport is not None:1232 transport.close()12331234 def __enter__(self: T) -> T:1235 if self._state != ClientState.UNOPENED:1236 msg = {1237 ClientState.OPENED: "Cannot open a client instance more than once.",1238 ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",1239 }[self._state]1240 raise RuntimeError(msg)12411242 self._state = ClientState.OPENED12431244 self._transport.__enter__()1245 for transport in self._mounts.values():
701 unmodified lines
1947 if proxy is not None:1948 await proxy.aclose()19491950 async def __aenter__(self: U) -> U:1951 if self._state != ClientState.UNOPENED:1952 msg = {1953 ClientState.OPENED: "Cannot open a client instance more than once.",1954 ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",1955 }[self._state]1956 raise RuntimeError(msg)19571958 self._state = ClientState.OPENED19591960 await self._transport.__aenter__()1961 for proxy in self._mounts.values():
47 unmodified lines
modified:tests/client/test_async_client.py+6 added
263 unmodified lines
264 assert not client.is_closed265 await client.aclose()266267 assert client.is_closed268 # Once we're close we cannot make any more requests.269 with pytest.raises(RuntimeError):270 await client.get("http://example.com")271272 # Once we're closed we cannot reopen the client.273 with pytest.raises(RuntimeError):274 async with client:275 pass # pragma: nocover276277278@pytest.mark.usefixtures("async_environment")279async def test_client_closed_state_using_with_block():280 async with httpx.AsyncClient(transport=httpx.MockTransport(hello_world)) as client:281 assert not client.is_closed
60 unmodified lines
modified:tests/client/test_client.py+7 added
303 unmodified lines
304 assert not client.is_closed305 client.close()306307 assert client.is_closed308309 # Once we're close we cannot make any more requests.310 with pytest.raises(RuntimeError):311 client.get("http://example.com")312313 # Once we're closed we cannot reopen the client.314 with pytest.raises(RuntimeError):315 with client:316 pass # pragma: nocover317318319def test_client_closed_state_using_with_block():320 with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:321 assert not client.is_closed322 client.get("http://example.com")
78 unmodified lines