import time

from bubblecam import bounded_io


def test_returns_value_when_fast():
    assert bounded_io.run_with_timeout(lambda: 42) == 42


def test_returns_default_on_timeout():
    # Stands in for a read against a wedged SD card, which blocks in
    # uninterruptible I/O and never returns.
    result = bounded_io.run_with_timeout(lambda: time.sleep(5), timeout=0.1, default="gave-up")
    assert result == "gave-up"


def test_returns_default_on_exception():
    def boom():
        raise OSError("device not responding")

    assert bounded_io.run_with_timeout(boom, default=0) == 0


def test_does_not_block_caller_past_timeout():
    started = time.monotonic()
    bounded_io.run_with_timeout(lambda: time.sleep(10), timeout=0.2, default=None)
    assert time.monotonic() - started < 3.0
