test__exponential_backoff.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright 2022 Google Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import mock
  15. import pytest # type: ignore
  16. from google.auth import _exponential_backoff
  17. from google.auth import exceptions
  18. @mock.patch("time.sleep", return_value=None)
  19. def test_exponential_backoff(mock_time):
  20. eb = _exponential_backoff.ExponentialBackoff()
  21. curr_wait = eb._current_wait_in_seconds
  22. iteration_count = 0
  23. for attempt in eb:
  24. if attempt == 1:
  25. assert mock_time.call_count == 0
  26. else:
  27. backoff_interval = mock_time.call_args[0][0]
  28. jitter = curr_wait * eb._randomization_factor
  29. assert (curr_wait - jitter) <= backoff_interval <= (curr_wait + jitter)
  30. assert attempt == iteration_count + 1
  31. assert eb.backoff_count == iteration_count + 1
  32. assert eb._current_wait_in_seconds == eb._multiplier ** iteration_count
  33. curr_wait = eb._current_wait_in_seconds
  34. iteration_count += 1
  35. assert eb.total_attempts == _exponential_backoff._DEFAULT_RETRY_TOTAL_ATTEMPTS
  36. assert eb.backoff_count == _exponential_backoff._DEFAULT_RETRY_TOTAL_ATTEMPTS
  37. assert iteration_count == _exponential_backoff._DEFAULT_RETRY_TOTAL_ATTEMPTS
  38. assert (
  39. mock_time.call_count == _exponential_backoff._DEFAULT_RETRY_TOTAL_ATTEMPTS - 1
  40. )
  41. def test_minimum_total_attempts():
  42. with pytest.raises(exceptions.InvalidValue):
  43. _exponential_backoff.ExponentialBackoff(total_attempts=0)
  44. with pytest.raises(exceptions.InvalidValue):
  45. _exponential_backoff.ExponentialBackoff(total_attempts=-1)
  46. _exponential_backoff.ExponentialBackoff(total_attempts=1)