2
0

CachedResponseHandlerTests.swift 8.6 KB

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