OLD | NEW |
1 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. | 1 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 import time | 5 import time |
6 from autotest_lib.client.common_lib import error | 6 from autotest_lib.client.common_lib import error |
7 | 7 |
8 | 8 |
| 9 class TimeoutError(error.TestError): |
| 10 """Error raised when we time out when waiting on a condition.""" |
| 11 |
| 12 |
9 def poll_for_condition( | 13 def poll_for_condition( |
10 condition, exception=None, timeout=10, sleep_interval=0.1): | 14 condition, exception=None, timeout=10, sleep_interval=0.1, desc=None): |
11 """Poll until a condition becomes true. | 15 """Poll until a condition becomes true. |
12 | 16 |
13 condition: function taking no args and returning bool | 17 condition: function taking no args and returning bool |
14 exception: exception to throw if condition doesn't become true | 18 exception: exception to throw if condition doesn't become true |
15 timeout: maximum number of seconds to wait | 19 timeout: maximum number of seconds to wait |
16 sleep_interval: time to sleep between polls | 20 sleep_interval: time to sleep between polls |
| 21 desc: description of default TimeoutError used if 'exception' is None |
17 | 22 |
18 Raises: | 23 Raises: |
19 'exception' arg if supplied; error.TestError otherwise | 24 'exception' arg if supplied; site_utils.TimeoutError otherwise |
20 """ | 25 """ |
21 start_time = time.time() | 26 start_time = time.time() |
22 while True: | 27 while True: |
23 if condition(): | 28 if condition(): |
24 return | 29 return |
25 if time.time() + sleep_interval - start_time > timeout: | 30 if time.time() + sleep_interval - start_time > timeout: |
26 raise exception if exception else error.TestError( | 31 if exception: |
27 'Timed out waiting for condition') | 32 raise exception |
| 33 |
| 34 if desc: |
| 35 desc = 'Timed out waiting for condition: %s' % desc |
| 36 else: |
| 37 desc = 'Timed out waiting for unnamed condition' |
| 38 raise error.TestError(desc) |
| 39 |
28 time.sleep(sleep_interval) | 40 time.sleep(sleep_interval) |
OLD | NEW |