Issue warning on unclosed `AsyncClient`. (#1197)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Made Client and AsyncClient checking for being closed in __del__ (#871) * Changed the AsyncClient closing warning type from ResourceWarning (which is too quiet) to UserWarning (#871) * Fixed tests and client's __exit__ and __aexit__ after the difficult merge (#871) * Update test_proxies.py * Update test_proxies.py
authored by cdeler · committed by GitHub · parent ec06ba2 · Browse files · 4 files·+125 added−18 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: Tom Christie <tom@tomchristie.com>
Diff stats
4 files+125 added−18 removed
- tests:+72 added−2 removed
- other:+53 added−16 removed
Provenance
- Commit
def9f1c- Tree
aeda101- Author
cdeler <serj.krotov@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ec06ba2
4 files changed+125 added−18 removed
modified:httpx/_client.py+53 added-16 removed
1 import functools2 import typing3+import warnings4 from types import TracebackType5 6 import httpcore7 71 unmodified lines79 self._timeout = Timeout(timeout)80 self.max_redirects = max_redirects81 self._trust_env = trust_env82 self._netrc = NetRCInfo()83+ self._is_closed = True84 85 @property86+ def is_closed(self) -> bool:87+ """88+ Check if the client being closed89+ """90+ return self._is_closed91+92+ @property93 def trust_env(self) -> bool:94 return self._trust_env95 96 def _enforce_trailing_slash(self, url: URL) -> URL:607 unmodified lines704 See also: [Request instances][0]705 706 [0]: /advanced/#request-instances707 """708+ self._is_closed = False709+710 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)711 712 auth = self._build_request_auth(request, auth)713 325 unmodified lines1039 def close(self) -> None:1040 """1041 Close transport and proxies.1042 """1032- self._transport.close()1033- for proxy in self._proxies.values():1034- if proxy is not None:1035- proxy.close()1043+ if not self.is_closed:1044+ self._is_closed = True1045 1046+ self._transport.close()1047+ for proxy in self._proxies.values():1048+ if proxy is not None:1049+ proxy.close()1050+1051 def __enter__(self) -> "Client":1052 self._transport.__enter__()1053 for proxy in self._proxies.values():1054 if proxy is not None:1055 proxy.__enter__()1056+ self._is_closed = False1057 return self1058 1059 def __exit__(1060 self,1061 exc_type: typing.Type[BaseException] = None,1062 exc_value: BaseException = None,1063 traceback: TracebackType = None,1064 ) -> None:1050- self._transport.__exit__(exc_type, exc_value, traceback)1051- for proxy in self._proxies.values():1052- if proxy is not None:1053- proxy.__exit__(exc_type, exc_value, traceback)1065+ if not self.is_closed:1066+ self._is_closed = True1067 1068+ self._transport.__exit__(exc_type, exc_value, traceback)1069+ for proxy in self._proxies.values():1070+ if proxy is not None:1071+ proxy.__exit__(exc_type, exc_value, traceback)1072 1073+ def __del__(self) -> None:1074+ self.close()1075+1076+1077 class AsyncClient(BaseClient):1078 """1079 An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,1080 cookie persistence, etc.244 unmodified lines1325 See also: [Request instances][0]1326 1327 [0]: /advanced/#request-instances1328 """1329+ self._is_closed = False1330+1331 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)1332 1333 auth = self._build_request_auth(request, auth)1334 327 unmodified lines1662 async def aclose(self) -> None:1663 """1664 Close transport and proxies.1665 """1643- await self._transport.aclose()1644- for proxy in self._proxies.values():1645- if proxy is not None:1646- await proxy.aclose()1666+ if not self.is_closed:1667+ self._is_closed = True1668 1669+ await self._transport.aclose()1670+ for proxy in self._proxies.values():1671+ if proxy is not None:1672+ await proxy.aclose()1673+1674 async def __aenter__(self) -> "AsyncClient":1675 await self._transport.__aenter__()1676 for proxy in self._proxies.values():1677 if proxy is not None:1678 await proxy.__aenter__()1679+ self._is_closed = False1680 return self1681 1682 async def __aexit__(1683 self,1684 exc_type: typing.Type[BaseException] = None,1685 exc_value: BaseException = None,1686 traceback: TracebackType = None,1687 ) -> None:1688+ if not self.is_closed:1689+ self._is_closed = True1661- await self._transport.__aexit__(exc_type, exc_value, traceback)1662- for proxy in self._proxies.values():1663- if proxy is not None:1664- await proxy.__aexit__(exc_type, exc_value, traceback)1690+ await self._transport.__aexit__(exc_type, exc_value, traceback)1691+ for proxy in self._proxies.values():1692+ if proxy is not None:1693+ await proxy.__aexit__(exc_type, exc_value, traceback)1694 1695+ def __del__(self) -> None:1696+ if not self.is_closed:1697+ warnings.warn(1698+ f"Unclosed {self!r}. "1699+ "See https://www.python-httpx.org/async/#opening-and-closing-clients "1700+ "for details."1701+ )1702 1703+1704 class StreamContextManager:1705 def __init__(1706 self,1707 client: BaseClient,55 unmodified linesmodified:tests/client/test_async_client.py+42 added
204 unmodified lines205 "transport.__aenter__",206 "transport.aclose",207 "transport.__aexit__",208 ]209+210+211+@pytest.mark.usefixtures("async_environment")212+async def test_that_async_client_is_closed_by_default():213+ client = httpx.AsyncClient()214+215+ assert client.is_closed216+217+218+@pytest.mark.usefixtures("async_environment")219+async def test_that_send_cause_async_client_to_be_not_closed():220+ client = httpx.AsyncClient()221+222+ await client.get("http://example.com")223+224+ assert not client.is_closed225+226+ await client.aclose()227+228+229+@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+ assert not client.is_closed233+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+240+ assert client.is_closed241+242+243+@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+249+ with pytest.warns(UserWarning):250+ del async_clientmodified:tests/client/test_client.py+26 added
245 unmodified lines246 "transport.__enter__",247 "transport.close",248 "transport.__exit__",249 ]250+251+252+def test_that_client_is_closed_by_default():253+ client = httpx.Client()254+255+ assert client.is_closed256+257+258+def test_that_send_cause_client_to_be_not_closed():259+ client = httpx.Client()260+261+ client.get("http://example.com")262+263+ assert not client.is_closed264+265+266+def test_that_client_is_not_closed_in_with_block():267+ with httpx.Client() as client:268+ assert not client.is_closed269+270+271+def test_that_client_is_closed_after_with_block():272+ with httpx.Client() as client:273+ pass274+275+ assert client.is_closedmodified:tests/client/test_proxies.py+4 added-2 removed
121 unmodified lines122 123 @pytest.mark.asyncio124 async def test_async_proxy_close():125 try:126- client = httpx.AsyncClient(proxies={"all://": PROXY_URL})126+ client = httpx.AsyncClient(proxies={"https://": PROXY_URL})127+ await client.get("http://example.com")128 finally:129 await client.aclose()130 131 132 def test_sync_proxy_close():133 try:133- client = httpx.Client(proxies={"all://": PROXY_URL})134+ client = httpx.Client(proxies={"https://": PROXY_URL})135+ client.get("http://example.com")136 finally:137 client.close()138 139 131 unmodified lines