Skip to content

Commit cee8a80

Browse files
committed
Let OS pick an available port when running TestInstalledAppFlow
tests.unit.test_flow.TestInstalledAppFlow attempts to create a new server at the specified host:port. New server creation occasionally results in 'address already in use' because the socket will be unavailable for a period of time after the socket is closed, resulting in flaky test failures. Work around this in the tests by letting the OS pick an available port each time. Change how Let OS select an available port
1 parent 0b962ed commit cee8a80

File tree

1 file changed

+4
-14
lines changed

1 file changed

+4
-14
lines changed

tests/unit/test_flow.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -251,25 +251,15 @@ def instance(self):
251251
CLIENT_SECRETS_INFO, scopes=self.SCOPES
252252
)
253253

254-
def is_port_in_use(self, port, host="localhost"):
255-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
256-
return s.connect_ex((host, port)) == 0
257-
258254
@pytest.fixture
259255
def port(self):
260256
# Creating a new server at the same port will result in
261257
# a 'Address already in use' error for a brief
262258
# period of time after the socket has been closed.
263-
# Work around this in the tests by choosing a different port each time.
264-
# https://stackoverflow.com/questions/6380057/python-binding-socket-address-already-in-use
265-
random_port = -1
266-
for _ in range(10):
267-
random_port = random.randrange(60400, 60900)
268-
if not self.is_port_in_use(random_port):
269-
break
270-
else:
271-
raise OSError("Could not find a free port")
272-
yield random_port
259+
# Work around this in the tests by letting the OS pick an available port each time.
260+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
261+
s.bind(("localhost", 0))
262+
return s.getsockname()[1]
273263

274264
@pytest.fixture
275265
def socket(self, port):

0 commit comments

Comments
 (0)