Skip to content

Commit

Permalink
Fix patching of is_connection_dropped from urllib3
Browse files Browse the repository at this point in the history
With old patching method, urllib3 never detected TCP connections that
were closed by the server side. For example, persistent HTTP connection
that were closed by the server (e.g., due to timeout) were not
recognized as closed. Any following requests that attempted to reuse
the same, closed connection caused the following failure:

    urllib3.exceptions.ProtocolError: ('Connection aborted.',
       RemoteDisconnected('Remote end closed connection without response'
    ))

Fixes: kevin1024#468
  • Loading branch information
peterisr committed Aug 31, 2021
1 parent e68aa84 commit 572dcbd
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion vcr/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,24 @@ def patched_new_conn(pool):

return patched_new_conn

def _patched_is_connection_dropped(self, cpool):
from .stubs import VCRFakeSocket
is_connection_dropped = cpool.is_connection_dropped

@functools.wraps(is_connection_dropped)
def patched_is_connection_dropped(conn):
sock = getattr(conn, "sock", None)
if isinstance(sock, VCRFakeSocket):
# Handle VCRFakeSocket instances here to avoid bad select() calls on Windows
# See https://github.com/kevin1024/vcrpy/issues/116
return False

# Let actual is_connection_dropped function handle real sockets.
# This allows urllib3 to detect closed TCP connections.
return is_connection_dropped(conn)

return patched_is_connection_dropped

def _urllib3(self):
try:
import urllib3.connectionpool as cpool
Expand Down Expand Up @@ -349,7 +367,7 @@ def _urllib3_patchers(self, cpool, stubs):
(cpool, "VerifiedHTTPSConnection", stubs.VCRRequestsHTTPSConnection),
(cpool, "HTTPConnection", stubs.VCRRequestsHTTPConnection),
(cpool, "HTTPSConnection", stubs.VCRRequestsHTTPSConnection),
(cpool, "is_connection_dropped", mock.Mock(return_value=False)), # Needed on Windows only
(cpool, "is_connection_dropped", self._patched_is_connection_dropped(cpool)),
(cpool.HTTPConnectionPool, "ConnectionCls", stubs.VCRRequestsHTTPConnection),
(cpool.HTTPSConnectionPool, "ConnectionCls", stubs.VCRRequestsHTTPSConnection),
)
Expand Down

0 comments on commit 572dcbd

Please sign in to comment.