mirror of
https://github.com/python/cpython.git
synced 2025-10-17 12:18:23 +00:00
gh-95243: Mitigate the race condition in testSockName (#96173)
find_unused_port() has an inherent race condition, but we can't use bind_port() as that uses .getsockname() which this test is exercising. Try binding to unused ports a few times before failing. Signed-off-by: Ross Burton <ross.burton@arm.com>
This commit is contained in:
parent
e34c82abeb
commit
df11012697
2 changed files with 16 additions and 2 deletions
|
@ -1398,10 +1398,21 @@ class GeneralModuleTests(unittest.TestCase):
|
||||||
|
|
||||||
def testSockName(self):
|
def testSockName(self):
|
||||||
# Testing getsockname()
|
# Testing getsockname()
|
||||||
port = socket_helper.find_unused_port()
|
|
||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
self.addCleanup(sock.close)
|
self.addCleanup(sock.close)
|
||||||
sock.bind(("0.0.0.0", port))
|
|
||||||
|
# Since find_unused_port() is inherently subject to race conditions, we
|
||||||
|
# call it a couple times if necessary.
|
||||||
|
for i in itertools.count():
|
||||||
|
port = socket_helper.find_unused_port()
|
||||||
|
try:
|
||||||
|
sock.bind(("0.0.0.0", port))
|
||||||
|
except OSError as e:
|
||||||
|
if e.errno != errno.EADDRINUSE or i == 5:
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
name = sock.getsockname()
|
name = sock.getsockname()
|
||||||
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
|
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
|
||||||
# it reasonable to get the host's addr in addition to 0.0.0.0.
|
# it reasonable to get the host's addr in addition to 0.0.0.0.
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
Mitigate the inherent race condition from using find_unused_port() in
|
||||||
|
testSockName() by trying to find an unused port a few times before failing.
|
||||||
|
Patch by Ross Burton.
|
Loading…
Add table
Add a link
Reference in a new issue