RetryStrategyTests.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. //
  2. // RetryStrategyTests.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/05/06.
  6. //
  7. // Copyright (c) 2020 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import XCTest
  27. @testable import Kingfisher
  28. class RetryStrategyTests: XCTestCase {
  29. var manager: KingfisherManager!
  30. override class func setUp() {
  31. super.setUp()
  32. LSNocilla.sharedInstance().start()
  33. }
  34. override class func tearDown() {
  35. LSNocilla.sharedInstance().stop()
  36. super.tearDown()
  37. }
  38. override func setUpWithError() throws {
  39. try super.setUpWithError()
  40. let uuid = UUID()
  41. let downloader = ImageDownloader(name: "test.manager.\(uuid.uuidString)")
  42. let cache = ImageCache(name: "test.cache.\(uuid.uuidString)")
  43. manager = KingfisherManager(downloader: downloader, cache: cache)
  44. manager.defaultOptions = [.waitForCache]
  45. }
  46. override func tearDownWithError() throws {
  47. LSNocilla.sharedInstance().clearStubs()
  48. clearCaches([manager.cache])
  49. cleanDefaultCache()
  50. manager = nil
  51. try super.tearDownWithError()
  52. }
  53. func testCanCreateRetryStrategy() {
  54. let strategy = DelayRetryStrategy(maxRetryCount: 10, retryInterval: .seconds(5))
  55. XCTAssertEqual(strategy.maxRetryCount, 10)
  56. XCTAssertEqual(strategy.retryInterval.timeInterval(for: 0), 5)
  57. }
  58. func testDelayRetryIntervalCalculating() {
  59. let secondInternal = DelayRetryStrategy.Interval.seconds(10)
  60. XCTAssertEqual(secondInternal.timeInterval(for: 0), 10)
  61. let accumulatedInternal = DelayRetryStrategy.Interval.accumulated(3)
  62. XCTAssertEqual(accumulatedInternal.timeInterval(for: 0), 3)
  63. XCTAssertEqual(accumulatedInternal.timeInterval(for: 1), 6)
  64. XCTAssertEqual(accumulatedInternal.timeInterval(for: 2), 9)
  65. XCTAssertEqual(accumulatedInternal.timeInterval(for: 3), 12)
  66. let customInternal = DelayRetryStrategy.Interval.custom { TimeInterval($0 * 2) }
  67. XCTAssertEqual(customInternal.timeInterval(for: 0), 0)
  68. XCTAssertEqual(customInternal.timeInterval(for: 1), 2)
  69. XCTAssertEqual(customInternal.timeInterval(for: 2), 4)
  70. XCTAssertEqual(customInternal.timeInterval(for: 3), 6)
  71. }
  72. func testKingfisherManagerCanRetry() {
  73. let exp = expectation(description: #function)
  74. let brokenURL = URL(string: "brokenurl")!
  75. stub(brokenURL, data: Data())
  76. let retry = StubRetryStrategy()
  77. _ = manager.retrieveImage(
  78. with: .network(brokenURL),
  79. options: [.retryStrategy(retry)],
  80. completionHandler: { result in
  81. XCTAssertEqual(retry.count, 3)
  82. exp.fulfill()
  83. }
  84. )
  85. waitForExpectations(timeout: 1, handler: nil)
  86. }
  87. func testDelayRetryStrategyExceededCount() {
  88. let exp = expectation(description: #function)
  89. let blockCalled: ActorArray<Bool> = ActorArray([])
  90. let source = Source.network(URL(string: "url")!)
  91. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  92. let group = DispatchGroup()
  93. group.enter()
  94. let context1 = RetryContext(
  95. source: source,
  96. error: .responseError(reason: .URLSessionError(error: E()))
  97. )
  98. retry.retry(context: context1) { decision in
  99. guard case RetryDecision.retry(let userInfo) = decision else {
  100. XCTFail("The decision should be `retry`")
  101. return
  102. }
  103. XCTAssertNil(userInfo)
  104. Task {
  105. await blockCalled.append(true)
  106. group.leave()
  107. }
  108. }
  109. group.enter()
  110. let context2 = RetryContext(
  111. source: source,
  112. error: .responseError(reason: .URLSessionError(error: E()))
  113. )
  114. context2.increaseRetryCount() // 1
  115. context2.increaseRetryCount() // 2
  116. context2.increaseRetryCount() // 3
  117. retry.retry(context: context2) { decision in
  118. guard case RetryDecision.stop = decision else {
  119. XCTFail("The decision should be `stop`")
  120. return
  121. }
  122. Task {
  123. await blockCalled.append(true)
  124. group.leave()
  125. }
  126. }
  127. group.notify(queue: .main) {
  128. Task {
  129. let result = await blockCalled.value
  130. XCTAssertEqual(result.count, 2)
  131. XCTAssertTrue(result.allSatisfy { $0 })
  132. exp.fulfill()
  133. }
  134. }
  135. waitForExpectations(timeout: 1, handler: nil)
  136. }
  137. func testDelayRetryStrategyNotRetryForErrorReason() {
  138. let exp = expectation(description: #function)
  139. // Only non-user cancel error && response error should be retied.
  140. let blockCalled: ActorArray<Bool> = ActorArray([])
  141. let source = Source.network(URL(string: "url")!)
  142. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  143. let task = URLSession.shared.dataTask(with: URL(string: "url")!)
  144. let group = DispatchGroup()
  145. group.enter()
  146. let context1 = RetryContext(
  147. source: source,
  148. error: .requestError(reason: .taskCancelled(task: .init(task: task), token: .init()))
  149. )
  150. retry.retry(context: context1) { decision in
  151. guard case RetryDecision.stop = decision else {
  152. XCTFail("The decision should be `stop` if user cancelled the task.")
  153. return
  154. }
  155. Task {
  156. await blockCalled.append(true)
  157. group.leave()
  158. }
  159. }
  160. group.enter()
  161. let context2 = RetryContext(
  162. source: source,
  163. error: .cacheError(reason: .imageNotExisting(key: "any_key"))
  164. )
  165. retry.retry(context: context2) { decision in
  166. guard case RetryDecision.stop = decision else {
  167. XCTFail("The decision should be `stop` if the error type is not response error.")
  168. return
  169. }
  170. Task {
  171. await blockCalled.append(true)
  172. group.leave()
  173. }
  174. }
  175. group.notify(queue: .main) {
  176. Task {
  177. let result = await blockCalled.value
  178. XCTAssertEqual(result.count, 2)
  179. XCTAssertTrue(result.allSatisfy { $0 })
  180. exp.fulfill()
  181. }
  182. }
  183. waitForExpectations(timeout: 1, handler: nil)
  184. }
  185. func testDelayRetryStrategyDidRetried() {
  186. let called = ActorBox(false)
  187. let source = Source.network(URL(string: "url")!)
  188. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  189. let context = RetryContext(
  190. source: source,
  191. error: .responseError(reason: .URLSessionError(error: E()))
  192. )
  193. retry.retry(context: context) { decision in
  194. guard case RetryDecision.retry = decision else {
  195. XCTFail("The decision should be `retry`.")
  196. return
  197. }
  198. Task {
  199. await called.setValue(true)
  200. }
  201. }
  202. Task {
  203. let result = await called.value
  204. XCTAssertTrue(result)
  205. }
  206. }
  207. }
  208. private struct E: Error {}
  209. final class StubRetryStrategy: RetryStrategy, @unchecked Sendable {
  210. let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.StubRetryStrategy")
  211. var _count = 0
  212. var count: Int {
  213. get { queue.sync { _count } }
  214. set { queue.sync { _count = newValue } }
  215. }
  216. func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
  217. if count == 0 {
  218. XCTAssertNil(context.userInfo)
  219. } else {
  220. XCTAssertEqual(context.userInfo as! Int, count)
  221. }
  222. XCTAssertEqual(context.retriedCount, count)
  223. count += 1
  224. if count == 3 {
  225. retryHandler(.stop)
  226. } else {
  227. retryHandler(.retry(userInfo: count))
  228. }
  229. }
  230. }