def test_event_loop_timer_updates():
    callback = _GetCallback()
    event_loop = EventLoop()

    source1 = event_loop.add_timer(_timer_update_callback1, callback)
    source1.timer_update(10)

    source2 = event_loop.add_timer(_timer_update_callback2, callback)
    source2.timer_update(10)

    callback.source1 = source1
    callback.source2 = source2

    assert callback.n_calls == 0

    # Wait 15 ms, so both timers should be called when we dispatch
    time.sleep(0.015)

    # This should take < 1 sec
    start_time = time.time()
    event_loop.dispatch(20)
    end_time = time.time()

    assert callback.n_calls == 2

    assert end_time - start_time < 1
def test_event_loop_timer():
    callback = _GetCallback()
    event_loop = EventLoop()

    source = event_loop.add_timer(_timer_callback, callback)
    source.timer_update(10)

    event_loop.dispatch(0)
    assert callback.n_calls == 0

    event_loop.dispatch(20)
    assert callback.n_calls == 1
def test_event_loop_signal():
    callback = _GetCallback()
    event_loop = EventLoop()

    event_loop.add_signal(signal.SIGUSR1, _signal_callback, callback)

    event_loop.dispatch(0)
    assert callback.callback is None

    os.kill(os.getpid(), signal.SIGUSR1)

    event_loop.dispatch(0)
    assert callback.callback == signal.SIGUSR1
def test_event_loop_post_dispatch_check():
    callback = _GetCallback()
    event_loop = EventLoop()

    r, w = os.pipe()

    try:
        source = event_loop.add_fd(r, _fd_callback,
                                   EventLoop.FdMask.WL_EVENT_READABLE,
                                   callback)
        source.check()

        event_loop.dispatch(0)
        assert callback.callback == r
    finally:
        os.close(r)
        os.close(w)
def test_event_loop_multiple_same_signals():
    callback = _GetCallback()
    event_loop = EventLoop()

    signal_rm = event_loop.add_signal(signal.SIGUSR1, _signal_callback,
                                      callback)
    event_loop.add_signal(signal.SIGUSR1, _signal_callback, callback)

    event_loop.dispatch(0)
    assert callback.n_calls == 0

    # Check callback gets 2 calls
    for _ in range(5):
        callback.n_calls = 0
        os.kill(os.getpid(), signal.SIGUSR1)
        event_loop.dispatch(0)

        assert callback.n_calls == 2

    # Remove one of the signals
    signal_rm.remove()

    # Callback only gets call now
    for _ in range(5):
        callback.n_calls = 0
        os.kill(os.getpid(), signal.SIGUSR1)
        event_loop.dispatch(0)

        assert callback.n_calls == 1