Skip to content

Commit

Permalink
test: Avoid freeport() collisions in io tests
Browse files Browse the repository at this point in the history
It's very unlikely, but it can (and did) happen that both the server and
admin ports have the same number returned from freeport(). This then
leads to a situation where PostgREST will accept the same port in both
cases, because the host "localhost" will allow binding to ipv4 or ipv6
respectively. This will make the IO tests fail.

This change makes sure that the admin port will never be the same as the
server port and thus avoids this problem.
  • Loading branch information
wolfgangwalther committed May 12, 2024
1 parent 8392357 commit 71885bd
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions test/io/postgrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def run(
env["PGRST_SERVER_UNIX_SOCKET"] = str(socketfile)
baseurl = "http+unix://" + urllib.parse.quote_plus(str(socketfile))

adminport = freeport()
adminport = freeport(port)
env["PGRST_ADMIN_SERVER_PORT"] = str(adminport)
adminurl = f"http://localhost:{adminport}"

Expand Down Expand Up @@ -169,12 +169,15 @@ def metapostgrest():
yield postgrest


def freeport():
def freeport(used_port=None):
"Find a free port on localhost."
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
while True:
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
port = s.getsockname()[1]
if port != used_port:
return port


def wait_until_exit(postgrest):
Expand Down

0 comments on commit 71885bd

Please sign in to comment.