Dan Talayco | ea8ad80 | 2010-02-22 20:30:18 -0800 | [diff] [blame] | 1 | |
| 2 | """ |
| 3 | Utilities for the OpenFlow test framework |
| 4 | """ |
| 5 | |
| 6 | import random |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 7 | import time |
Dan Talayco | ea8ad80 | 2010-02-22 20:30:18 -0800 | [diff] [blame] | 8 | |
| 9 | def gen_xid(): |
| 10 | return random.randrange(1,0xffffffff) |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 11 | |
| 12 | """ |
| 13 | Wait on a condition variable until the given function returns non-None or a timeout expires. |
| 14 | The condition variable must already be acquired. |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 15 | The timeout value -1 means use the default timeout. |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 16 | There is deliberately no support for an infinite timeout. |
| 17 | TODO: get the default timeout from configuration |
| 18 | """ |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 19 | def timed_wait(cv, fn, timeout=-1): |
| 20 | if timeout == -1: |
| 21 | # TODO make this configurable |
Rich Lane | c8aaa3e | 2012-07-26 19:28:02 -0700 | [diff] [blame^] | 22 | timeout = 2 |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 23 | |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 24 | end_time = time.time() + timeout |
| 25 | while True: |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 26 | val = fn() |
| 27 | if val != None: |
| 28 | return val |
| 29 | |
| 30 | remaining_time = end_time - time.time() |
| 31 | cv.wait(remaining_time) |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 32 | |
| 33 | if time.time() > end_time: |
| 34 | return None |