blob: c3c679befc2391f9ca5df096f57dc8b371888f8a [file] [log] [blame]
Pau Espin Pedrol927344b2017-05-22 16:38:49 +02001# 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
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Pau Espin Pedrol927344b2017-05-22 16:38:49 +02009# 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
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020018# 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 *
23import time
24poll_funcs = []
25
26def register_poll_func(func):
27 global poll_funcs
28 poll_funcs.append(func)
29
30def unregister_poll_func(func):
31 global poll_funcs
32 poll_funcs.remove(func)
33
34def poll():
35 global poll_funcs
36 for func in poll_funcs:
37 func()
38
39def 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
55def 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
59def 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