Skip to content

Commit 82885e4

Browse files
authored
Refactor connection creation and exception handling
Updated the connection creation method to use a lambda for better testability and changed exception handling from TimeoutError to OSError.
1 parent 5e0b9f3 commit 82885e4

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

Lib/http/client.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -887,9 +887,12 @@ def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
887887

888888
self._validate_host(self.host)
889889

890-
# This is stored as an instance variable to allow unit
891-
# tests to replace it with a suitable mockup
892-
self._create_connection = socket.create_connection
890+
# Callable used to open sockets. Kept on the instance so tests
891+
# can replace it; use a thin wrapper so the real
892+
# `socket.create_connection` is invoked at `connect()` time.
893+
# This avoids permanently capturing a patched factory at
894+
# construction time.
895+
self._create_connection = (lambda *a, **kw: socket.create_connection(*a, **kw))
893896

894897
def set_tunnel(self, host, port=None, headers=None):
895898
"""Set up host and port for HTTP CONNECT tunnelling.
@@ -1341,7 +1344,7 @@ def request(self, method, url, body=None, headers={}, *,
13411344
"""Send a complete request to the server."""
13421345
try:
13431346
self._send_request(method, url, body, headers, encode_chunked)
1344-
except TimeoutError:
1347+
except OSError:
13451348
# If the transmission fails (e.g. timeout), close the connection
13461349
# to reset the state machine to _CS_IDLE
13471350
self.close()

0 commit comments

Comments
 (0)