Skip to content

chore: check if port is in use before returning the port to start a new server. #394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions tests/unit/test_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,14 +251,25 @@ def instance(self):
CLIENT_SECRETS_INFO, scopes=self.SCOPES
)

def is_port_in_use(self, port, host="localhost"):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex((host, port)) == 0

@pytest.fixture
def port(self):
# Creating a new server at the same port will result in
# a 'Address already in use' error for a brief
# period of time after the socket has been closed.
# Work around this in the tests by choosing a random port.
# Work around this in the tests by choosing a different port each time.
# https://stackoverflow.com/questions/6380057/python-binding-socket-address-already-in-use
yield random.randrange(60400, 60900)
random_port = -1
for _ in range(10):
random_port = random.randrange(60400, 60900)
if not self.is_port_in_use(random_port):
break
else:
raise OSError("Could not find a free port")
yield random_port

@pytest.fixture
def socket(self, port):
Expand Down
Loading