Skip to content
Myr

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

3 files+70 added−58 removed

modified:httpx/_client.py+35 added-23 removed
1import datetime2import enum3import functools4import typing5import warnings6from types import TracebackType
64 unmodified lines
71 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]72)737475class ClientState(enum.Enum):76 UNOPENED = 177 OPENED = 278 CLOSED = 3798081class BaseClient:82 def __init__(83 self,84 *,
22 unmodified lines
107 "response": list(event_hooks.get("response", [])),108 }109 self._trust_env = trust_env110 self._netrc = NetRCInfo()104 self._is_closed = True111 self._state = ClientState.UNOPENED112113 @property114 def is_closed(self) -> bool:115 """116 Check if the client being closed117 """111 return self._is_closed118 return self._state == ClientState.CLOSED119120 @property121 def trust_env(self) -> bool:122 return self._trust_env
633 unmodified lines
756 See also: [Request instances][0]757758 [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.")762763 self._state = ClientState.OPENED764 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)765766 auth = self._build_request_auth(request, auth)767
344 unmodified lines
1112 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.CLOSED11181119 self._transport.close()1120 for proxy in self._proxies.values():1121 if proxy is not None:1122 proxy.close()11231124 def __enter__(self: T) -> T:1125 self._state = ClientState.OPENED11261127 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 self11321133 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.CLOSED11401132 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)11451146 def __del__(self) -> None:1147 self.close()1148
253 unmodified lines
1402 See also: [Request instances][0]14031404 [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.")14081409 self._state = ClientState.OPENED1410 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)14111412 auth = self._build_request_auth(request, auth)1413
346 unmodified lines
1760 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.CLOSED17661767 await self._transport.aclose()1768 for proxy in self._proxies.values():1769 if proxy is not None:1770 await proxy.aclose()17711772 async def __aenter__(self: U) -> U:1773 self._state = ClientState.OPENED17741775 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 self17801781 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.CLOSED17881789 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)17931794 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 lines
modified:tests/client/test_async_client.py+19 added-22 removed
2 unmodified lines
3import httpcore4import pytest56import httpx7from tests.utils import MockTransport8910@pytest.mark.usefixtures("async_environment")11async def test_get(server):
196 unmodified lines
208 "transport.__aexit__",209 ]210211211@pytest.mark.usefixtures("async_environment")212async def test_that_async_client_is_closed_by_default():213 client = httpx.AsyncClient()212def hello_world(request):213 return httpx.Response(200, text="Hello, world!")214215 assert client.is_closed215217216@pytest.mark.usefixtures("async_environment")219async def test_that_send_cause_async_client_to_be_not_closed():220 client = httpx.AsyncClient()217async def test_client_closed_state_using_implicit_open():218 client = httpx.AsyncClient(transport=MockTransport(hello_world))219220 assert not client.is_closed221 await client.get("http://example.com")222223 assert not client.is_closed225224 await client.aclose()225226 assert client.is_closed227 with pytest.raises(RuntimeError):228 await client.get("http://example.com")229230231@pytest.mark.usefixtures("async_environment")230async def test_that_async_client_is_not_closed_in_with_block():231 async with httpx.AsyncClient() as client:232async 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")236234235@pytest.mark.usefixtures("async_environment")236async def test_that_async_client_is_closed_after_with_block():237 async with httpx.AsyncClient() as client:238 pass239237 assert client.is_closed238 with pytest.raises(RuntimeError):239 await client.get("http://example.com")240241242@pytest.mark.usefixtures("async_environment")244async def test_that_async_client_caused_warning_when_being_deleted():245 async_client = httpx.AsyncClient()246247 await async_client.get("http://example.com")248243async 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 client
modified:tests/client/test_client.py+16 added-13 removed
2 unmodified lines
3import httpcore4import pytest56import httpx7from tests.utils import MockTransport8910def test_get(server):11 url = server.url
235 unmodified lines
247 "transport.__exit__",248 ]249250250def test_that_client_is_closed_by_default():251 client = httpx.Client()251def hello_world(request):252 return httpx.Response(200, text="Hello, world!")253253 assert client.is_closed254255def test_client_closed_state_using_implicit_open():256 client = httpx.Client(transport=MockTransport(hello_world))257256def test_that_send_cause_client_to_be_not_closed():257 client = httpx.Client()258258 assert not client.is_closed259 client.get("http://example.com")260261 assert not client.is_closed262 client.close()263264 assert client.is_closed265 with pytest.raises(RuntimeError):266 client.get("http://example.com")267264def test_that_client_is_not_closed_in_with_block():265 with httpx.Client() as client:268269def 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")273268269def test_that_client_is_closed_after_with_block():270 with httpx.Client() as client:271 pass272274 assert client.is_closed275 with pytest.raises(RuntimeError):276 client.get("http://example.com")