diff --git a/py/selenium/webdriver/common/utils.py b/py/selenium/webdriver/common/utils.py index 801b88ce2d027..fd5ac0b0607f2 100644 --- a/py/selenium/webdriver/common/utils.py +++ b/py/selenium/webdriver/common/utils.py @@ -14,9 +14,11 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -"""The Utils methods.""" + +"""Utility functions.""" import socket +import urllib.request from collections.abc import Iterable from typing import Optional, Union @@ -67,8 +69,8 @@ def find_connectable_ip(host: Union[str, bytes, bytearray, None], port: Optional port are considered. :Args: - - host - A hostname. - - port - Optional port number. + - host - hostname + - port - port number :Returns: 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: example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - - host - A hostname. - - port - An integer port. + - host - hostname or IP + - port - port number """ if ":" in host and not host.startswith("["): return f"[{host}]:{port}" @@ -112,7 +114,8 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool: """Tries to connect to the server at port to see if it is running. :Args: - - port - The port to connect. + - port - port number + - host - hostname or IP """ socket_ = None try: @@ -130,18 +133,22 @@ def is_connectable(port: int, host: Optional[str] = "localhost") -> bool: return result -def is_url_connectable(port: Union[int, str]) -> bool: - """Tries to connect to the HTTP server at /status path and specified port - to see if it responds successfully. +def is_url_connectable( + port: Union[int, str], + host: Optional[str] = "127.0.0.1", + scheme: Optional[str] = "http", +) -> bool: + """Sends a request to the HTTP server at the /status endpoint to see if it + responds successfully. :Args: - - port - The port to connect. + - port - port number + - host - hostname or IP + - scheme - URL scheme """ - from urllib import request as url_request - try: - res = url_request.urlopen(f"http://127.0.0.1:{port}/status") - return res.getcode() == 200 + with urllib.request.urlopen(f"{scheme}://{host}:{port}/status") as res: + return res.getcode() == 200 except Exception: return False