Skip to content

Commit

Permalink
Warn a ResourceWarning when AsyncClient hasn't been closed (encode#871)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdeler committed Aug 18, 2020
1 parent cb620e6 commit 256f3c8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions httpx/_client.py
@@ -1,5 +1,6 @@
import functools
import typing
import warnings
from types import TracebackType

import httpcore
Expand Down Expand Up @@ -1160,6 +1161,7 @@ def __init__(
for key, proxy in proxy_map.items()
}
self._proxies = dict(sorted(self._proxies.items()))
self._is_closed = False

def _init_transport(
self,
Expand Down Expand Up @@ -1627,6 +1629,7 @@ async def aclose(self) -> None:
for proxy in self._proxies.values():
if proxy is not None:
await proxy.aclose()
self._is_closed = True

async def __aenter__(self) -> "AsyncClient":
return self
Expand All @@ -1639,6 +1642,10 @@ async def __aexit__(
) -> None:
await self.aclose()

def __del__(self) -> None:
if not self._is_closed:
warnings.warn(f"Unclosed {self!r}", ResourceWarning)


class StreamContextManager:
def __init__(
Expand Down
22 changes: 22 additions & 0 deletions tests/client/test_async_client.py
Expand Up @@ -166,3 +166,25 @@ async def test_100_continue(server):

assert response.status_code == 200
assert response.content == data


@pytest.mark.usefixtures("async_environment")
async def test_unclosed_client_caused_warning():
with pytest.warns(ResourceWarning):
client = httpx.AsyncClient()
del client

with pytest.warns(None) as wb:

async with httpx.AsyncClient() as client: # noqa: F841
pass

assert len(wb.list) == 0


@pytest.mark.usefixtures("async_environment")
async def test_that_client_is_closed_after_with_block():
async with httpx.AsyncClient() as client:
pass

assert client._is_closed

0 comments on commit 256f3c8

Please sign in to comment.