blob: 6f64ef9e49a4d3f8d9b0301ff799f7919ad3e084 [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
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020024from . import log
25
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020026poll_funcs = []
27
28def register_poll_func(func):
29 global poll_funcs
30 poll_funcs.append(func)
31
32def unregister_poll_func(func):
33 global poll_funcs
34 poll_funcs.remove(func)
35
36def poll():
37 global poll_funcs
38 for func in poll_funcs:
39 func()
40
41def wait_no_raise(log_obj, condition, condition_args, condition_kwargs, timeout, timestep):
42 if not timeout or timeout < 0:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020043 self = log_obj
44 raise log.Error('wait() *must* time out at some point.', timeout=timeout)
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020045 if timestep < 0.1:
46 timestep = 0.1
47
48 started = time.time()
49 while True:
50 poll()
51 if condition(*condition_args, **condition_kwargs):
52 return True
53 waited = time.time() - started
54 if waited > timeout:
55 return False
56 time.sleep(timestep)
57
58def wait(log_obj, condition, *condition_args, timeout=300, timestep=1, **condition_kwargs):
59 if not wait_no_raise(log_obj, condition, condition_args, condition_kwargs, timeout, timestep):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020060 log.ctx(log_obj)
61 raise log.Error('Wait timeout')
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020062
63def sleep(log_obj, seconds):
64 assert seconds > 0.
65 wait_no_raise(log_obj, lambda: False, [], {}, timeout=seconds, timestep=min(seconds, 1))
66
67
68# vim: expandtab tabstop=4 shiftwidth=4