Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions Lib/http/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1012,19 +1012,35 @@ def connect(self):
if self._tunnel_host:
self._tunnel()

def close(self):
"""Close the connection to the HTTP server."""
def close(self, shutdown=False):
Copy link
Contributor

@Mr-Sunglasses Mr-Sunglasses Mar 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should add it in the Doc/library/socket.rst also, about the shutdown.

Ref.

.. method:: socket.close()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, shouldn't take too long

Copy link
Contributor Author

@sharktide sharktide Mar 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Mr-Sunglasses Finally ready for review/ Added/updated docs for the close method of HTTPConnection class as well as added back a modifed docstring in http/client.py!

self.__state = _CS_IDLE
try:
sock = self.sock
if sock:
self.sock = None
sock.close() # close it manually... there may be other refs
if shutdown:
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError as e:
print(f"Socket shutdown error: {e}", file=sys.stderr)
except Exception as e:
print(f"Unexpected error during socket shutdown: {e}", file=sys.stderr)
try:
sock.close()
except OSError as e:
print(f"Socket close error: {e}", file=sys.stderr)
except Exception as e:
print(f"Unexpected error during socket close: {e}", file=sys.stderr)
finally:
response = self.__response
if response:
self.__response = None
response.close()
try:
response.close()
except OSError as e:
print(f"Response close error: {e}", file=sys.stderr)
except Exception as e:
print(f"Unexpected error during response close: {e}", file=sys.stderr)

def send(self, data):
"""Send 'data' to the server.
Expand Down
74 changes: 74 additions & 0 deletions Lib/test/test_httplib.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import enum
import errno
from http import client, HTTPStatus
from http.client import HTTPConnection
import io
from io import StringIO
import itertools
import os
import array
import re
import socket
import sys
import threading

import unittest
Expand All @@ -16,6 +19,7 @@
from test import support
from test.support import os_helper
from test.support import socket_helper
from unittest.mock import MagicMock

support.requires_working_socket(module=True)

Expand Down Expand Up @@ -2525,5 +2529,75 @@ def _create_connection(address, timeout=None, source_address=None):
self.assertTrue(sock.file_closed)



class TestHTTPSocketShutdown(TestCase):
def test_close_with_shutdown(self):
mock_socket = MagicMock()
mock_socket.close = MagicMock()
mock_socket.shutdown = MagicMock()
connection = HTTPConnection('www.example.com')
connection.sock = mock_socket
original_stderr = sys.stderr
sys.stderr = StringIO()
try:
connection.close(shutdown=True)
mock_socket.shutdown.assert_called_once_with(2) # SHUT_RDWR
mock_socket.close.assert_called_once()
error_output = sys.stderr.getvalue()
self.assertEqual(error_output, "")
finally:
sys.stderr = original_stderr

def test_close_without_shutdown(self):
mock_socket = MagicMock()
mock_socket.close = MagicMock()
mock_socket.shutdown = MagicMock()
connection = HTTPConnection('www.example.com')
connection.sock = mock_socket
original_stderr = sys.stderr
sys.stderr = StringIO()
try:
connection.close(shutdown=False)
mock_socket.shutdown.assert_not_called()
mock_socket.close.assert_called_once()
error_output = sys.stderr.getvalue()
self.assertEqual(error_output, "")
finally:
sys.stderr = original_stderr

def test_close_shutdown_error(self):
mock_socket = MagicMock()
mock_socket.close = MagicMock()
mock_socket.shutdown = MagicMock(side_effect=OSError("Shutdown error"))
connection = HTTPConnection('www.example.com')
connection.sock = mock_socket
original_stderr = sys.stderr
sys.stderr = StringIO()
try:
connection.close(shutdown=True)
mock_socket.shutdown.assert_called_once_with(2) # SHUT_RDWR
mock_socket.close.assert_called_once()
error_output = sys.stderr.getvalue()
self.assertIn("Socket shutdown error: Shutdown error", error_output)
finally:
sys.stderr = original_stderr

def test_close_unexpected_error(self):
mock_socket = MagicMock()
mock_socket.close = MagicMock()
mock_socket.shutdown = MagicMock(side_effect=Exception("Unexpected error"))
connection = HTTPConnection('www.example.com')
connection.sock = mock_socket
original_stderr = sys.stderr
sys.stderr = StringIO()
try:
connection.close(shutdown=True)
mock_socket.shutdown.assert_called_once_with(2) # SHUT_RDWR
mock_socket.close.assert_called_once()
error_output = sys.stderr.getvalue()
self.assertIn("Unexpected error during socket shutdown: Unexpected error", error_output)
finally:
sys.stderr = original_stderr

if __name__ == '__main__':
unittest.main(verbosity=2)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Issue: :gh:`130902`


Modifies the :meth:`http.client.HTTPConnection.close` of :class:`http.client.HTTPConnection` to include an optional socket ``shutdown``, improving functionality with error handling.
Loading