Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / util.py
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.
4
5 import imp
6 import inspect
7 import logging
8 import os
9 import socket
10 import sys
11 import time
12
13
14 class TimeoutException(Exception):
15   pass
16
17
18 def GetBaseDir():
19   main_module = sys.modules['__main__']
20   if hasattr(main_module, '__file__'):
21     return os.path.dirname(os.path.abspath(main_module.__file__))
22   else:
23     return os.getcwd()
24
25
26 def GetTelemetryDir():
27   return os.path.normpath(os.path.join(
28       __file__, os.pardir, os.pardir, os.pardir))
29
30
31 def GetUnittestDataDir():
32   return os.path.join(GetTelemetryDir(), 'unittest_data')
33
34
35 def GetChromiumSrcDir():
36   return os.path.normpath(os.path.join(GetTelemetryDir(), os.pardir, os.pardir))
37
38
39 def AddDirToPythonPath(*path_parts):
40   path = os.path.abspath(os.path.join(*path_parts))
41   if os.path.isdir(path) and path not in sys.path:
42     sys.path.append(path)
43
44 _counter = [0]
45 def _GetUniqueModuleName():
46   _counter[0] += 1
47   return "page_set_module_" + str(_counter[0])
48
49 def GetPythonPageSetModule(file_path):
50   return imp.load_source(_GetUniqueModuleName(), file_path)
51
52
53 def WaitFor(condition, timeout):
54   """Waits for up to |timeout| secs for the function |condition| to return True.
55
56   Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
57
58   Returns:
59     Result of |condition| function (if present).
60   """
61   min_poll_interval =   0.1
62   max_poll_interval =   5
63   output_interval   = 300
64
65   def GetConditionString():
66     if condition.__name__ == '<lambda>':
67       try:
68         return inspect.getsource(condition).strip()
69       except IOError:
70         pass
71     return condition.__name__
72
73   start_time = time.time()
74   last_output_time = start_time
75   while True:
76     res = condition()
77     if res:
78       return res
79     now = time.time()
80     elapsed_time = now - start_time
81     last_output_elapsed_time = now - last_output_time
82     if elapsed_time > timeout:
83       raise TimeoutException('Timed out while waiting %ds for %s.' %
84                              (timeout, GetConditionString()))
85     if last_output_elapsed_time > output_interval:
86       logging.info('Continuing to wait %ds for %s. Elapsed: %ds.',
87                    timeout, GetConditionString(), elapsed_time)
88       last_output_time = time.time()
89     poll_interval = min(max(elapsed_time / 10., min_poll_interval),
90                         max_poll_interval)
91     time.sleep(poll_interval)
92
93
94 def FindElementAndPerformAction(tab, text, callback_code):
95   """JavaScript snippet for finding an element with a given text on a page."""
96   code = """
97       (function() {
98         var callback_function = """ + callback_code + """;
99         function _findElement(element, text) {
100           if (element.innerHTML == text) {
101             callback_function
102             return element;
103           }
104           for (var i in element.childNodes) {
105             var found = _findElement(element.childNodes[i], text);
106             if (found)
107               return found;
108           }
109           return null;
110         }
111         var _element = _findElement(document, \"""" + text + """\");
112         return callback_function(_element);
113       })();"""
114   return tab.EvaluateJavaScript(code)
115
116
117 def GetUnreservedAvailableLocalPort():
118   """Returns an available port on the system.
119
120   WARNING: This method does not reserve the port it returns, so it may be used
121   by something else before you get to use it. This can lead to flake.
122   """
123   tmp = socket.socket()
124   tmp.bind(('', 0))
125   port = tmp.getsockname()[1]
126   tmp.close()
127
128   return port
129
130
131 def CloseConnections(tab):
132   """Closes all TCP sockets held open by the browser."""
133   try:
134     tab.ExecuteJavaScript("""window.chrome && chrome.benchmarking &&
135                              chrome.benchmarking.closeConnections()""")
136   except Exception:
137     pass
138
139
140 def GetBuildDirectories():
141   """Yields all combination of Chromium build output directories."""
142   build_dirs = ['build',
143                 os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
144                 'xcodebuild']
145
146   build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64']
147
148   for build_dir in build_dirs:
149     for build_type in build_types:
150       yield build_dir, build_type