Xixuan Wu | 865fa28 | 2017-09-05 15:23:19 -0700 | [diff] [blame] | 1 | # Copyright 2017 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 | |
| 5 | """Module for use by any callers.""" |
| 6 | |
| 7 | import logging |
| 8 | |
| 9 | import time |
| 10 | |
| 11 | |
| 12 | DEFAULT_TIMEOUT_SEC = 10 |
| 13 | |
| 14 | |
| 15 | def wait_for_value(func, expected_value=None, exception_to_raise=(), |
| 16 | timeout_sec=DEFAULT_TIMEOUT_SEC): |
| 17 | """Wait to return the value of func(). |
| 18 | |
| 19 | If |expected_value| is not set, return immediately. |
| 20 | |
| 21 | If |expected_value| is set, polls the return value until |expected_value| |
| 22 | is reached, and returns that value. |
| 23 | |
| 24 | Polling will stop after |timeout_sec| regardless of these thresholds. |
| 25 | |
| 26 | Args: |
| 27 | func: function whose return value is to be waited on. |
| 28 | expected_value: wait for func to return this value. |
| 29 | exception_to_raise: exceptions that func() could raise. |
| 30 | timeout_sec: Number of seconds to wait before giving up and |
| 31 | returning whatever value func() last returned. |
| 32 | |
| 33 | Returns: |
| 34 | The most recent return value of func(). |
| 35 | |
| 36 | Raises: |
| 37 | Unexpected exceptions: not exist in exception_to_raise. |
| 38 | """ |
| 39 | value = None |
| 40 | start_time_sec = time.time() |
| 41 | while True: |
| 42 | time.sleep(0.1) |
| 43 | try: |
| 44 | value = func() |
| 45 | if (expected_value is None or |
| 46 | (expected_value is not None and value == expected_value)): |
| 47 | break |
| 48 | |
| 49 | if time.time() - start_time_sec >= timeout_sec: |
| 50 | break |
| 51 | except exception_to_raise as e: |
| 52 | logging.warning(str(e)) |
| 53 | |
| 54 | return value |