CacheTests.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //
  2. // CacheTests.swift
  3. //
  4. // Copyright (c) 2014-2016 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. /**
  28. This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
  29. are meant to cover the main cases of `Cache-Control` header usage, but are by no means exhaustive.
  30. These tests work as follows:
  31. - Set up an `NSURLCache`
  32. - Set up an `Alamofire.Manager`
  33. - Execute requests for all `Cache-Control` header values to prime the `NSURLCache` with cached responses
  34. - Start up a new test
  35. - Execute another round of the same requests with a given `NSURLRequestCachePolicy`
  36. - Verify whether the response came from the cache or from the network
  37. - This is determined by whether the cached response timestamp matches the new response timestamp
  38. An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
  39. a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
  40. The different tests below reflect and demonstrate this behavior.
  41. For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
  42. */
  43. class CacheTestCase: BaseTestCase {
  44. // MARK: -
  45. struct CacheControl {
  46. static let Public = "public"
  47. static let Private = "private"
  48. static let MaxAgeNonExpired = "max-age=3600"
  49. static let MaxAgeExpired = "max-age=0"
  50. static let NoCache = "no-cache"
  51. static let NoStore = "no-store"
  52. static var allValues: [String] {
  53. return [
  54. CacheControl.Public,
  55. CacheControl.Private,
  56. CacheControl.MaxAgeNonExpired,
  57. CacheControl.MaxAgeExpired,
  58. CacheControl.NoCache,
  59. CacheControl.NoStore
  60. ]
  61. }
  62. }
  63. // MARK: - Properties
  64. var URLCache: NSURLCache!
  65. var manager: Manager!
  66. let URLString = "https://httpbin.org/response-headers"
  67. let requestTimeout: NSTimeInterval = 30
  68. var requests: [String: NSURLRequest] = [:]
  69. var timestamps: [String: String] = [:]
  70. // MARK: - Setup and Teardown
  71. override func setUp() {
  72. super.setUp()
  73. URLCache = {
  74. let capacity = 50 * 1024 * 1024 // MBs
  75. let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
  76. return URLCache
  77. }()
  78. manager = {
  79. let configuration: NSURLSessionConfiguration = {
  80. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  81. configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
  82. configuration.requestCachePolicy = .UseProtocolCachePolicy
  83. configuration.URLCache = URLCache
  84. return configuration
  85. }()
  86. let manager = Manager(configuration: configuration)
  87. return manager
  88. }()
  89. primeCachedResponses()
  90. }
  91. override func tearDown() {
  92. super.tearDown()
  93. requests.removeAll()
  94. timestamps.removeAll()
  95. URLCache.removeAllCachedResponses()
  96. }
  97. // MARK: - Cache Priming Methods
  98. /**
  99. Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
  100. This implementation leverages dispatch groups to execute all the requests as well as wait an additional
  101. second before returning. This ensures the cache contains responses for all requests that are at least
  102. one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
  103. or the network based on the timestamp of the response.
  104. */
  105. func primeCachedResponses() {
  106. let dispatchGroup = dispatch_group_create()
  107. let serialQueue = dispatch_queue_create("com.alamofire.cache-tests", DISPATCH_QUEUE_SERIAL)
  108. for cacheControl in CacheControl.allValues {
  109. dispatch_group_enter(dispatchGroup)
  110. let request = startRequest(
  111. cacheControl: cacheControl,
  112. queue: serialQueue,
  113. completion: { _, response in
  114. let timestamp = response!.allHeaderFields["Date"] as! String
  115. self.timestamps[cacheControl] = timestamp
  116. dispatch_group_leave(dispatchGroup)
  117. }
  118. )
  119. requests[cacheControl] = request
  120. }
  121. // Wait for all requests to complete
  122. dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(30.0 * Float(NSEC_PER_SEC))))
  123. // Pause for 2 additional seconds to ensure all timestamps will be different
  124. dispatch_group_enter(dispatchGroup)
  125. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Float(NSEC_PER_SEC))), serialQueue) {
  126. dispatch_group_leave(dispatchGroup)
  127. }
  128. // Wait for our 2 second pause to complete
  129. dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
  130. }
  131. // MARK: - Request Helper Methods
  132. func URLRequest(cacheControl cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
  133. let parameters = ["Cache-Control": cacheControl]
  134. let URL = NSURL(string: URLString)!
  135. let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: requestTimeout)
  136. URLRequest.HTTPMethod = Method.GET.rawValue
  137. return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
  138. }
  139. func startRequest(
  140. cacheControl cacheControl: String,
  141. cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
  142. queue: dispatch_queue_t = dispatch_get_main_queue(),
  143. completion: (NSURLRequest?, NSHTTPURLResponse?) -> Void)
  144. -> NSURLRequest
  145. {
  146. let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
  147. let request = manager.request(urlRequest)
  148. request.response(
  149. queue: queue,
  150. completionHandler: { _, response, data, _ in
  151. completion(request.request, response)
  152. }
  153. )
  154. return urlRequest
  155. }
  156. // MARK: - Test Execution and Verification
  157. func executeTest(
  158. cachePolicy cachePolicy: NSURLRequestCachePolicy,
  159. cacheControl: String,
  160. shouldReturnCachedResponse: Bool)
  161. {
  162. // Given
  163. let expectation = expectationWithDescription("GET request to httpbin")
  164. var response: NSHTTPURLResponse?
  165. // When
  166. startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
  167. response = responseResponse
  168. expectation.fulfill()
  169. }
  170. waitForExpectationsWithTimeout(timeout, handler: nil)
  171. // Then
  172. verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
  173. }
  174. func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
  175. guard let cachedResponseTimestamp = timestamps[cacheControl] else {
  176. XCTFail("cached response timestamp should not be nil")
  177. return
  178. }
  179. if let
  180. response = response,
  181. timestamp = response.allHeaderFields["Date"] as? String
  182. {
  183. if isCachedResponse {
  184. XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
  185. } else {
  186. XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
  187. }
  188. } else {
  189. XCTFail("response should not be nil")
  190. }
  191. }
  192. // MARK: - Cache Helper Methods
  193. private func isCachedResponseForNoStoreHeaderExpected() -> Bool {
  194. #if os(iOS)
  195. if #available(iOS 8.3, *) {
  196. return false
  197. } else {
  198. return true
  199. }
  200. #else
  201. return false
  202. #endif
  203. }
  204. // MARK: - Tests
  205. func testURLCacheContainsCachedResponsesForAllRequests() {
  206. // Given
  207. let publicRequest = requests[CacheControl.Public]!
  208. let privateRequest = requests[CacheControl.Private]!
  209. let maxAgeNonExpiredRequest = requests[CacheControl.MaxAgeNonExpired]!
  210. let maxAgeExpiredRequest = requests[CacheControl.MaxAgeExpired]!
  211. let noCacheRequest = requests[CacheControl.NoCache]!
  212. let noStoreRequest = requests[CacheControl.NoStore]!
  213. // When
  214. let publicResponse = URLCache.cachedResponseForRequest(publicRequest)
  215. let privateResponse = URLCache.cachedResponseForRequest(privateRequest)
  216. let maxAgeNonExpiredResponse = URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
  217. let maxAgeExpiredResponse = URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
  218. let noCacheResponse = URLCache.cachedResponseForRequest(noCacheRequest)
  219. let noStoreResponse = URLCache.cachedResponseForRequest(noStoreRequest)
  220. // Then
  221. XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
  222. XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
  223. XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
  224. XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
  225. XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
  226. if isCachedResponseForNoStoreHeaderExpected() {
  227. XCTAssertNotNil(noStoreResponse, "\(CacheControl.NoStore) response should not be nil")
  228. } else {
  229. XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
  230. }
  231. }
  232. func testDefaultCachePolicy() {
  233. let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
  234. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
  235. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
  236. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
  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 testIgnoreLocalCacheDataPolicy() {
  242. let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
  243. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
  244. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
  245. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
  246. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
  247. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
  248. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
  249. }
  250. func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
  251. let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
  252. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
  253. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, 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. if isCachedResponseForNoStoreHeaderExpected() {
  258. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
  259. } else {
  260. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
  261. }
  262. }
  263. func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
  264. let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
  265. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
  266. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
  267. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
  268. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
  269. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
  270. if isCachedResponseForNoStoreHeaderExpected() {
  271. executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
  272. } else {
  273. // Given
  274. let expectation = expectationWithDescription("GET request to httpbin")
  275. var response: NSHTTPURLResponse?
  276. // When
  277. startRequest(cacheControl: CacheControl.NoStore, cachePolicy: cachePolicy) { _, responseResponse in
  278. response = responseResponse
  279. expectation.fulfill()
  280. }
  281. waitForExpectationsWithTimeout(timeout, handler: nil)
  282. // Then
  283. XCTAssertNil(response, "response should be nil")
  284. }
  285. }
  286. }