2
0

CachedResponseHandlerTests.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. //
  2. // CachedResponseHandlerTests.swift
  3. //
  4. // Copyright (c) 2019 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. import Alamofire
  25. import Foundation
  26. import XCTest
  27. final class CachedResponseHandlerTestCase: BaseTestCase {
  28. // MARK: Properties
  29. private let urlString = "https://httpbin.org/get"
  30. // MARK: Tests - Per Request
  31. func testThatRequestCachedResponseHandlerCanCacheResponse() {
  32. // Given
  33. let session = self.session()
  34. var response: DataResponse<Data?, AFError>?
  35. let expectation = self.expectation(description: "Request should cache response")
  36. // When
  37. let request = session.request(urlString).cacheResponse(using: ResponseCacher.cache).response { resp in
  38. response = resp
  39. expectation.fulfill()
  40. }
  41. waitForExpectations(timeout: timeout, handler: nil)
  42. // Then
  43. XCTAssertEqual(response?.result.isSuccess, true)
  44. XCTAssertTrue(session.cachedResponseExists(for: request))
  45. }
  46. func testThatRequestCachedResponseHandlerCanNotCacheResponse() {
  47. // Given
  48. let session = self.session()
  49. var response: DataResponse<Data?, AFError>?
  50. let expectation = self.expectation(description: "Request should not cache response")
  51. // When
  52. let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in
  53. response = resp
  54. expectation.fulfill()
  55. }
  56. waitForExpectations(timeout: timeout, handler: nil)
  57. // Then
  58. XCTAssertEqual(response?.result.isSuccess, true)
  59. XCTAssertFalse(session.cachedResponseExists(for: request))
  60. }
  61. func testThatRequestCachedResponseHandlerCanModifyCacheResponse() {
  62. // Given
  63. let session = self.session()
  64. var response: DataResponse<Data?, AFError>?
  65. let expectation = self.expectation(description: "Request should cache response")
  66. // When
  67. let cacher = ResponseCacher(behavior: .modify { _, response in
  68. CachedURLResponse(response: response.response,
  69. data: response.data,
  70. userInfo: ["key": "value"],
  71. storagePolicy: .allowed)
  72. })
  73. let request = session.request(urlString).cacheResponse(using: cacher).response { resp in
  74. response = resp
  75. expectation.fulfill()
  76. }
  77. waitForExpectations(timeout: timeout, handler: nil)
  78. // Then
  79. XCTAssertEqual(response?.result.isSuccess, true)
  80. XCTAssertTrue(session.cachedResponseExists(for: request))
  81. XCTAssertEqual(session.cachedResponse(for: request)?.userInfo?["key"] as? String, "value")
  82. }
  83. // MARK: Tests - Per Session
  84. func testThatSessionCachedResponseHandlerCanCacheResponse() {
  85. // Given
  86. let session = self.session(using: ResponseCacher.cache)
  87. var response: DataResponse<Data?, AFError>?
  88. let expectation = self.expectation(description: "Request should cache response")
  89. // When
  90. let request = session.request(urlString).response { resp in
  91. response = resp
  92. expectation.fulfill()
  93. }
  94. waitForExpectations(timeout: timeout, handler: nil)
  95. // Then
  96. XCTAssertEqual(response?.result.isSuccess, true)
  97. XCTAssertTrue(session.cachedResponseExists(for: request))
  98. }
  99. func testThatSessionCachedResponseHandlerCanNotCacheResponse() {
  100. // Given
  101. let session = self.session(using: ResponseCacher.doNotCache)
  102. var response: DataResponse<Data?, AFError>?
  103. let expectation = self.expectation(description: "Request should not cache response")
  104. // When
  105. let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in
  106. response = resp
  107. expectation.fulfill()
  108. }
  109. waitForExpectations(timeout: timeout, handler: nil)
  110. // Then
  111. XCTAssertEqual(response?.result.isSuccess, true)
  112. XCTAssertFalse(session.cachedResponseExists(for: request))
  113. }
  114. func testThatSessionCachedResponseHandlerCanModifyCacheResponse() {
  115. // Given
  116. let cacher = ResponseCacher(behavior: .modify { _, response in
  117. CachedURLResponse(response: response.response,
  118. data: response.data,
  119. userInfo: ["key": "value"],
  120. storagePolicy: .allowed)
  121. })
  122. let session = self.session(using: cacher)
  123. var response: DataResponse<Data?, AFError>?
  124. let expectation = self.expectation(description: "Request should cache response")
  125. // When
  126. let request = session.request(urlString).cacheResponse(using: cacher).response { resp in
  127. response = resp
  128. expectation.fulfill()
  129. }
  130. waitForExpectations(timeout: timeout, handler: nil)
  131. // Then
  132. XCTAssertEqual(response?.result.isSuccess, true)
  133. XCTAssertTrue(session.cachedResponseExists(for: request))
  134. XCTAssertEqual(session.cachedResponse(for: request)?.userInfo?["key"] as? String, "value")
  135. }
  136. // MARK: Tests - Per Request Prioritization
  137. func testThatRequestCachedResponseHandlerIsPrioritizedOverSessionCachedResponseHandler() {
  138. // Given
  139. let session = self.session(using: ResponseCacher.cache)
  140. var response: DataResponse<Data?, AFError>?
  141. let expectation = self.expectation(description: "Request should cache response")
  142. // When
  143. let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in
  144. response = resp
  145. expectation.fulfill()
  146. }
  147. waitForExpectations(timeout: timeout, handler: nil)
  148. // Then
  149. XCTAssertEqual(response?.result.isSuccess, true)
  150. XCTAssertFalse(session.cachedResponseExists(for: request))
  151. }
  152. // MARK: Private - Test Helpers
  153. private func session(using handler: CachedResponseHandler? = nil) -> Session {
  154. let configuration = URLSessionConfiguration.af.default
  155. let capacity = 100_000_000
  156. let cache: URLCache
  157. #if targetEnvironment(macCatalyst)
  158. let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
  159. cache = URLCache(memoryCapacity: capacity, diskCapacity: capacity, directory: directory)
  160. #else
  161. let directory = (NSTemporaryDirectory() as NSString).appendingPathComponent(UUID().uuidString)
  162. cache = URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: directory)
  163. #endif
  164. configuration.urlCache = cache
  165. return Session(configuration: configuration, cachedResponseHandler: handler)
  166. }
  167. }
  168. // MARK: -
  169. extension Session {
  170. fileprivate func cachedResponse(for request: Request) -> CachedURLResponse? {
  171. guard let urlRequest = request.request else { return nil }
  172. return session.configuration.urlCache?.cachedResponse(for: urlRequest)
  173. }
  174. fileprivate func cachedResponseExists(for request: Request) -> Bool {
  175. cachedResponse(for: request) != nil
  176. }
  177. }