diff --git a/kafka/cluster.py b/kafka/cluster.py index 4cf3cc6b7..d93ac367b 100644 --- a/kafka/cluster.py +++ b/kafka/cluster.py @@ -728,7 +728,11 @@ def collect_hosts(hosts, randomize=True): result = [] for host_port in hosts: # ignore leading SECURITY_PROTOCOL:// to mimic java client - host_port = re.sub('^.*://', '', host_port) + host_port = re.sub('^.*://', '', host_port.strip()) + # skip empty entries (e.g. a trailing comma), like the java client does; + # otherwise '' resolves to localhost:9092 + if not host_port: + continue host, port, afi = get_ip_port_afi(host_port) result.append((host, port, afi)) diff --git a/test/test_cluster.py b/test/test_cluster.py index e4a4b726d..9f6e9506c 100644 --- a/test/test_cluster.py +++ b/test/test_cluster.py @@ -414,6 +414,19 @@ def test_collect_hosts__protocol(self): ('fizz.buzz', 5678, socket.AF_UNSPEC), ]) + @pytest.mark.parametrize('hosts', [ + "localhost:1234,", + "localhost:1234,,localhost", + " localhost:1234 , ", + "localhost:1234,PLAINTEXT://", + ['localhost:1234', ' ', ''], + ]) + def test_collect_hosts__ignores_empty_entries(self, hosts): + # An empty entry would otherwise become ('', 9092), which resolves to localhost + results = collect_hosts(hosts) + assert results + assert all(host == 'localhost' for host, _port, _afi in results) + class TestExpandToCanonicalBootstrapHosts: def test_expands_multi_ip_host_to_canonical_names(self):