from unittest.mock import Mock import pytest from getstream_connector.throttling import RateLimitThrottler def test_init(): throttler = RateLimitThrottler() assert throttler @pytest.mark.parametrize("threshold_factor", (-0.1, 1.1)) def test_init_threshold_factor(threshold_factor): with pytest.raises(ValueError, match=r"threshold_factor must be within the range \[0, 1\]"): RateLimitThrottler(threshold_factor=threshold_factor) def test_scale_factor(): with pytest.raises(ValueError, match=r"scale_factor must be greater than 0"): RateLimitThrottler(scale_factor=-0.1) def test_get_sleep_time(mocker): throttler = RateLimitThrottler() mock_client = Mock(ratelimit_info=Mock(remaining=100, limit=1000, reset_in_seconds=50)) mock_get_sleep_time_on_rate_limit = mocker.patch.object(throttler, "_get_sleep_time_on_rate_limit") throttler._get_sleep_time(client=mock_client) mock_get_sleep_time_on_rate_limit.assert_called_once_with(100, 1000, 50) @pytest.mark.parametrize( "remaining, reset_in, limit, threshold_factor, scale_factor, expected", ( # No sleep needed when remaining is within the safe zone (500, 60, 1000, 0.75, 20.0, 0), # Higher scale factor makes sleep time larger (10, 60, 1000, 0.5, 20.0, 60.0), # Sleep time should not exceed reset_in (1, 10, 1000, 0.5, 1000.0, 10.0), # No remaining requests (0, 30, 1000, 0.5, 20.0, 30.0), # Negative remaining. Shouldn't be possible but still test for it (-100, 60, 1000, 0.5, 20.0, 60), # Negative reset_in. Shouldn't be possible but still test for it (100, -60, 1000, 0.5, 20.0, 0), ), ) def test_rate_limit_throttling(remaining, reset_in, limit, threshold_factor, scale_factor, expected): throttler = RateLimitThrottler(threshold_factor=threshold_factor, scale_factor=scale_factor) sleep_time = throttler._get_sleep_time_on_rate_limit(remaining, limit, reset_in) assert sleep_time == expected