CacheTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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.SessionManager`
  34. /// - Execute requests for all `Cache-Control` header values to prime the `NSURLCache` 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 `NSURLCache` 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. class CacheTestCase: BaseTestCase {
  46. // MARK: -
  47. struct 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. return [
  56. CacheControl.publicControl,
  57. CacheControl.privateControl,
  58. CacheControl.maxAgeNonExpired,
  59. CacheControl.maxAgeExpired,
  60. CacheControl.noCache,
  61. CacheControl.noStore
  62. ]
  63. }
  64. }
  65. // MARK: - Properties
  66. var urlCache: URLCache!
  67. var manager: Session!
  68. let urlString = "https://httpbin.org/response-headers"
  69. let requestTimeout: TimeInterval = 30
  70. var requests: [String: URLRequest] = [:]
  71. var timestamps: [String: String] = [:]
  72. // MARK: - Setup and Teardown
  73. override func setUp() {
  74. super.setUp()
  75. urlCache = {
  76. let capacity = 50 * 1024 * 1024 // MBs
  77. if #available(OSX 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
  78. return URLCache(memoryCapacity: capacity, diskCapacity: capacity)
  79. } else {
  80. return URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
  81. }
  82. }()
  83. manager = {
  84. let configuration: URLSessionConfiguration = {
  85. let configuration = URLSessionConfiguration.default
  86. configuration.headers = HTTPHeaders.default
  87. configuration.requestCachePolicy = .useProtocolCachePolicy
  88. configuration.urlCache = urlCache
  89. return configuration
  90. }()
  91. let manager = Session(configuration: configuration)
  92. return manager
  93. }()
  94. primeCachedResponses()
  95. }
  96. override func tearDown() {
  97. super.tearDown()
  98. requests.removeAll()
  99. timestamps.removeAll()
  100. urlCache.removeAllCachedResponses()
  101. }
  102. // MARK: - Cache Priming Methods
  103. /**
  104. Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
  105. This implementation leverages dispatch groups to execute all the requests as well as wait an additional
  106. second before returning. This ensures the cache contains responses for all requests that are at least
  107. one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
  108. or the network based on the timestamp of the response.
  109. */
  110. func primeCachedResponses() {
  111. let dispatchGroup = DispatchGroup()
  112. let serialQueue = DispatchQueue(label: "org.alamofire.cache-tests")
  113. for cacheControl in CacheControl.allValues {
  114. dispatchGroup.enter()
  115. let request = startRequest(
  116. cacheControl: cacheControl,
  117. queue: serialQueue,
  118. completion: { _, response in
  119. let timestamp = response!.allHeaderFields["Date"] as! String
  120. self.timestamps[cacheControl] = timestamp
  121. dispatchGroup.leave()
  122. }
  123. )
  124. requests[cacheControl] = request
  125. }
  126. // Wait for all requests to complete
  127. _ = dispatchGroup.wait(timeout: .now() + 30)
  128. // Pause for 1 additional second to ensure all timestamps will be different
  129. dispatchGroup.enter()
  130. serialQueue.asyncAfter(deadline: .now() + 1) {
  131. dispatchGroup.leave()
  132. }
  133. // Wait for our 1 second pause to complete
  134. _ = dispatchGroup.wait(timeout: .now() + 1.25)
  135. }
  136. // MARK: - Request Helper Methods
  137. func urlRequest(cacheControl: String, cachePolicy: URLRequest.CachePolicy) -> URLRequest {
  138. let parameters = ["Cache-Control": cacheControl]
  139. let url = URL(string: urlString)!
  140. var urlRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: requestTimeout)
  141. urlRequest.httpMethod = HTTPMethod.get.rawValue
  142. do {
  143. return try URLEncoding.default.encode(urlRequest, with: parameters)
  144. } catch {
  145. return urlRequest
  146. }
  147. }
  148. @discardableResult
  149. func startRequest(
  150. cacheControl: String,
  151. cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy,
  152. queue: DispatchQueue = .main,
  153. completion: @escaping (URLRequest?, HTTPURLResponse?) -> Void)
  154. -> URLRequest
  155. {
  156. let urlRequest = self.urlRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
  157. let request = manager.request(urlRequest)
  158. request.response(
  159. queue: queue,
  160. completionHandler: { response in
  161. completion(response.request, response.response)
  162. }
  163. )
  164. return urlRequest
  165. }
  166. // MARK: - Test Execution and Verification
  167. func executeTest(
  168. cachePolicy: URLRequest.CachePolicy,
  169. cacheControl: String,
  170. shouldReturnCachedResponse: Bool)
  171. {
  172. // Given
  173. let expectation = self.expectation(description: "GET request to httpbin")
  174. var response: HTTPURLResponse?
  175. // When
  176. startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
  177. response = responseResponse
  178. expectation.fulfill()
  179. }
  180. waitForExpectations(timeout: timeout, handler: nil)
  181. // Then
  182. verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
  183. }
  184. func verifyResponse(_ response: HTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
  185. guard let cachedResponseTimestamp = timestamps[cacheControl] else {
  186. XCTFail("cached response timestamp should not be nil")
  187. return
  188. }
  189. if let response = response, let timestamp = response.allHeaderFields["Date"] as? String {
  190. if isCachedResponse {
  191. XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
  192. } else {
  193. XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
  194. }
  195. } else {
  196. XCTFail("response should not be nil")
  197. }
  198. }
  199. // MARK: - Tests
  200. func testURLCacheContainsCachedResponsesForAllRequests() {
  201. // Given
  202. let publicRequest = requests[CacheControl.publicControl]!
  203. let privateRequest = requests[CacheControl.privateControl]!
  204. let maxAgeNonExpiredRequest = requests[CacheControl.maxAgeNonExpired]!
  205. let maxAgeExpiredRequest = requests[CacheControl.maxAgeExpired]!
  206. let noCacheRequest = requests[CacheControl.noCache]!
  207. let noStoreRequest = requests[CacheControl.noStore]!
  208. // When
  209. let publicResponse = urlCache.cachedResponse(for: publicRequest)
  210. let privateResponse = urlCache.cachedResponse(for: privateRequest)
  211. let maxAgeNonExpiredResponse = urlCache.cachedResponse(for: maxAgeNonExpiredRequest)
  212. let maxAgeExpiredResponse = urlCache.cachedResponse(for: maxAgeExpiredRequest)
  213. let noCacheResponse = urlCache.cachedResponse(for: noCacheRequest)
  214. let noStoreResponse = urlCache.cachedResponse(for: noStoreRequest)
  215. // Then
  216. XCTAssertNotNil(publicResponse, "\(CacheControl.publicControl) response should not be nil")
  217. XCTAssertNotNil(privateResponse, "\(CacheControl.privateControl) response should not be nil")
  218. XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.maxAgeNonExpired) response should not be nil")
  219. XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.maxAgeExpired) response should not be nil")
  220. XCTAssertNotNil(noCacheResponse, "\(CacheControl.noCache) response should not be nil")
  221. XCTAssertNil(noStoreResponse, "\(CacheControl.noStore) response should be nil")
  222. }
  223. func testDefaultCachePolicy() {
  224. let cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
  225. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false)
  226. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false)
  227. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  228. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false)
  229. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false)
  230. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  231. }
  232. func testIgnoreLocalCacheDataPolicy() {
  233. let cachePolicy: URLRequest.CachePolicy = .reloadIgnoringLocalCacheData
  234. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false)
  235. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false)
  236. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: false)
  237. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false)
  238. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false)
  239. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  240. }
  241. func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
  242. let cachePolicy: URLRequest.CachePolicy = .returnCacheDataElseLoad
  243. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true)
  244. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true)
  245. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  246. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true)
  247. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true)
  248. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false)
  249. }
  250. func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
  251. let cachePolicy: URLRequest.CachePolicy = .returnCacheDataDontLoad
  252. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true)
  253. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true)
  254. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true)
  255. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true)
  256. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true)
  257. // Given
  258. let expectation = self.expectation(description: "GET request to httpbin")
  259. var response: HTTPURLResponse?
  260. // When
  261. startRequest(cacheControl: CacheControl.noStore, cachePolicy: cachePolicy) { _, responseResponse in
  262. response = responseResponse
  263. expectation.fulfill()
  264. }
  265. waitForExpectations(timeout: timeout, handler: nil)
  266. // Then
  267. XCTAssertNil(response, "response should be nil")
  268. }
  269. }