Skip to content

Commit 9a1dfab

Browse files
authored
chore: check if port is in use before returning the port to start a new server. (#394)
* fix flaky tests * fix formatting changes
1 parent 9c38610 commit 9a1dfab

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

tests/unit/test_flow.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,14 +251,25 @@ 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+
254258
@pytest.fixture
255259
def port(self):
256260
# Creating a new server at the same port will result in
257261
# a 'Address already in use' error for a brief
258262
# period of time after the socket has been closed.
259-
# Work around this in the tests by choosing a random port.
263+
# Work around this in the tests by choosing a different port each time.
260264
# https://stackoverflow.com/questions/6380057/python-binding-socket-address-already-in-use
261-
yield random.randrange(60400, 60900)
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
262273

263274
@pytest.fixture
264275
def socket(self, port):

0 commit comments

Comments
 (0)