Skip to content

Commit

Permalink
Find free port on localhost
Browse files Browse the repository at this point in the history
Instead of a hard-coded port, tests are now using getaddrinfo() and
accept((None, 0)) to find an unused port on localhost.

Signed-off-by: Christian Heimes <[email protected]>
  • Loading branch information
tiran committed Mar 27, 2017
1 parent ed8c29b commit 2260706
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file

import os
import socket
import subprocess
import sys
import unittest

import six


def find_free_address():
"""Bind to None, 0 to find an unused port on localhost (IPv4 or IPv6)
:return:
"""
err = None
for info in socket.getaddrinfo(None, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM):
family, stype, proto, _, addr = info
sock = None
try:
sock = socket.socket(family, stype, proto)
sock.bind(addr)
if family == socket.AF_INET:
return "{}:{}".format(*sock.getsockname())
elif family == socket.AF_INET6:
return "[{}]:{}".format(*sock.getsockname()[:2])
except socket.error as e:
err = e
finally:
if sock is not None:
sock.close()
if err is not None:
raise err
else:
raise socket.error("getaddrinfo returns an empty list")


class TestsCommandLine(unittest.TestCase):
def _custodia_cli(self, *args):
env = os.environ.copy()
Expand Down Expand Up @@ -41,7 +70,8 @@ def test_help(self):
self.assertIn(u'Custodia command line interface', output)

def test_connection_error_with_server_option(self):
invalid_server_name = 'http://localhost:4/secrets/key'
host_port = find_free_address()
invalid_server_name = 'http://{}/secrets/key'.format(host_port)
with self.assertRaises(subprocess.CalledProcessError) as cm:
self._custodia_cli('--server',
invalid_server_name,
Expand Down

0 comments on commit 2260706

Please sign in to comment.