rastrillo / native Public

Clone
git clone https://amadan.net/rastrillo/native

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import XCTest
3import RastrilloNative
4
5final class BackoffTests: XCTestCase {
6 func testDoublesFromHalfASecondToTenWithEqualJitter() {
7 var high = Backoff(random: { $0.upperBound })
8 XCTAssertEqual((0..<7).map { _ in high.next() }, [0.5, 1, 2, 4, 8, 10, 10])
9 var low = Backoff(random: { $0.lowerBound })
10 XCTAssertEqual((0..<6).map { _ in low.next() }, [0.25, 0.5, 1, 2, 4, 5])
11 var real = Backoff()
12 for expected in [0.5, 1.0, 2.0, 4.0] {
13 let delay = real.next()
14 XCTAssertTrue((expected / 2...expected).contains(delay), "\(delay) outside [\(expected / 2), \(expected)]")
15 }
16 }
17
18 func testRetryAfterIsAFloorCappedAtFiveMinutes() {
19 var backoff = Backoff(random: { $0.upperBound })
20 XCTAssertEqual(backoff.next(retryAfter: 30), 30)
21 XCTAssertEqual(backoff.next(retryAfter: 3600), 300)
22 XCTAssertEqual(backoff.next(retryAfter: 0.1), 2, "A short Retry-After must not undercut the backoff")
23 }
24
25 func testResetsOnSuccessAndAfterAStableConnectionOnly() {
26 var backoff = Backoff(random: { $0.upperBound })
27 _ = backoff.next(); _ = backoff.next(); _ = backoff.next()
28 backoff.opened(at: 100)
29 backoff.ended(at: 103)
30 XCTAssertEqual(backoff.next(), 4, "A connection that dropped quickly must keep backing off")
31 backoff.opened(at: 200)
32 backoff.ended(at: 206)
33 XCTAssertEqual(backoff.next(), 0.5)
34 _ = backoff.next()
35 backoff.reset()
36 XCTAssertEqual(backoff.next(), 0.5)
37 }
38
39 /// The stable clock starts when the stream opens, not when the attempt
40 /// starts: a slow refusal or a long access check must not count.
41 func testAnAttemptThatNeverOpenedIsNeverStable() {
42 var backoff = Backoff(random: { $0.upperBound })
43 _ = backoff.next(); _ = backoff.next()
44 backoff.ended(at: 1_000)
45 XCTAssertEqual(backoff.next(), 2, "An attempt that never opened reset the backoff")
46 backoff.opened(at: 2_000)
47 backoff.ended(at: 2_006)
48 _ = backoff.next()
49 backoff.ended(at: 9_000)
50 XCTAssertEqual(backoff.next(), 1, "An earlier open was counted for a later attempt")
51 }
52}
53