Three requests that get a 401 share one refresh
A refresh-token race reads as the flow it tests: three requests get a 401, one refresh is held while they wait, and each retries with the new token.
- 1 · Script/me answers 401 to the old token and a user to the new one, by condition.
- 2 · HoldThe refresh is held, so the test sees all three 401s arrive before it answers.
- 3 · CheckOne refresh, three retries with the new token, and the new tokens saved.
Run it
swift test --filter refreshTokenRace
RefreshTokenTests.swift
@Test("Three requests that get a 401 share one refresh, then retry with the new token", .verifiesMocks) func refreshTokenRace() async throws { let profileRoute = server.route(.get, "/me") profileRoute.willReturn(.unauthorized(.invalidToken), when: { request in request.bearerToken == "old" }) profileRoute.willReturn(try .json(User(name: "Ana")), when: { request in request.bearerToken == "new" }) let tokenRoute = server.route(.post, "/oauth/token") let heldRefresh = tokenRoute.holdNextCall() async let firstProfile = apiClient.currentUser() async let secondProfile = apiClient.currentUser() async let thirdProfile = apiClient.currentUser() let refreshRequest = await heldRefresh.arrived() for _ in 1...3 { _ = await profileRoute.nextCall(within: 5) } heldRefresh.resume(returning: .oauthToken(access: "new", refresh: "second", expiresIn: 3_600)) let users = try await [firstProfile, secondProfile, thirdProfile] #expect(refreshRequest?.oauthTokenRequest?.grant == .refreshToken("first")) #expect(users == Array(repeating: User(name: "Ana"), count: 3)) tokenRoute.expect(times: 1) profileRoute.expect(times: 3, where: { request in request.bearerToken == "old" }) profileRoute.expect(times: 3, where: { request in request.bearerToken == "new" }) tokenStore.saveSpy.expect(Tokens(access: "new", refresh: "second")) }