Fix issue #17675: make socket repr() provide local and remote addresses (if any).

This commit is contained in:
Giampaolo Rodola' 2013-04-10 15:49:47 +02:00
parent 7d36e4f074
commit 50331cbf08
3 changed files with 40 additions and 9 deletions

View File

@ -103,13 +103,32 @@ class socket(_socket.socket):
self.close() self.close()
def __repr__(self): def __repr__(self):
"""Wrap __repr__() to reveal the real class name.""" """Wrap __repr__() to reveal the real class name and socket
s = _socket.socket.__repr__(self) address(es).
if s.startswith("<socket object"): """
s = "<%s.%s%s%s" % (self.__class__.__module__, closed = getattr(self, '_closed', False)
self.__class__.__name__, s = "<%s.%s%s fd=%i, family=%i, type=%i, proto=%i" \
getattr(self, '_closed', False) and " [closed] " or "", % (self.__class__.__module__,
s[7:]) self.__class__.__name__,
" [closed]" if closed else "",
self.fileno(),
self.family,
self.type,
self.proto)
if not closed:
try:
laddr = self.getsockname()
if laddr:
s += ", laddr=%s" % str(laddr)
except error:
pass
try:
raddr = self.getpeername()
if raddr:
s += ", raddr=%s" % str(raddr)
except error:
pass
s += '>'
return s return s
def __getstate__(self): def __getstate__(self):

View File

@ -652,8 +652,17 @@ class GeneralModuleTests(unittest.TestCase):
def test_repr(self): def test_repr(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(s.close) with s:
self.assertTrue(repr(s).startswith("<socket.socket object")) self.assertIn('fd=%i' % s.fileno(), repr(s))
self.assertIn('family=%i' % socket.AF_INET, repr(s))
self.assertIn('type=%i' % socket.SOCK_STREAM, repr(s))
self.assertIn('proto=0', repr(s))
self.assertIn('laddr', repr(s))
self.assertNotIn('raddr', repr(s))
s.bind(('127.0.0.1', 0))
self.assertIn(str(s.getsockname()), repr(s))
self.assertIn('[closed]', repr(s))
self.assertNotIn('laddr', repr(s))
def test_weakref(self): def test_weakref(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

View File

@ -32,6 +32,9 @@ Core and Builtins
Library Library
------- -------
- Issue #17675: socket repr() provides local and remote addresses (if any).
Patch by Giampaolo Rodola'
- Issue #17093: Make the ABCs in importlib.abc provide default values or raise - Issue #17093: Make the ABCs in importlib.abc provide default values or raise
reasonable exceptions for their methods to make them more amenable to super() reasonable exceptions for their methods to make them more amenable to super()
calls. calls.