1414# KIND, either express or implied. See the License for the
1515# specific language governing permissions and limitations
1616# under the License.
17- """The Utils methods."""
17+
18+ """Utility functions."""
1819
1920import socket
21+ import urllib .request
2022from collections .abc import Iterable
2123from typing import Optional , Union
2224
@@ -67,8 +69,8 @@ def find_connectable_ip(host: Union[str, bytes, bytearray, None], port: Optional
6769 port are considered.
6870
6971 :Args:
70- - host - A hostname.
71- - port - Optional port number.
72+ - host - hostname
73+ - port - port number
7274
7375 :Returns:
7476 A single IP address, as a string. If any IPv4 address is found, one is
@@ -100,8 +102,8 @@ def join_host_port(host: str, port: int) -> str:
100102 example, _join_host_port('::1', 80) == '[::1]:80'.
101103
102104 :Args:
103- - host - A hostname.
104- - port - An integer port.
105+ - host - hostname or IP
106+ - port - port number
105107 """
106108 if ":" in host and not host .startswith ("[" ):
107109 return f"[{ host } ]:{ port } "
@@ -112,7 +114,8 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
112114 """Tries to connect to the server at port to see if it is running.
113115
114116 :Args:
115- - port - The port to connect.
117+ - port - port number
118+ - host - hostname or IP
116119 """
117120 socket_ = None
118121 try :
@@ -130,18 +133,22 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
130133 return result
131134
132135
133- def is_url_connectable (port : Union [int , str ]) -> bool :
134- """Tries to connect to the HTTP server at /status path and specified port
135- to see if it responds successfully.
136+ def is_url_connectable (
137+ port : Union [int , str ],
138+ host : Optional [str ] = "127.0.0.1" ,
139+ scheme : Optional [str ] = "http" ,
140+ ) -> bool :
141+ """Sends a request to the HTTP server at the /status endpoint to see if it
142+ responds successfully.
136143
137144 :Args:
138- - port - The port to connect.
145+ - port - port number
146+ - host - hostname or IP
147+ - scheme - URL scheme
139148 """
140- from urllib import request as url_request
141-
142149 try :
143- res = url_request . urlopen (f"http ://127.0.0.1 :{ port } /status" )
144- return res .getcode () == 200
150+ with urllib . request . urlopen (f"{ scheme } ://{ host } :{ port } /status" ) as res :
151+ return res .getcode () == 200
145152 except Exception :
146153 return False
147154
0 commit comments