Tighten client closed-state behaviour (#1346)
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 a3eb0f9 · Browse files · 3 files·+70 added−58 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
Diff stats
3 files+70 added−58 removed
- tests:+35 added−35 removed
- other:+35 added−23 removed
Provenance
- Commit
2a2bbe5- Tree
d161884- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
a3eb0f9
3 files changed+70 added−58 removed
modified:httpx/_client.py+35 added-23 removed
1 import datetime2+import enum3 import functools4 import typing5 import warnings6 from types import TracebackType64 unmodified lines71 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]72 )73 74 75+class ClientState(enum.Enum):76+ UNOPENED = 177+ OPENED = 278+ CLOSED = 379+80+81 class BaseClient:82 def __init__(83 self,84 *,22 unmodified lines107 "response": list(event_hooks.get("response", [])),108 }109 self._trust_env = trust_env110 self._netrc = NetRCInfo()104- self._is_closed = True111+ self._state = ClientState.UNOPENED112 113 @property114 def is_closed(self) -> bool:115 """116 Check if the client being closed117 """111- return self._is_closed118+ return self._state == ClientState.CLOSED119 120 @property121 def trust_env(self) -> bool:122 return self._trust_env633 unmodified lines756 See also: [Request instances][0]757 758 [0]: /advanced/#request-instances759 """753- self._is_closed = False760+ if self._state == ClientState.CLOSED:761+ raise RuntimeError("Cannot send a request, as the client has been closed.")762 763+ self._state = ClientState.OPENED764 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)765 766 auth = self._build_request_auth(request, auth)767 344 unmodified lines1112 def close(self) -> None:1113 """1114 Close transport and proxies.1115 """1107- if not self.is_closed:1108- self._is_closed = True1116+ if self._state != ClientState.CLOSED:1117+ self._state = ClientState.CLOSED1118 1119 self._transport.close()1120 for proxy in self._proxies.values():1121 if proxy is not None:1122 proxy.close()1123 1124 def __enter__(self: T) -> T:1125+ self._state = ClientState.OPENED1126+1127 self._transport.__enter__()1128 for proxy in self._proxies.values():1129 if proxy is not None:1130 proxy.__enter__()1120- self._is_closed = False1131 return self1132 1133 def __exit__(1134 self,1135 exc_type: typing.Type[BaseException] = None,1136 exc_value: BaseException = None,1137 traceback: TracebackType = None,1138 ) -> None:1129- if not self.is_closed:1130- self._is_closed = True1139+ self._state = ClientState.CLOSED1140 1132- self._transport.__exit__(exc_type, exc_value, traceback)1133- for proxy in self._proxies.values():1134- if proxy is not None:1135- proxy.__exit__(exc_type, exc_value, traceback)1141+ self._transport.__exit__(exc_type, exc_value, traceback)1142+ for proxy in self._proxies.values():1143+ if proxy is not None:1144+ proxy.__exit__(exc_type, exc_value, traceback)1145 1146 def __del__(self) -> None:1147 self.close()1148 253 unmodified lines1402 See also: [Request instances][0]1403 1404 [0]: /advanced/#request-instances1405 """1397- self._is_closed = False1406+ if self._state == ClientState.CLOSED:1407+ raise RuntimeError("Cannot send a request, as the client has been closed.")1408 1409+ self._state = ClientState.OPENED1410 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)1411 1412 auth = self._build_request_auth(request, auth)1413 346 unmodified lines1760 async def aclose(self) -> None:1761 """1762 Close transport and proxies.1763 """1753- if not self.is_closed:1754- self._is_closed = True1764+ if self._state != ClientState.CLOSED:1765+ self._state = ClientState.CLOSED1766 1767 await self._transport.aclose()1768 for proxy in self._proxies.values():1769 if proxy is not None:1770 await proxy.aclose()1771 1772 async def __aenter__(self: U) -> U:1773+ self._state = ClientState.OPENED1774+1775 await self._transport.__aenter__()1776 for proxy in self._proxies.values():1777 if proxy is not None:1778 await proxy.__aenter__()1766- self._is_closed = False1779 return self1780 1781 async def __aexit__(1782 self,1783 exc_type: typing.Type[BaseException] = None,1784 exc_value: BaseException = None,1785 traceback: TracebackType = None,1786 ) -> None:1775- if not self.is_closed:1776- self._is_closed = True1777- await self._transport.__aexit__(exc_type, exc_value, traceback)1778- for proxy in self._proxies.values():1779- if proxy is not None:1780- await proxy.__aexit__(exc_type, exc_value, traceback)1787+ self._state = ClientState.CLOSED1788 1789+ await self._transport.__aexit__(exc_type, exc_value, traceback)1790+ for proxy in self._proxies.values():1791+ if proxy is not None:1792+ await proxy.__aexit__(exc_type, exc_value, traceback)1793+1794 def __del__(self) -> None:1783- if not self.is_closed:1795+ if self._state == ClientState.OPENED:1796 warnings.warn(1797 f"Unclosed {self!r}. "1798 "See https://www.python-httpx.org/async/#opening-and-closing-clients "1799 "for details."62 unmodified linesmodified:tests/client/test_async_client.py+19 added-22 removed
2 unmodified lines3 import httpcore4 import pytest5 6 import httpx7+from tests.utils import MockTransport8 9 10 @pytest.mark.usefixtures("async_environment")11 async def test_get(server):196 unmodified lines208 "transport.__aexit__",209 ]210 211 211-@pytest.mark.usefixtures("async_environment")212-async def test_that_async_client_is_closed_by_default():213- client = httpx.AsyncClient()212+def hello_world(request):213+ return httpx.Response(200, text="Hello, world!")214 215- assert client.is_closed215 217-216 @pytest.mark.usefixtures("async_environment")219-async def test_that_send_cause_async_client_to_be_not_closed():220- client = httpx.AsyncClient()217+async def test_client_closed_state_using_implicit_open():218+ client = httpx.AsyncClient(transport=MockTransport(hello_world))219 220+ assert not client.is_closed221 await client.get("http://example.com")222 223 assert not client.is_closed225-224 await client.aclose()225 226+ assert client.is_closed227+ with pytest.raises(RuntimeError):228+ await client.get("http://example.com")229 230+231 @pytest.mark.usefixtures("async_environment")230-async def test_that_async_client_is_not_closed_in_with_block():231- async with httpx.AsyncClient() as client:232+async def test_client_closed_state_using_with_block():233+ async with httpx.AsyncClient(transport=MockTransport(hello_world)) as client:234 assert not client.is_closed235+ await client.get("http://example.com")236 234-235-@pytest.mark.usefixtures("async_environment")236-async def test_that_async_client_is_closed_after_with_block():237- async with httpx.AsyncClient() as client:238- pass239-237 assert client.is_closed238+ with pytest.raises(RuntimeError):239+ await client.get("http://example.com")240 241 242 @pytest.mark.usefixtures("async_environment")244-async def test_that_async_client_caused_warning_when_being_deleted():245- async_client = httpx.AsyncClient()246-247- await async_client.get("http://example.com")248-243+async def test_deleting_unclosed_async_client_causes_warning():244+ client = httpx.AsyncClient(transport=MockTransport(hello_world))245+ await client.get("http://example.com")246 with pytest.warns(UserWarning):250- del async_client247+ del clientmodified:tests/client/test_client.py+16 added-13 removed
2 unmodified lines3 import httpcore4 import pytest5 6 import httpx7+from tests.utils import MockTransport8 9 10 def test_get(server):11 url = server.url235 unmodified lines247 "transport.__exit__",248 ]249 250 250-def test_that_client_is_closed_by_default():251- client = httpx.Client()251+def hello_world(request):252+ return httpx.Response(200, text="Hello, world!")253 253- assert client.is_closed254 255+def test_client_closed_state_using_implicit_open():256+ client = httpx.Client(transport=MockTransport(hello_world))257 256-def test_that_send_cause_client_to_be_not_closed():257- client = httpx.Client()258-258+ assert not client.is_closed259 client.get("http://example.com")260 261 assert not client.is_closed262+ client.close()263 264+ assert client.is_closed265+ with pytest.raises(RuntimeError):266+ client.get("http://example.com")267 264-def test_that_client_is_not_closed_in_with_block():265- with httpx.Client() as client:268+269+def test_client_closed_state_using_with_block():270+ with httpx.Client(transport=MockTransport(hello_world)) as client:271 assert not client.is_closed272+ client.get("http://example.com")273 268-269-def test_that_client_is_closed_after_with_block():270- with httpx.Client() as client:271- pass272-274 assert client.is_closed275+ with pytest.raises(RuntimeError):276+ client.get("http://example.com")