Skip to content

Commit 6060d65

Browse files
authored
fix: Let OS select an available port when running TestInstalledAppFlow (#407)
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. Fixes #381
1 parent 0b962ed commit 6060d65

File tree

1 file changed

+4
-15
lines changed

1 file changed

+4
-15
lines changed

tests/unit/test_flow.py

+4-15
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import json
1919
import os
2020
import re
21-
import random
2221
import socket
2322

2423
import mock
@@ -251,25 +250,15 @@ def instance(self):
251250
CLIENT_SECRETS_INFO, scopes=self.SCOPES
252251
)
253252

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-
258253
@pytest.fixture
259254
def port(self):
260255
# Creating a new server at the same port will result in
261256
# a 'Address already in use' error for a brief
262257
# 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
258+
# Work around this in the tests by letting the OS pick an available port each time.
259+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
260+
s.bind(("localhost", 0))
261+
return s.getsockname()[1]
273262

274263
@pytest.fixture
275264
def socket(self, port):

0 commit comments

Comments
 (0)