|
| 1 | +from unittest.mock import Mock, patch |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from webknossos.utils import call_with_retries |
| 6 | + |
| 7 | + |
| 8 | +def test_call_with_retries_success() -> None: |
| 9 | + """Test that a successful function call returns immediately.""" |
| 10 | + mock_fn = Mock(return_value="success") |
| 11 | + |
| 12 | + result = call_with_retries(mock_fn) |
| 13 | + |
| 14 | + assert result == "success" |
| 15 | + mock_fn.call_count == 1 # Function called only once (direct success) |
| 16 | + |
| 17 | + |
| 18 | +@patch("time.sleep") |
| 19 | +def test_call_with_retries_sucess_with_retry(mock_sleep: Mock) -> None: |
| 20 | + """Test retry behavior when function succeeds after retryable failures.""" |
| 21 | + mock_fn = Mock( |
| 22 | + side_effect=[ |
| 23 | + Exception("Too Many Requests"), |
| 24 | + Exception("GatewayTimeout"), |
| 25 | + "success", |
| 26 | + ] |
| 27 | + ) |
| 28 | + |
| 29 | + result = call_with_retries(mock_fn, num_retries=3, backoff_factor=2.0) |
| 30 | + |
| 31 | + assert result == "success" |
| 32 | + assert mock_fn.call_count == 3 # Called once for each try |
| 33 | + assert mock_sleep.call_count == 2 # Sleep called twice for retries |
| 34 | + |
| 35 | + |
| 36 | +@patch("time.sleep") |
| 37 | +def test_call_with_retries_failure_after_retry(mock_sleep: Mock) -> None: |
| 38 | + """Test retry behavior when function succeeds after retryable failures.""" |
| 39 | + mock_fn = Mock( |
| 40 | + side_effect=[ |
| 41 | + Exception("Too Many Requests"), |
| 42 | + Exception("GatewayTimeout"), |
| 43 | + "success", |
| 44 | + ] |
| 45 | + ) |
| 46 | + |
| 47 | + with pytest.raises(Exception): |
| 48 | + call_with_retries(mock_fn, num_retries=2, backoff_factor=2.0) |
| 49 | + |
| 50 | + assert mock_fn.call_count == 2 |
| 51 | + assert ( |
| 52 | + mock_sleep.call_count == 1 |
| 53 | + ) # Sleep called once after the first failure but not after the second/last failure |
| 54 | + |
| 55 | + |
| 56 | +@patch("time.sleep") |
| 57 | +def test_call_with_retries_direct_failure(mock_sleep: Mock) -> None: |
| 58 | + """Test retry behavior when function succeeds after retryable failures.""" |
| 59 | + mock_fn = Mock( |
| 60 | + side_effect=[ |
| 61 | + RuntimeError("Non Retryable Runtime Error"), |
| 62 | + "success", |
| 63 | + ] |
| 64 | + ) |
| 65 | + |
| 66 | + with pytest.raises(RuntimeError): |
| 67 | + call_with_retries(mock_fn, num_retries=5, backoff_factor=2.0) |
| 68 | + |
| 69 | + assert mock_fn.call_count == 1 # Only called once, no retries |
| 70 | + assert mock_sleep.call_count == 0 # Sleep not called since it failed immediately |
0 commit comments