ConnectionBackoffTests.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import XCTest
  17. @testable import GRPCHTTP2Core
  18. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  19. final class ConnectionBackoffTests: XCTestCase {
  20. func testUnjitteredBackoff() {
  21. let backoff = ConnectionBackoff(
  22. initial: .seconds(10),
  23. max: .seconds(30),
  24. multiplier: 1.5,
  25. jitter: 0.0
  26. )
  27. var iterator = backoff.makeIterator()
  28. XCTAssertEqual(iterator.next(), .seconds(10))
  29. // 10 * 1.5 = 15 seconds
  30. XCTAssertEqual(iterator.next(), .seconds(15))
  31. // 15 * 1.5 = 22.5 seconds
  32. XCTAssertEqual(iterator.next(), .seconds(22.5))
  33. // 22.5 * 1.5 = 33.75 seconds, clamped to 30 seconds, all future values will be the same.
  34. XCTAssertEqual(iterator.next(), .seconds(30))
  35. XCTAssertEqual(iterator.next(), .seconds(30))
  36. XCTAssertEqual(iterator.next(), .seconds(30))
  37. }
  38. func testJitteredBackoff() {
  39. let backoff = ConnectionBackoff(
  40. initial: .seconds(10),
  41. max: .seconds(30),
  42. multiplier: 1.5,
  43. jitter: 0.1
  44. )
  45. var iterator = backoff.makeIterator()
  46. // Initial isn't jittered.
  47. XCTAssertEqual(iterator.next(), .seconds(10))
  48. // Next value should be 10 * 1.5 = 15 seconds ± 1.5 seconds
  49. var expected: ClosedRange<Duration> = .seconds(13.5) ... .seconds(16.5)
  50. XCTAssert(expected.contains(iterator.next()))
  51. // Next value should be 15 * 1.5 = 22.5 seconds ± 2.25 seconds
  52. expected = .seconds(20.25) ... .seconds(24.75)
  53. XCTAssert(expected.contains(iterator.next()))
  54. // Next value should be 22.5 * 1.5 = 33.75 seconds, clamped to 30 seconds ± 3 seconds.
  55. // All future values will be in the same range.
  56. expected = .seconds(27) ... .seconds(33)
  57. XCTAssert(expected.contains(iterator.next()))
  58. XCTAssert(expected.contains(iterator.next()))
  59. XCTAssert(expected.contains(iterator.next()))
  60. }
  61. }