AuthenticationInterceptorTests.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. //
  2. // AuthenticationInterceptorTests.swift
  3. //
  4. // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. @testable import Alamofire
  25. import Foundation
  26. import XCTest
  27. final class AuthenticationInterceptorTestCase: BaseTestCase {
  28. // MARK: - Helper Types
  29. struct TestCredential: AuthenticationCredential {
  30. let accessToken: String
  31. let refreshToken: String
  32. let userID: String
  33. let expiration: Date
  34. let requiresRefresh: Bool
  35. init(accessToken: String = "a0",
  36. refreshToken: String = "r0",
  37. userID: String = "u0",
  38. expiration: Date = Date(),
  39. requiresRefresh: Bool = false) {
  40. self.accessToken = accessToken
  41. self.refreshToken = refreshToken
  42. self.userID = userID
  43. self.expiration = expiration
  44. self.requiresRefresh = requiresRefresh
  45. }
  46. }
  47. enum TestAuthError: Error {
  48. case refreshNetworkFailure
  49. }
  50. final class TestAuthenticator: Authenticator {
  51. private(set) var applyCount = 0
  52. private(set) var refreshCount = 0
  53. private(set) var didRequestFailDueToAuthErrorCount = 0
  54. private(set) var isRequestAuthenticatedWithCredentialCount = 0
  55. let shouldRefreshAsynchronously: Bool
  56. let refreshResult: Result<TestCredential, any Error>?
  57. let lock = NSLock()
  58. init(shouldRefreshAsynchronously: Bool = true, refreshResult: Result<TestCredential, any Error>? = nil) {
  59. self.shouldRefreshAsynchronously = shouldRefreshAsynchronously
  60. self.refreshResult = refreshResult
  61. }
  62. func apply(_ credential: TestCredential, to urlRequest: inout URLRequest) {
  63. lock.lock(); defer { lock.unlock() }
  64. applyCount += 1
  65. urlRequest.headers.add(.authorization(credential.accessToken))
  66. }
  67. func refresh(_ credential: TestCredential,
  68. for session: Session,
  69. completion: @escaping (Result<TestCredential, any Error>) -> Void) {
  70. lock.lock()
  71. refreshCount += 1
  72. let result = refreshResult ?? .success(
  73. TestCredential(accessToken: "a\(refreshCount)",
  74. refreshToken: "a\(refreshCount)",
  75. userID: "u1",
  76. expiration: Date())
  77. )
  78. if shouldRefreshAsynchronously {
  79. // The 10 ms delay here is important to allow multiple requests to queue up while refreshing.
  80. DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.01) { completion(result) }
  81. lock.unlock()
  82. } else {
  83. lock.unlock()
  84. completion(result)
  85. }
  86. }
  87. func didRequest(_ urlRequest: URLRequest,
  88. with response: HTTPURLResponse,
  89. failDueToAuthenticationError error: any Error)
  90. -> Bool {
  91. lock.lock(); defer { lock.unlock() }
  92. didRequestFailDueToAuthErrorCount += 1
  93. return response.statusCode == 401
  94. }
  95. func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: TestCredential) -> Bool {
  96. lock.lock(); defer { lock.unlock() }
  97. isRequestAuthenticatedWithCredentialCount += 1
  98. return urlRequest.headers["Authorization"] == credential.accessToken
  99. }
  100. }
  101. final class PathAdapter: RequestAdapter {
  102. var paths: [String]
  103. init(paths: [String]) {
  104. self.paths = paths
  105. }
  106. func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, any Error>) -> Void) {
  107. var request = urlRequest
  108. var urlComponents = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!
  109. urlComponents.path = paths.removeFirst()
  110. request.url = urlComponents.url
  111. completion(.success(request))
  112. }
  113. }
  114. // MARK: - Tests - Adapt
  115. // @MainActor
  116. // func testThatInterceptorCanAdaptURLRequest() {
  117. // // Given
  118. // let credential = TestCredential()
  119. // let authenticator = TestAuthenticator()
  120. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  121. //
  122. // let session = Session()
  123. //
  124. // let expect = expectation(description: "request should complete")
  125. // var response: AFDataResponse<Data?>?
  126. //
  127. // // When
  128. // let request = session.request(.default, interceptor: interceptor).validate().response {
  129. // response = $0
  130. // expect.fulfill()
  131. // }
  132. //
  133. // waitForExpectations(timeout: timeout)
  134. //
  135. // // Then
  136. // XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  137. // XCTAssertEqual(response?.result.isSuccess, true)
  138. //
  139. // XCTAssertEqual(authenticator.applyCount, 1)
  140. // XCTAssertEqual(authenticator.refreshCount, 0)
  141. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  142. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  143. //
  144. // XCTAssertEqual(request.retryCount, 0)
  145. // }
  146. //
  147. // @MainActor
  148. // func testThatInterceptorQueuesAdaptOperationWhenRefreshing() {
  149. // // Given
  150. // let credential = TestCredential(requiresRefresh: true)
  151. // let authenticator = TestAuthenticator()
  152. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  153. //
  154. // let session = Session()
  155. //
  156. // let expect = expectation(description: "both requests should complete")
  157. // expect.expectedFulfillmentCount = 2
  158. //
  159. // var response1: AFDataResponse<Data?>?
  160. // var response2: AFDataResponse<Data?>?
  161. //
  162. // // When
  163. // let request1 = session.request(.status(200), interceptor: interceptor).validate().response {
  164. // response1 = $0
  165. // expect.fulfill()
  166. // }
  167. //
  168. // let request2 = session.request(.status(202), interceptor: interceptor).validate().response {
  169. // response2 = $0
  170. // expect.fulfill()
  171. // }
  172. //
  173. // waitForExpectations(timeout: timeout)
  174. //
  175. // // Then
  176. // XCTAssertEqual(response1?.request?.headers["Authorization"], "a1")
  177. // XCTAssertEqual(response2?.request?.headers["Authorization"], "a1")
  178. // XCTAssertEqual(response1?.result.isSuccess, true)
  179. // XCTAssertEqual(response2?.result.isSuccess, true)
  180. //
  181. // XCTAssertEqual(authenticator.applyCount, 2)
  182. // XCTAssertEqual(authenticator.refreshCount, 1)
  183. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  184. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  185. //
  186. // XCTAssertEqual(request1.retryCount, 0)
  187. // XCTAssertEqual(request2.retryCount, 0)
  188. // }
  189. //
  190. // @MainActor
  191. // func testThatInterceptorThrowsMissingCredentialErrorWhenCredentialIsNil() {
  192. // // Given
  193. // let authenticator = TestAuthenticator()
  194. // let interceptor = AuthenticationInterceptor(authenticator: authenticator)
  195. //
  196. // let session = Session()
  197. //
  198. // let expect = expectation(description: "request should complete")
  199. // var response: AFDataResponse<Data?>?
  200. //
  201. // // When
  202. // let request = session.request(.default, interceptor: interceptor).validate().response {
  203. // response = $0
  204. // expect.fulfill()
  205. // }
  206. //
  207. // waitForExpectations(timeout: timeout)
  208. //
  209. // // Then
  210. // XCTAssertEqual(response?.request?.headers.count, 0)
  211. //
  212. // XCTAssertEqual(response?.result.isFailure, true)
  213. // XCTAssertEqual(response?.result.failure?.asAFError?.isRequestAdaptationError, true)
  214. // XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .missingCredential)
  215. //
  216. // XCTAssertEqual(authenticator.applyCount, 0)
  217. // XCTAssertEqual(authenticator.refreshCount, 0)
  218. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  219. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  220. //
  221. // XCTAssertEqual(request.retryCount, 0)
  222. // }
  223. //
  224. // @MainActor
  225. // func testThatInterceptorRethrowsRefreshErrorFromAdapt() {
  226. // // Given
  227. // let credential = TestCredential(requiresRefresh: true)
  228. // let authenticator = TestAuthenticator(refreshResult: .failure(TestAuthError.refreshNetworkFailure))
  229. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  230. //
  231. // let session = Session()
  232. //
  233. // let expect = expectation(description: "request should complete")
  234. // var response: AFDataResponse<Data?>?
  235. //
  236. // // When
  237. // let request = session.request(.default, interceptor: interceptor).validate().response {
  238. // response = $0
  239. // expect.fulfill()
  240. // }
  241. //
  242. // waitForExpectations(timeout: timeout)
  243. //
  244. // // Then
  245. // XCTAssertEqual(response?.request?.headers.count, 0)
  246. //
  247. // XCTAssertEqual(response?.result.isFailure, true)
  248. // XCTAssertEqual(response?.result.failure?.asAFError?.isRequestAdaptationError, true)
  249. // XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? TestAuthError, .refreshNetworkFailure)
  250. //
  251. // if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  252. // XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  253. // XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  254. // }
  255. //
  256. // XCTAssertEqual(authenticator.applyCount, 0)
  257. // XCTAssertEqual(authenticator.refreshCount, 1)
  258. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  259. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  260. //
  261. // XCTAssertEqual(request.retryCount, 0)
  262. // }
  263. //
  264. // // MARK: - Tests - Retry
  265. //
  266. // // If we not using swift-corelibs-foundation where URLRequest to /invalid/path is a fatal error.
  267. // #if !canImport(FoundationNetworking)
  268. // @MainActor
  269. // func testThatInterceptorDoesNotRetryWithoutResponse() {
  270. // // Given
  271. // let credential = TestCredential()
  272. // let authenticator = TestAuthenticator()
  273. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  274. //
  275. // let urlRequest = URLRequest(url: URL(string: "/invalid/path")!)
  276. // let session = Session()
  277. //
  278. // let expect = expectation(description: "request should complete")
  279. // var response: AFDataResponse<Data?>?
  280. //
  281. // // When
  282. // let request = session.request(urlRequest, interceptor: interceptor).validate().response {
  283. // response = $0
  284. // expect.fulfill()
  285. // }
  286. //
  287. // waitForExpectations(timeout: timeout)
  288. //
  289. // // Then
  290. // XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  291. //
  292. // XCTAssertEqual(response?.result.isFailure, true)
  293. // XCTAssertEqual(response?.result.failure?.asAFError?.isSessionTaskError, true)
  294. //
  295. // XCTAssertEqual(authenticator.applyCount, 1)
  296. // XCTAssertEqual(authenticator.refreshCount, 0)
  297. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  298. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  299. //
  300. // XCTAssertEqual(request.retryCount, 0)
  301. // }
  302. // #endif
  303. //
  304. // @MainActor
  305. // func testThatInterceptorDoesNotRetryWhenRequestDoesNotFailDueToAuthError() {
  306. // // Given
  307. // let credential = TestCredential()
  308. // let authenticator = TestAuthenticator()
  309. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  310. //
  311. // let session = Session()
  312. //
  313. // let expect = expectation(description: "request should complete")
  314. // var response: AFDataResponse<Data?>?
  315. //
  316. // // When
  317. // let request = session.request(.status(500), interceptor: interceptor).validate().response {
  318. // response = $0
  319. // expect.fulfill()
  320. // }
  321. //
  322. // waitForExpectations(timeout: timeout)
  323. //
  324. // // Then
  325. // XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  326. //
  327. // XCTAssertEqual(response?.result.isFailure, true)
  328. // XCTAssertEqual(response?.result.failure?.asAFError?.isResponseValidationError, true)
  329. // XCTAssertEqual(response?.result.failure?.asAFError?.responseCode, 500)
  330. //
  331. // XCTAssertEqual(authenticator.applyCount, 1)
  332. // XCTAssertEqual(authenticator.refreshCount, 0)
  333. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  334. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  335. //
  336. // XCTAssertEqual(request.retryCount, 0)
  337. // }
  338. //
  339. // @MainActor
  340. // func testThatInterceptorThrowsMissingCredentialErrorWhenCredentialIsNilAndRequestShouldBeRetried() {
  341. // // Given
  342. // let credential = TestCredential()
  343. // let authenticator = TestAuthenticator()
  344. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  345. //
  346. // let session = stored(Session())
  347. //
  348. // let expect = expectation(description: "request should complete")
  349. // var response: AFDataResponse<Data?>?
  350. //
  351. // // When
  352. // let request = session.request(.status(401), interceptor: interceptor)
  353. // .validate {
  354. // interceptor.credential = nil
  355. // }
  356. // .response {
  357. // response = $0
  358. // expect.fulfill()
  359. // }
  360. //
  361. // waitForExpectations(timeout: timeout)
  362. //
  363. // // Then
  364. // XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  365. //
  366. // XCTAssertEqual(response?.result.isFailure, true)
  367. // XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  368. // XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .missingCredential)
  369. //
  370. // if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  371. // XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  372. // XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  373. // }
  374. //
  375. // XCTAssertEqual(authenticator.applyCount, 1)
  376. // XCTAssertEqual(authenticator.refreshCount, 0)
  377. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  378. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  379. //
  380. // XCTAssertEqual(request.retryCount, 0)
  381. // }
  382. //
  383. // @MainActor
  384. // func testThatInterceptorRetriesRequestThatFailedWithOutdatedCredential() {
  385. // // Given
  386. // let credential = TestCredential()
  387. // let authenticator = TestAuthenticator()
  388. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  389. //
  390. // let session = stored(Session())
  391. //
  392. // let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  393. // let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  394. //
  395. // let expect = expectation(description: "request should complete")
  396. // var response: AFDataResponse<Data?>?
  397. //
  398. // // When
  399. // let request = session.request(.default, interceptor: compositeInterceptor)
  400. // .validate {
  401. // interceptor.credential = TestCredential(accessToken: "a1",
  402. // refreshToken: "r1",
  403. // userID: "u0",
  404. // expiration: Date(),
  405. // requiresRefresh: false)
  406. // }
  407. // .response {
  408. // response = $0
  409. // expect.fulfill()
  410. // }
  411. //
  412. // waitForExpectations(timeout: timeout)
  413. //
  414. // // Then
  415. // XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  416. // XCTAssertEqual(response?.result.isSuccess, true)
  417. //
  418. // XCTAssertEqual(authenticator.applyCount, 2)
  419. // XCTAssertEqual(authenticator.refreshCount, 0)
  420. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  421. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  422. //
  423. // XCTAssertEqual(request.retryCount, 1)
  424. // }
  425. //
  426. // // Produces double lock reported in https://github.com/Alamofire/Alamofire/issues/3294#issuecomment-703241558
  427. // @MainActor
  428. // func testThatInterceptorDoesNotDeadlockWhenAuthenticatorCallsRefreshCompletionSynchronouslyOnCallingQueue() {
  429. // // Given
  430. // let credential = TestCredential(requiresRefresh: true)
  431. // let authenticator = TestAuthenticator(shouldRefreshAsynchronously: false)
  432. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  433. //
  434. // let eventMonitor = ClosureEventMonitor()
  435. //
  436. // eventMonitor.requestDidCreateTask = { _, _ in
  437. // interceptor.credential = TestCredential(accessToken: "a1",
  438. // refreshToken: "r1",
  439. // userID: "u0",
  440. // expiration: Date(),
  441. // requiresRefresh: false)
  442. // }
  443. //
  444. // let session = Session(eventMonitors: [eventMonitor])
  445. //
  446. // let pathAdapter = PathAdapter(paths: ["/status/200"])
  447. // let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  448. //
  449. // let expect = expectation(description: "request should complete")
  450. // var response: AFDataResponse<Data?>?
  451. //
  452. // // When
  453. // let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  454. // response = $0
  455. // expect.fulfill()
  456. // }
  457. //
  458. // waitForExpectations(timeout: timeout)
  459. //
  460. // // Then
  461. // XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  462. // XCTAssertEqual(response?.result.isSuccess, true)
  463. //
  464. // XCTAssertEqual(authenticator.applyCount, 1)
  465. // XCTAssertEqual(authenticator.refreshCount, 1)
  466. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  467. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  468. //
  469. // XCTAssertEqual(request.retryCount, 0)
  470. // }
  471. //
  472. // @MainActor
  473. // func testThatInterceptorRetriesRequestAfterRefresh() {
  474. // // Given
  475. // let credential = TestCredential()
  476. // let authenticator = TestAuthenticator()
  477. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  478. //
  479. // let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  480. //
  481. // let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  482. //
  483. // let session = Session()
  484. //
  485. // let expect = expectation(description: "request should complete")
  486. // var response: AFDataResponse<Data?>?
  487. //
  488. // // When
  489. // let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  490. // response = $0
  491. // expect.fulfill()
  492. // }
  493. //
  494. // waitForExpectations(timeout: timeout)
  495. //
  496. // // Then
  497. // XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  498. // XCTAssertEqual(response?.result.isSuccess, true)
  499. //
  500. // XCTAssertEqual(authenticator.applyCount, 2)
  501. // XCTAssertEqual(authenticator.refreshCount, 1)
  502. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  503. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  504. //
  505. // XCTAssertEqual(request.retryCount, 1)
  506. // }
  507. //
  508. // @MainActor
  509. // func testThatInterceptorRethrowsRefreshErrorFromRetry() {
  510. // // Given
  511. // let credential = TestCredential()
  512. // let authenticator = TestAuthenticator(refreshResult: .failure(TestAuthError.refreshNetworkFailure))
  513. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  514. //
  515. // let session = Session()
  516. //
  517. // let expect = expectation(description: "request should complete")
  518. // var response: AFDataResponse<Data?>?
  519. //
  520. // // When
  521. // let request = session.request(.status(401), interceptor: interceptor).validate().response {
  522. // response = $0
  523. // expect.fulfill()
  524. // }
  525. //
  526. // waitForExpectations(timeout: timeout)
  527. //
  528. // // Then
  529. // XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  530. //
  531. // XCTAssertEqual(response?.result.isFailure, true)
  532. // XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  533. // XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? TestAuthError, .refreshNetworkFailure)
  534. //
  535. // if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  536. // XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  537. // XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  538. // }
  539. //
  540. // XCTAssertEqual(authenticator.applyCount, 1)
  541. // XCTAssertEqual(authenticator.refreshCount, 1)
  542. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  543. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  544. //
  545. // XCTAssertEqual(request.retryCount, 0)
  546. // }
  547. //
  548. // @MainActor
  549. // func testThatInterceptorTriggersRefreshWithMultipleParallelRequestsReturning401Responses() {
  550. // // Given
  551. // let credential = TestCredential()
  552. // let authenticator = TestAuthenticator()
  553. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  554. //
  555. // let requestCount = 6
  556. // let session = stored(Session())
  557. //
  558. // let expect = expectation(description: "both requests should complete")
  559. // expect.expectedFulfillmentCount = requestCount
  560. //
  561. // var requests: [Int: Request] = [:]
  562. // var responses: [Int: AFDataResponse<Data?>] = [:]
  563. //
  564. // for index in 0..<requestCount {
  565. // let pathAdapter = PathAdapter(paths: ["/status/401", "/status/20\(index)"])
  566. // let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  567. //
  568. // // When
  569. // let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  570. // responses[index] = $0
  571. // expect.fulfill()
  572. // }
  573. //
  574. // requests[index] = request
  575. // }
  576. //
  577. // waitForExpectations(timeout: timeout)
  578. //
  579. // // Then
  580. // for index in 0..<requestCount {
  581. // let response = responses[index]
  582. // XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  583. // XCTAssertEqual(response?.result.isSuccess, true)
  584. //
  585. // let request = requests[index]
  586. // XCTAssertEqual(request?.retryCount, 1)
  587. // }
  588. //
  589. // XCTAssertEqual(authenticator.applyCount, 12)
  590. // XCTAssertEqual(authenticator.refreshCount, 1)
  591. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 6)
  592. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 6)
  593. // }
  594. //
  595. // // MARK: - Tests - Excessive Refresh
  596. //
  597. // @MainActor
  598. // func testThatInterceptorIgnoresExcessiveRefreshWhenRefreshWindowIsNil() {
  599. // // Given
  600. // let credential = TestCredential()
  601. // let authenticator = TestAuthenticator()
  602. // let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  603. //
  604. // let pathAdapter = PathAdapter(paths: ["/status/401",
  605. // "/status/401",
  606. // "/status/401",
  607. // "/status/401",
  608. // "/status/401",
  609. // "/status/200"])
  610. //
  611. // let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  612. //
  613. // let session = Session()
  614. //
  615. // let expect = expectation(description: "request should complete")
  616. // var response: AFDataResponse<Data?>?
  617. //
  618. // // When
  619. // let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  620. // response = $0
  621. // expect.fulfill()
  622. // }
  623. //
  624. // waitForExpectations(timeout: timeout)
  625. //
  626. // // Then
  627. // XCTAssertEqual(response?.request?.headers["Authorization"], "a5")
  628. // XCTAssertEqual(response?.result.isSuccess, true)
  629. //
  630. // XCTAssertEqual(authenticator.applyCount, 6)
  631. // XCTAssertEqual(authenticator.refreshCount, 5)
  632. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 5)
  633. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 5)
  634. //
  635. // XCTAssertEqual(request.retryCount, 5)
  636. // }
  637. //
  638. // @MainActor
  639. // func testThatInterceptorThrowsExcessiveRefreshErrorWhenExcessiveRefreshOccurs() {
  640. // // Given
  641. // let credential = TestCredential()
  642. // let authenticator = TestAuthenticator()
  643. // let interceptor = AuthenticationInterceptor(authenticator: authenticator,
  644. // credential: credential,
  645. // refreshWindow: .init(interval: 30, maximumAttempts: 2))
  646. //
  647. // let session = Session()
  648. //
  649. // let expect = expectation(description: "request should complete")
  650. // var response: AFDataResponse<Data?>?
  651. //
  652. // // When
  653. // let request = session.request(.status(401), interceptor: interceptor).validate().response {
  654. // response = $0
  655. // expect.fulfill()
  656. // }
  657. //
  658. // waitForExpectations(timeout: timeout)
  659. //
  660. // // Then
  661. // XCTAssertEqual(response?.request?.headers["Authorization"], "a2")
  662. //
  663. // XCTAssertEqual(response?.result.isFailure, true)
  664. // XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  665. // XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .excessiveRefresh)
  666. //
  667. // if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  668. // XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  669. // XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  670. // }
  671. //
  672. // XCTAssertEqual(authenticator.applyCount, 3)
  673. // XCTAssertEqual(authenticator.refreshCount, 2)
  674. // XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 3)
  675. // XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 3)
  676. //
  677. // XCTAssertEqual(request.retryCount, 2)
  678. // }
  679. }