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.realpath(main_module.__file__))
24 def GetTelemetryDir():
25 return os.path.normpath(os.path.join(
26 os.path.realpath(__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 def GetUnreservedAvailableLocalPort():
108 """Returns an available port on the system.
110 WARNING: This method does not reserve the port it returns, so it may be used
111 by something else before you get to use it. This can lead to flake.
113 tmp = socket.socket()
115 port = tmp.getsockname()[1]
121 def CloseConnections(tab):
122 """Closes all TCP sockets held open by the browser."""
124 tab.ExecuteJavaScript("""window.chrome && chrome.benchmarking &&
125 chrome.benchmarking.closeConnections()""")
130 def GetBuildDirectories():
131 """Yields all combination of Chromium build output directories."""
132 build_dirs = ['build',
133 os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
136 build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64']
138 for build_dir in build_dirs:
139 for build_type in build_types:
140 yield build_dir, build_type
142 def FindSupportBinary(binary_name, executable=True):
143 """Returns the path to the given binary name."""
144 # TODO(tonyg/dtu): This should support finding binaries in cloud storage.
147 required_mode = os.R_OK
149 required_mode = os.X_OK
151 chrome_root = GetChromiumSrcDir()
152 for build_dir, build_type in GetBuildDirectories():
153 candidate = os.path.join(chrome_root, build_dir, build_type, binary_name)
154 if os.path.isfile(candidate) and os.access(candidate, required_mode):
155 candidate_mtime = os.stat(candidate).st_mtime
156 if candidate_mtime > command_mtime:
158 command_mtime = candidate_mtime