CacheTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. //
  2. // CacheTests.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
  28. /// are meant to cover the main cases of `Cache-Control` header usage, but are by no means exhaustive.
  29. ///
  30. /// These tests work as follows:
  31. ///
  32. /// - Set up an `URLCache`
  33. /// - Set up an `Alamofire.Session`
  34. /// - Execute requests for all `Cache-Control` header values to prime the `URLCache` with cached responses
  35. /// - Start up a new test
  36. /// - Execute another round of the same requests with a given `URLRequestCachePolicy`
  37. /// - Verify whether the response came from the cache or from the network
  38. /// - This is determined by whether the cached response timestamp matches the new response timestamp
  39. ///
  40. /// An important thing to note is the difference in behavior between iOS and macOS. On iOS, a response with
  41. /// a `Cache-Control` header value of `no-store` is still written into the `URLCache` where on macOS, it is not.
  42. /// The different tests below reflect and demonstrate this behavior.
  43. ///
  44. /// For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
  45. final class CacheTestCase: BaseTestCase {
  46. // MARK: -
  47. enum CacheControl {
  48. static let publicControl = "public"
  49. static let privateControl = "private"
  50. static let maxAgeNonExpired = "max-age=3600"
  51. static let maxAgeExpired = "max-age=0"
  52. static let noCache = "no-cache"
  53. static let noStore = "no-store"
  54. static var allValues: [String] {
  55. [CacheControl.publicControl,
  56. CacheControl.privateControl,
  57. CacheControl.maxAgeNonExpired,
  58. CacheControl.maxAgeExpired,
  59. CacheControl.noCache,
  60. CacheControl.noStore]
  61. }
  62. }
  63. // MARK: - Properties
  64. var urlCache: URLCache!
  65. var manager: Session!
  66. var requests: [String: URLRequest] = [:]
  67. var timestamps: [String: String] = [:]
  68. // MARK: - Setup and Teardown
  69. override func setUp() {
  70. super.setUp()
  71. urlCache = {
  72. let capacity = 50 * 1024 * 1024 // MBs
  73. #if targetEnvironment(macCatalyst)
  74. let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
  75. return URLCache(memoryCapacity: capacity, diskCapacity: capacity, directory: directory)
  76. #else
  77. let directory = (NSTemporaryDirectory() as NSString).appendingPathComponent(UUID().uuidString)
  78. return URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: directory)
  79. #endif
  80. }()
  81. manager = {
  82. let configuration: URLSessionConfiguration = {
  83. let configuration = URLSessionConfiguration.default
  84. configuration.headers = HTTPHeaders.default
  85. configuration.requestCachePolicy = .useProtocolCachePolicy
  86. configuration.urlCache = urlCache
  87. return configuration
  88. }()
  89. let manager = Session(configuration: configuration)
  90. return manager
  91. }()
  92. primeCachedResponses()
  93. }
  94. override func tearDown() {
  95. super.tearDown()
  96. requests.removeAll()
  97. timestamps.removeAll()
  98. urlCache.removeAllCachedResponses()
  99. }
  100. // MARK: - Cache Priming Methods
  101. /**
  102. Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
  103. This implementation leverages dispatch groups to execute all the requests as well as wait an additional
  104. second before returning. This ensures the cache contains responses for all requests that are at least
  105. one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
  106. or the network based on the timestamp of the response.
  107. */
  108. func primeCachedResponses() {
  109. let dispatchGroup = DispatchGroup()
  110. let serialQueue = DispatchQueue(label: "org.alamofire.cache-tests")
  111. for cacheControl in CacheControl.allValues {
  112. dispatchGroup.enter()
  113. let request = startRequest(cacheControl: cacheControl,
  114. queue: serialQueue,
  115. completion: { _, response in
  116. let timestamp = response!.allHeaderFields["Date"] as! String
  117. self.timestamps[cacheControl] = timestamp
  118. dispatchGroup.leave()
  119. })
  120. requests[cacheControl] = request
  121. }
  122. // Wait for all requests to complete
  123. _ = dispatchGroup.wait(timeout: .now() + 30)
  124. // Pause for 1 additional second to ensure all timestamps will be different
  125. dispatchGroup.enter()
  126. serialQueue.asyncAfter(deadline: .now() + 1.5) {
  127. dispatchGroup.leave()
  128. }
  129. // Wait for our 1 second pause to complete
  130. _ = dispatchGroup.wait(timeout: .now() + 1.75)
  131. }
  132. // MARK: - Request Helper Methods
  133. @discardableResult
  134. func startRequest(cacheControl: String,
  135. cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy,
  136. queue: DispatchQueue = .main,
  137. completion: @escaping (URLRequest?, HTTPURLResponse?) -> Void)
  138. -> URLRequest {
  139. var urlRequest = Endpoint(path: .responseHeaders,
  140. timeout: 30,
  141. cachePolicy: cachePolicy).urlRequest
  142. urlRequest = (try? URLEncoding.default.encode(urlRequest, with: ["Cache-Control": cacheControl])) ?? urlRequest
  143. let request = manager.request(urlRequest)
  144. request.response(queue: queue) { response in
  145. completion(response.request, response.response)
  146. }
  147. return urlRequest
  148. }
  149. // MARK: - Test Execution and Verification
  150. func executeTest(cachePolicy: URLRequest.CachePolicy,
  151. cacheControl: String,
  152. shouldReturnCachedResponse: Bool) {
  153. // Given
  154. let expectation = self.expectation(description: "GET request to httpbin")
  155. var response: HTTPURLResponse?
  156. // When
  157. startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
  158. response = responseResponse
  159. expectation.fulfill()
  160. }
  161. waitForExpectations(timeout: timeout)
  162. // Then
  163. verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
  164. }
  165. func verifyResponse(_ response: HTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
  166. guard let cachedResponseTimestamp = timestamps[cacheControl] else {
  167. XCTFail("cached response timestamp should not be nil")
  168. return
  169. }
  170. if let response = response, let timestamp = response.allHeaderFields["Date"] as? String {
  171. if isCachedResponse {
  172. XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
  173. } else {
  174. XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
  175. }
  176. } else {
  177. XCTFail("response should not be nil")
  178. }
  179. }
  180. // MARK: - Tests
  181. func testURLCacheContainsCachedResponsesForAllRequests() {
  182. // Given
  183. let publicRequest = requests[CacheControl.publicControl]!
  184. let privateRequest = requests[CacheControl.privateControl]!
  185. let maxAgeNonExpiredRequest = requests[CacheControl.maxAgeNonExpired]!
  186. let maxAgeExpiredRequest = requests[CacheControl.maxAgeExpired]!
  187. let noCacheRequest = requests[CacheControl.noCache]!
  188. let noStoreRequest = requests[CacheControl.noStore]!
  189. // When
  190. let publicResponse = urlCache.cachedResponse(for: publicRequest)
  191. let privateResponse = urlCache.cachedResponse(for: privateRequest)
  192. let maxAgeNonExpiredResponse = urlCache.cachedResponse(for: maxAgeNonExpiredRequest)
  193. let maxAgeExpiredResponse = urlCache.cachedResponse(for: maxAgeExpiredRequest)
  194. let noCacheResponse = urlCache.cachedResponse(for: noCacheRequest)
  195. let noStoreResponse = urlCache.cachedResponse(for: noStoreRequest)
  196. // Then
  197. XCTAssertNotNil(publicResponse, "\(CacheControl.publicControl) response should not be nil")
  198. XCTAssertNotNil(privateResponse, "\(CacheControl.privateControl) response should not be nil")
  199. XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.maxAgeNonExpired) response should not be nil")
  200. XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.maxAgeExpired) response should not be nil")
  201. XCTAssertNotNil(noCacheResponse, "\(CacheControl.noCache) response should not be nil")
  202. XCTAssertNil(noStoreResponse, "\(CacheControl.noStore) response should be nil")
  203. }
  204. func testDefaultCachePolicy() {
  205. let cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
  206. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false)
  207. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false)
  208. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  209. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false)
  210. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false)
  211. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  212. }
  213. func testIgnoreLocalCacheDataPolicy() {
  214. let cachePolicy: URLRequest.CachePolicy = .reloadIgnoringLocalCacheData
  215. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false)
  216. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false)
  217. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: false)
  218. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false)
  219. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false)
  220. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  221. }
  222. func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
  223. let cachePolicy: URLRequest.CachePolicy = .returnCacheDataElseLoad
  224. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true)
  225. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true)
  226. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  227. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true)
  228. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true)
  229. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  230. }
  231. func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
  232. let cachePolicy: URLRequest.CachePolicy = .returnCacheDataDontLoad
  233. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true)
  234. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true)
  235. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  236. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true)
  237. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true)
  238. // Given
  239. let expectation = self.expectation(description: "GET request to httpbin")
  240. var response: HTTPURLResponse?
  241. // When
  242. startRequest(cacheControl: CacheControl.noStore, cachePolicy: cachePolicy) { _, responseResponse in
  243. response = responseResponse
  244. expectation.fulfill()
  245. }
  246. waitForExpectations(timeout: timeout)
  247. // Then
  248. XCTAssertNil(response, "response should be nil")
  249. }
  250. }