site_utils.py revision 5d3e45481f628e7fe5b3ba805f35f512bfad4c2b
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
3# found in the LICENSE file.
4
5import time
6from autotest_lib.client.common_lib import error
7
8
9class TimeoutError(error.TestError):
10    """Error raised when we time out when waiting on a condition."""
11
12
13def poll_for_condition(
14    condition, exception=None, timeout=10, sleep_interval=0.1, desc=None):
15    """Poll until a condition becomes true.
16
17    condition: function taking no args and returning bool
18    exception: exception to throw if condition doesn't become true
19    timeout: maximum number of seconds to wait
20    sleep_interval: time to sleep between polls
21    desc: description of default TimeoutError used if 'exception' is None
22
23    Raises:
24        'exception' arg if supplied; site_utils.TimeoutError otherwise
25    """
26    start_time = time.time()
27    while True:
28        if condition():
29            return
30        if time.time() + sleep_interval - start_time > timeout:
31            if exception:
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 TimeoutError, desc
39
40        time.sleep(sleep_interval)
41