OLD | NEW |
| (Empty) |
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 import inspect | |
5 import socket | |
6 import time | |
7 | |
8 class TimeoutException(Exception): | |
9 pass | |
10 | |
11 def WaitFor(condition, | |
12 timeout, poll_interval=0.1, | |
13 pass_time_left_to_func=False): | |
14 assert isinstance(condition, type(lambda: None)) # is function | |
15 start_time = time.time() | |
16 while True: | |
17 if pass_time_left_to_func: | |
18 res = condition(max((start_time + timeout) - time.time(), 0.0)) | |
19 else: | |
20 res = condition() | |
21 if res: | |
22 break | |
23 if time.time() - start_time > timeout: | |
24 if condition.__name__ == '<lambda>': | |
25 try: | |
26 condition_string = inspect.getsource(condition).strip() | |
27 except IOError: | |
28 condition_string = condition.__name__ | |
29 else: | |
30 condition_string = condition.__name__ | |
31 raise TimeoutException('Timed out while waiting %ds for %s.' % | |
32 (timeout, condition_string)) | |
33 time.sleep(poll_interval) | |
34 | |
35 def FindElementAndPerformAction(tab, text, callback_code): | |
36 """JavaScript snippet for finding an element with a given text on a page.""" | |
37 code = """ | |
38 (function() { | |
39 var callback_function = """ + callback_code + """; | |
40 function _findElement(element, text) { | |
41 if (element.innerHTML == text) { | |
42 callback_function | |
43 return element; | |
44 } | |
45 for (var i in element.childNodes) { | |
46 var found = _findElement(element.childNodes[i], text); | |
47 if (found) | |
48 return found; | |
49 } | |
50 return null; | |
51 } | |
52 var _element = _findElement(document, \"""" + text + """\"); | |
53 return callback_function(_element); | |
54 })();""" | |
55 return tab.EvaluateJavaScript(code) | |
56 | |
57 class PortPair(object): | |
58 def __init__(self, local_port, remote_port): | |
59 self.local_port = local_port | |
60 self.remote_port = remote_port | |
61 | |
62 def GetAvailableLocalPort(): | |
63 tmp = socket.socket() | |
64 tmp.bind(('', 0)) | |
65 port = tmp.getsockname()[1] | |
66 tmp.close() | |
67 | |
68 return port | |
OLD | NEW |