utils.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """
  18. The Utils methods.
  19. """
  20. import socket
  21. from selenium.webdriver.common.keys import Keys
  22. try:
  23. basestring
  24. except NameError:
  25. # Python 3
  26. basestring = str
  27. def free_port():
  28. """
  29. Determines a free port using sockets.
  30. """
  31. free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  32. free_socket.bind(('0.0.0.0', 0))
  33. free_socket.listen(5)
  34. port = free_socket.getsockname()[1]
  35. free_socket.close()
  36. return port
  37. def find_connectable_ip(host, port=None):
  38. """Resolve a hostname to an IP, preferring IPv4 addresses.
  39. We prefer IPv4 so that we don't change behavior from previous IPv4-only
  40. implementations, and because some drivers (e.g., FirefoxDriver) do not
  41. support IPv6 connections.
  42. If the optional port number is provided, only IPs that listen on the given
  43. port are considered.
  44. :Args:
  45. - host - A hostname.
  46. - port - Optional port number.
  47. :Returns:
  48. A single IP address, as a string. If any IPv4 address is found, one is
  49. returned. Otherwise, if any IPv6 address is found, one is returned. If
  50. neither, then None is returned.
  51. """
  52. try:
  53. addrinfos = socket.getaddrinfo(host, None)
  54. except socket.gaierror:
  55. return None
  56. ip = None
  57. for family, _, _, _, sockaddr in addrinfos:
  58. connectable = True
  59. if port:
  60. connectable = is_connectable(port, sockaddr[0])
  61. if connectable and family == socket.AF_INET:
  62. return sockaddr[0]
  63. if connectable and not ip and family == socket.AF_INET6:
  64. ip = sockaddr[0]
  65. return ip
  66. def join_host_port(host, port):
  67. """Joins a hostname and port together.
  68. This is a minimal implementation intended to cope with IPv6 literals. For
  69. example, _join_host_port('::1', 80) == '[::1]:80'.
  70. :Args:
  71. - host - A hostname.
  72. - port - An integer port.
  73. """
  74. if ':' in host and not host.startswith('['):
  75. return '[%s]:%d' % (host, port)
  76. return '%s:%d' % (host, port)
  77. def is_connectable(port, host="localhost"):
  78. """
  79. Tries to connect to the server at port to see if it is running.
  80. :Args:
  81. - port - The port to connect.
  82. """
  83. socket_ = None
  84. try:
  85. socket_ = socket.create_connection((host, port), 1)
  86. result = True
  87. except socket.error:
  88. result = False
  89. finally:
  90. if socket_:
  91. socket_.close()
  92. return result
  93. def is_url_connectable(port):
  94. """
  95. Tries to connect to the HTTP server at /status path
  96. and specified port to see if it responds successfully.
  97. :Args:
  98. - port - The port to connect.
  99. """
  100. try:
  101. from urllib import request as url_request
  102. except ImportError:
  103. import urllib2 as url_request
  104. try:
  105. res = url_request.urlopen("http://127.0.0.1:%s/status" % port)
  106. if res.getcode() == 200:
  107. return True
  108. else:
  109. return False
  110. except Exception:
  111. return False
  112. def keys_to_typing(value):
  113. """Processes the values that will be typed in the element."""
  114. typing = []
  115. for val in value:
  116. if isinstance(val, Keys):
  117. typing.append(val)
  118. elif isinstance(val, int):
  119. val = str(val)
  120. for i in range(len(val)):
  121. typing.append(val[i])
  122. else:
  123. for i in range(len(val)):
  124. typing.append(val[i])
  125. return typing