Team Ai
Apppublic

cactus183/patchbench-dev

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
test_code.py87 linesDownload Raw Back to medium_03
1import time2from solution import retry_with_backoff3 4 5def test_success_first_try():6    @retry_with_backoff(max_retries=3, base_delay=0.01)7    def succeed():8        return 429    assert succeed() == 4210 11 12def test_retries_on_exception():13    call_count = 014 15    @retry_with_backoff(max_retries=3, base_delay=0.01)16    def fail_twice():17        nonlocal call_count18        call_count += 119        if call_count <= 2:20            raise ValueError("not yet")21        return "ok"22 23    assert fail_twice() == "ok"24    assert call_count == 325 26 27def test_gives_up_after_max_retries():28    call_count = 029 30    @retry_with_backoff(max_retries=3, base_delay=0.01)31    def always_fail():32        nonlocal call_count33        call_count += 134        raise ValueError("fail")35 36    try:37        always_fail()38        assert False, "Should have raised"39    except ValueError:40        pass41    assert call_count == 3, f"Expected 3 calls, got {call_count}"42 43 44def test_exponential_delay():45    timestamps = []46    call_count = 047 48    @retry_with_backoff(max_retries=4, base_delay=0.01)49    def fail_and_track():50        nonlocal call_count51        timestamps.append(time.time())52        call_count += 153        if call_count <= 3:54            raise ValueError("fail")55        return "ok"56 57    fail_and_track()58    delays = [timestamps[i + 1] - timestamps[i] for i in range(len(timestamps) - 1)]59    # Delays should increase: each should be > 1.5x the previous60    for i in range(1, len(delays)):61        assert delays[i] > delays[i - 1] * 1.5, (62            f"Delay {i} ({delays[i]:.4f}) should be > 1.5x delay {i-1} ({delays[i-1]:.4f})"63        )64 65 66def test_returns_on_success():67    @retry_with_backoff(max_retries=3, base_delay=0.01)68    def compute():69        return {"result": [1, 2, 3]}70    assert compute() == {"result": [1, 2, 3]}71 72 73def test_exception_message_preserved():74    call_count = 075 76    @retry_with_backoff(max_retries=3, base_delay=0.01)77    def fail_with_message():78        nonlocal call_count79        call_count += 180        raise ValueError(f"error on call {call_count}")81 82    try:83        fail_with_message()84        assert False, "Should have raised"85    except ValueError as e:86        assert "call 3" in str(e), f"Expected 'call 3' in error, got: {e}"87