Andrew Geissler | 615f2f1 | 2022-07-15 14:00:58 -0500 | [diff] [blame] | 1 | Upstream-Status: Pending |
| 2 | Signed-off-by: Ross Burton <ross.burton@arm.com> |
| 3 | |
| 4 | From 8103b90148e8768456c3ab707de105d63d9d5b20 Mon Sep 17 00:00:00 2001 |
| 5 | From: Ross Burton <ross.burton@arm.com> |
| 6 | Date: Fri, 17 Jun 2022 11:53:59 +0100 |
| 7 | Subject: [PATCH] Mitigate the race condition in testSockName |
| 8 | |
| 9 | find_unused_port() has an inherent race condition, but we can't use |
| 10 | bind_port() as that uses .getsockname() which this test is exercising. |
| 11 | |
| 12 | Try binding to unused ports a few times before failing. |
| 13 | --- |
| 14 | Lib/test/test_socket.py | 15 +++++++++++++-- |
| 15 | 1 file changed, 13 insertions(+), 2 deletions(-) |
| 16 | |
| 17 | diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py |
| 18 | index c981903824..b1630d18b6 100644 |
| 19 | --- a/Lib/test/test_socket.py |
| 20 | +++ b/Lib/test/test_socket.py |
| 21 | @@ -1390,10 +1390,21 @@ def testStringToIPv6(self): |
| 22 | |
| 23 | def testSockName(self): |
| 24 | # Testing getsockname() |
| 25 | - port = socket_helper.find_unused_port() |
| 26 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 27 | self.addCleanup(sock.close) |
| 28 | - sock.bind(("0.0.0.0", port)) |
| 29 | + |
| 30 | + # Since find_unused_port() is inherently subject to race conditions, we |
| 31 | + # call it a couple times if necessary. |
| 32 | + for i in itertools.count(): |
| 33 | + port = socket_helper.find_unused_port() |
| 34 | + try: |
| 35 | + sock.bind(("0.0.0.0", port)) |
| 36 | + except OSError as e: |
| 37 | + if e.errno != errno.EADDRINUSE or i == 5: |
| 38 | + raise |
| 39 | + else: |
| 40 | + break |
| 41 | + |
| 42 | name = sock.getsockname() |
| 43 | # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate |
| 44 | # it reasonable to get the host's addr in addition to 0.0.0.0. |
| 45 | -- |
| 46 | 2.25.1 |
| 47 | |