Pau Espin Pedrol | 927344b | 2017-05-22 16:38:49 +0200 | [diff] [blame] | 1 | # osmo_gsm_tester: Event loop |
| 2 | # |
| 3 | # Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH |
| 4 | # |
| 5 | # Author: Pau Espin Pedrol <pespin@sysmocom.de> |
| 6 | # |
| 7 | # This program is free software: you can redistribute it and/or modify |
| 8 | # it under the terms of the GNU Affero General Public License as |
| 9 | # published by the Free Software Foundation, either version 3 of the |
| 10 | # License, or (at your option) any later version. |
| 11 | # |
| 12 | # This program is distributed in the hope that it will be useful, |
| 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | # GNU Affero General Public License for more details. |
| 16 | # |
| 17 | # You should have received a copy of the GNU Affero General Public License |
| 18 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 | |
| 20 | # These will be initialized before each test run. |
| 21 | # A test script can thus establish its context by doing: |
| 22 | # from osmo_gsm_tester.test import * |
| 23 | import time |
| 24 | poll_funcs = [] |
| 25 | |
| 26 | def register_poll_func(func): |
| 27 | global poll_funcs |
| 28 | poll_funcs.append(func) |
| 29 | |
| 30 | def unregister_poll_func(func): |
| 31 | global poll_funcs |
| 32 | poll_funcs.remove(func) |
| 33 | |
| 34 | def poll(): |
| 35 | global poll_funcs |
| 36 | for func in poll_funcs: |
| 37 | func() |
| 38 | |
| 39 | def wait_no_raise(log_obj, condition, condition_args, condition_kwargs, timeout, timestep): |
| 40 | if not timeout or timeout < 0: |
| 41 | log_obj.raise_exn('wait() *must* time out at some point. timeout=%r' % timeout) |
| 42 | if timestep < 0.1: |
| 43 | timestep = 0.1 |
| 44 | |
| 45 | started = time.time() |
| 46 | while True: |
| 47 | poll() |
| 48 | if condition(*condition_args, **condition_kwargs): |
| 49 | return True |
| 50 | waited = time.time() - started |
| 51 | if waited > timeout: |
| 52 | return False |
| 53 | time.sleep(timestep) |
| 54 | |
| 55 | def wait(log_obj, condition, *condition_args, timeout=300, timestep=1, **condition_kwargs): |
| 56 | if not wait_no_raise(log_obj, condition, condition_args, condition_kwargs, timeout, timestep): |
| 57 | log_obj.raise_exn('Wait timeout') |
| 58 | |
| 59 | def sleep(log_obj, seconds): |
| 60 | assert seconds > 0. |
| 61 | wait_no_raise(log_obj, lambda: False, [], {}, timeout=seconds, timestep=min(seconds, 1)) |
| 62 | |
| 63 | |
| 64 | # vim: expandtab tabstop=4 shiftwidth=4 |