1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
12 class TimeoutException(Exception):
17 main_module = sys.modules['__main__']
18 if hasattr(main_module, '__file__'):
19 return os.path.dirname(os.path.abspath(main_module.__file__))
24 def GetTelemetryDir():
25 return os.path.normpath(os.path.join(
26 __file__, os.pardir, os.pardir, os.pardir))
29 def GetUnittestDataDir():
30 return os.path.join(GetTelemetryDir(), 'unittest_data')
33 def GetChromiumSrcDir():
34 return os.path.normpath(os.path.join(GetTelemetryDir(), os.pardir, os.pardir))
37 def AddDirToPythonPath(*path_parts):
38 path = os.path.abspath(os.path.join(*path_parts))
39 if os.path.isdir(path) and path not in sys.path:
43 def WaitFor(condition, timeout):
44 """Waits for up to |timeout| secs for the function |condition| to return True.
46 Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
49 Result of |condition| function (if present).
51 min_poll_interval = 0.1
55 def GetConditionString():
56 if condition.__name__ == '<lambda>':
58 return inspect.getsource(condition).strip()
61 return condition.__name__
63 start_time = time.time()
64 last_output_time = start_time
70 elapsed_time = now - start_time
71 last_output_elapsed_time = now - last_output_time
72 if elapsed_time > timeout:
73 raise TimeoutException('Timed out while waiting %ds for %s.' %
74 (timeout, GetConditionString()))
75 if last_output_elapsed_time > output_interval:
76 logging.info('Continuing to wait %ds for %s. Elapsed: %ds.',
77 timeout, GetConditionString(), elapsed_time)
78 last_output_time = time.time()
79 poll_interval = min(max(elapsed_time / 10., min_poll_interval),
81 time.sleep(poll_interval)
84 def FindElementAndPerformAction(tab, text, callback_code):
85 """JavaScript snippet for finding an element with a given text on a page."""
88 var callback_function = """ + callback_code + """;
89 function _findElement(element, text) {
90 if (element.innerHTML == text) {
94 for (var i in element.childNodes) {
95 var found = _findElement(element.childNodes[i], text);
101 var _element = _findElement(document, \"""" + text + """\");
102 return callback_function(_element);
104 return tab.EvaluateJavaScript(code)
107 class PortPair(object):
108 def __init__(self, local_port, remote_port):
109 self.local_port = local_port
110 self.remote_port = remote_port
113 def GetUnreservedAvailableLocalPort():
114 """Returns an available port on the system.
116 WARNING: This method does not reserve the port it returns, so it may be used
117 by something else before you get to use it. This can lead to flake.
119 tmp = socket.socket()
121 port = tmp.getsockname()[1]
127 def CloseConnections(tab):
128 """Closes all TCP sockets held open by the browser."""
130 tab.ExecuteJavaScript("""window.chrome && chrome.benchmarking &&
131 chrome.benchmarking.closeConnections()""")
136 def GetBuildDirectories():
137 """Yields all combination of Chromium build output directories."""
138 build_dirs = ['build',
139 os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
142 build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64']
144 for build_dir in build_dirs:
145 for build_type in build_types:
146 yield build_dir, build_type
148 def FindSupportBinary(binary_name, executable=True):
149 """Returns the path to the given binary name."""
150 # TODO(tonyg/dtu): This should support finding binaries in cloud storage.
153 required_mode = os.R_OK
155 required_mode = os.X_OK
157 chrome_root = GetChromiumSrcDir()
158 for build_dir, build_type in GetBuildDirectories():
159 candidate = os.path.join(chrome_root, build_dir, build_type, binary_name)
160 if os.path.isfile(candidate) and os.access(candidate, required_mode):
161 candidate_mtime = os.stat(candidate).st_mtime
162 if candidate_mtime > command_mtime:
164 command_mtime = candidate_mtime