]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Stricter enforcement of either 'with httpx.Client() as client' or 'client = httpx...
authorTom Christie <tom@tomchristie.com>
Fri, 13 Aug 2021 14:17:15 +0000 (15:17 +0100)
committerGitHub <noreply@github.com>
Fri, 13 Aug 2021 14:17:15 +0000 (15:17 +0100)
httpx/_client.py
tests/client/test_async_client.py
tests/client/test_client.py

index 9fd96c499755fc87a143be906d9f52074dbf4aa1..212222a2f6c2fdaff4c2700d3b933aa0a3e16dec 100644 (file)
@@ -1232,6 +1232,13 @@ class Client(BaseClient):
                     transport.close()
 
     def __enter__(self: T) -> T:
+        if self._state != ClientState.UNOPENED:
+            msg = {
+                ClientState.OPENED: "Cannot open a client instance more than once.",
+                ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",
+            }[self._state]
+            raise RuntimeError(msg)
+
         self._state = ClientState.OPENED
 
         self._transport.__enter__()
@@ -1941,6 +1948,13 @@ class AsyncClient(BaseClient):
                     await proxy.aclose()
 
     async def __aenter__(self: U) -> U:
+        if self._state != ClientState.UNOPENED:
+            msg = {
+                ClientState.OPENED: "Cannot open a client instance more than once.",
+                ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",
+            }[self._state]
+            raise RuntimeError(msg)
+
         self._state = ClientState.OPENED
 
         await self._transport.__aenter__()
index 0f83eddd7ffd78daaccada9008d3de687ac8bb2c..1761287454eda71da388f4cc7512e2ee874c33ad 100644 (file)
@@ -265,9 +265,15 @@ async def test_client_closed_state_using_implicit_open():
     await client.aclose()
 
     assert client.is_closed
+    # Once we're close we cannot make any more requests.
     with pytest.raises(RuntimeError):
         await client.get("http://example.com")
 
+    # Once we're closed we cannot reopen the client.
+    with pytest.raises(RuntimeError):
+        async with client:
+            pass  # pragma: nocover
+
 
 @pytest.mark.usefixtures("async_environment")
 async def test_client_closed_state_using_with_block():
index 01d0de828403d28b5a539443716c8e47609205e0..783d6d41f035678faa0175c48900c3ed7b081ac8 100644 (file)
@@ -305,9 +305,16 @@ def test_client_closed_state_using_implicit_open():
     client.close()
 
     assert client.is_closed
+
+    # Once we're close we cannot make any more requests.
     with pytest.raises(RuntimeError):
         client.get("http://example.com")
 
+    # Once we're closed we cannot reopen the client.
+    with pytest.raises(RuntimeError):
+        with client:
+            pass  # pragma: nocover
+
 
 def test_client_closed_state_using_with_block():
     with httpx.Client(transport=httpx.MockTransport(hello_world)) as client: