RetryStrategyTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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: 3, handler: nil)
  86. }
  87. // MARK: - DelayRetryStrategy Tests
  88. func testDelayRetryStrategyExceededCount() {
  89. let exp = expectation(description: #function)
  90. let blockCalled: ActorArray<Bool> = ActorArray([])
  91. let source = Source.network(URL(string: "url")!)
  92. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  93. let group = DispatchGroup()
  94. group.enter()
  95. let context1 = RetryContext(
  96. source: source,
  97. error: .responseError(reason: .URLSessionError(error: E()))
  98. )
  99. retry.retry(context: context1) { decision in
  100. guard case RetryDecision.retry(let userInfo) = decision else {
  101. XCTFail("The decision should be `retry`")
  102. return
  103. }
  104. XCTAssertNil(userInfo)
  105. Task {
  106. await blockCalled.append(true)
  107. group.leave()
  108. }
  109. }
  110. group.enter()
  111. let context2 = RetryContext(
  112. source: source,
  113. error: .responseError(reason: .URLSessionError(error: E()))
  114. )
  115. context2.increaseRetryCount() // 1
  116. context2.increaseRetryCount() // 2
  117. context2.increaseRetryCount() // 3
  118. retry.retry(context: context2) { decision in
  119. guard case RetryDecision.stop = decision else {
  120. XCTFail("The decision should be `stop`")
  121. return
  122. }
  123. Task {
  124. await blockCalled.append(true)
  125. group.leave()
  126. }
  127. }
  128. group.notify(queue: .main) {
  129. Task {
  130. let result = await blockCalled.value
  131. XCTAssertEqual(result.count, 2)
  132. XCTAssertTrue(result.allSatisfy { $0 })
  133. exp.fulfill()
  134. }
  135. }
  136. waitForExpectations(timeout: 3, handler: nil)
  137. }
  138. func testDelayRetryStrategyNotRetryForErrorReason() {
  139. let exp = expectation(description: #function)
  140. // Only non-user cancel error && response error should be retied.
  141. let blockCalled: ActorArray<Bool> = ActorArray([])
  142. let source = Source.network(URL(string: "url")!)
  143. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  144. let task = URLSession.shared.dataTask(with: URL(string: "url")!)
  145. let group = DispatchGroup()
  146. group.enter()
  147. let context1 = RetryContext(
  148. source: source,
  149. error: .requestError(reason: .taskCancelled(task: .init(task: task), token: .init()))
  150. )
  151. retry.retry(context: context1) { decision in
  152. guard case RetryDecision.stop = decision else {
  153. XCTFail("The decision should be `stop` if user cancelled the task.")
  154. return
  155. }
  156. Task {
  157. await blockCalled.append(true)
  158. group.leave()
  159. }
  160. }
  161. group.enter()
  162. let context2 = RetryContext(
  163. source: source,
  164. error: .cacheError(reason: .imageNotExisting(key: "any_key"))
  165. )
  166. retry.retry(context: context2) { decision in
  167. guard case RetryDecision.stop = decision else {
  168. XCTFail("The decision should be `stop` if the error type is not response error.")
  169. return
  170. }
  171. Task {
  172. await blockCalled.append(true)
  173. group.leave()
  174. }
  175. }
  176. group.notify(queue: .main) {
  177. Task {
  178. let result = await blockCalled.value
  179. XCTAssertEqual(result.count, 2)
  180. XCTAssertTrue(result.allSatisfy { $0 })
  181. exp.fulfill()
  182. }
  183. }
  184. waitForExpectations(timeout: 3, handler: nil)
  185. }
  186. func testDelayRetryStrategyDidRetried() {
  187. let exp = expectation(description: #function)
  188. let called = ActorBox(false)
  189. let source = Source.network(URL(string: "url")!)
  190. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  191. let context = RetryContext(
  192. source: source,
  193. error: .responseError(reason: .URLSessionError(error: E()))
  194. )
  195. retry.retry(context: context) { decision in
  196. guard case RetryDecision.retry = decision else {
  197. XCTFail("The decision should be `retry`.")
  198. return
  199. }
  200. Task {
  201. await called.setValue(true)
  202. let result = await called.value
  203. XCTAssertTrue(result)
  204. exp.fulfill()
  205. }
  206. }
  207. waitForExpectations(timeout: 3, handler: nil)
  208. }
  209. // MARK: - NetworkRetryStrategy Tests
  210. func testNetworkRetryStrategyRetriesImmediatelyWhenConnected() {
  211. let exp = expectation(description: #function)
  212. let source = Source.network(URL(string: "url")!)
  213. let networkMonitor = TestNetworkMonitor(isConnected: true)
  214. let retry = NetworkRetryStrategy(networkMonitor: networkMonitor)
  215. let context = RetryContext(
  216. source: source,
  217. error: .responseError(reason: .URLSessionError(error: E()))
  218. )
  219. retry.retry(context: context) { decision in
  220. guard case RetryDecision.retry(let userInfo) = decision else {
  221. XCTFail("The decision should be `retry` when network is connected")
  222. return
  223. }
  224. XCTAssertNil(userInfo)
  225. exp.fulfill()
  226. }
  227. waitForExpectations(timeout: 1, handler: nil)
  228. }
  229. func testNetworkRetryStrategyStopsForTaskCancelled() {
  230. let exp = expectation(description: #function)
  231. let source = Source.network(URL(string: "url")!)
  232. let networkMonitor = TestNetworkMonitor(isConnected: true)
  233. let retry = NetworkRetryStrategy(networkMonitor: networkMonitor)
  234. let task = URLSession.shared.dataTask(with: URL(string: "url")!)
  235. let context = RetryContext(
  236. source: source,
  237. error: .requestError(reason: .taskCancelled(task: .init(task: task), token: .init()))
  238. )
  239. retry.retry(context: context) { decision in
  240. guard case RetryDecision.stop = decision else {
  241. XCTFail("The decision should be `stop` if user cancelled the task")
  242. return
  243. }
  244. exp.fulfill()
  245. }
  246. waitForExpectations(timeout: 1, handler: nil)
  247. }
  248. func testNetworkRetryStrategyStopsForNonResponseError() {
  249. let exp = expectation(description: #function)
  250. let source = Source.network(URL(string: "url")!)
  251. let networkMonitor = TestNetworkMonitor(isConnected: true)
  252. let retry = NetworkRetryStrategy(networkMonitor: networkMonitor)
  253. let context = RetryContext(
  254. source: source,
  255. error: .cacheError(reason: .imageNotExisting(key: "any_key"))
  256. )
  257. retry.retry(context: context) { decision in
  258. guard case RetryDecision.stop = decision else {
  259. XCTFail("The decision should be `stop` if the error type is not response error")
  260. return
  261. }
  262. exp.fulfill()
  263. }
  264. waitForExpectations(timeout: 1, handler: nil)
  265. }
  266. func testNetworkRetryStrategyWithTimeout() {
  267. let exp = expectation(description: #function)
  268. let source = Source.network(URL(string: "url")!)
  269. let networkMonitor = TestNetworkMonitor(isConnected: false)
  270. let retry = NetworkRetryStrategy(timeoutInterval: 0.1, networkMonitor: networkMonitor)
  271. let context = RetryContext(
  272. source: source,
  273. error: .responseError(reason: .URLSessionError(error: E()))
  274. )
  275. // Test timeout behavior when network is disconnected
  276. retry.retry(context: context) { decision in
  277. guard case RetryDecision.stop = decision else {
  278. XCTFail("The decision should be `stop` after timeout")
  279. return
  280. }
  281. exp.fulfill()
  282. }
  283. waitForExpectations(timeout: 1, handler: nil)
  284. }
  285. func testNetworkRetryStrategyWaitsForReconnection() {
  286. let exp = expectation(description: #function)
  287. let source = Source.network(URL(string: "url")!)
  288. let networkMonitor = TestNetworkMonitor(isConnected: false)
  289. let retry = NetworkRetryStrategy(networkMonitor: networkMonitor)
  290. let context = RetryContext(
  291. source: source,
  292. error: .responseError(reason: .URLSessionError(error: E()))
  293. )
  294. // Start retry when network is disconnected - should wait for reconnection
  295. retry.retry(context: context) { decision in
  296. guard case RetryDecision.retry(let userInfo) = decision else {
  297. XCTFail("The decision should be `retry` when network reconnects")
  298. return
  299. }
  300. XCTAssertNotNil(userInfo) // Should contain the observer
  301. exp.fulfill()
  302. }
  303. // Simulate network reconnection after a short delay
  304. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  305. networkMonitor.simulateNetworkChange(isConnected: true)
  306. }
  307. waitForExpectations(timeout: 1, handler: nil)
  308. }
  309. func testNetworkRetryStrategyCancelsPreviousObserver() {
  310. let exp = expectation(description: #function)
  311. let source = Source.network(URL(string: "url")!)
  312. let networkMonitor = TestNetworkMonitor(isConnected: false)
  313. let retry = NetworkRetryStrategy(networkMonitor: networkMonitor)
  314. let context = RetryContext(
  315. source: source,
  316. error: .responseError(reason: .URLSessionError(error: E()))
  317. )
  318. // First retry attempt - should create an observer
  319. retry.retry(context: context) { decision in
  320. // This should not be called since network is disconnected initially
  321. XCTFail("First callback should not be called immediately when network is disconnected")
  322. }
  323. // Second retry attempt - should cancel previous observer
  324. retry.retry(context: context) { decision in
  325. guard case RetryDecision.retry(let userInfo) = decision else {
  326. XCTFail("The second decision should be `retry`")
  327. return
  328. }
  329. XCTAssertNotNil(userInfo)
  330. exp.fulfill()
  331. }
  332. // Simulate network reconnection
  333. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  334. networkMonitor.simulateNetworkChange(isConnected: true)
  335. }
  336. waitForExpectations(timeout: 1, handler: nil)
  337. }
  338. }
  339. private struct E: Error {}
  340. final class StubRetryStrategy: RetryStrategy, @unchecked Sendable {
  341. let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.StubRetryStrategy")
  342. var _count = 0
  343. var count: Int {
  344. get { queue.sync { _count } }
  345. set { queue.sync { _count = newValue } }
  346. }
  347. func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
  348. if count == 0 {
  349. XCTAssertNil(context.userInfo)
  350. } else {
  351. XCTAssertEqual(context.userInfo as! Int, count)
  352. }
  353. XCTAssertEqual(context.retriedCount, count)
  354. count += 1
  355. if count == 3 {
  356. retryHandler(.stop)
  357. } else {
  358. retryHandler(.retry(userInfo: count))
  359. }
  360. }
  361. }
  362. // MARK: - Test Network Monitoring Implementations
  363. /// A test implementation of NetworkMonitoring that allows controlling network state for testing.
  364. final class TestNetworkMonitor: @unchecked Sendable, NetworkMonitoring {
  365. private let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.TestNetworkMonitor", attributes: .concurrent)
  366. private var _isConnected: Bool
  367. private var observers: [TestNetworkObserver] = []
  368. var isConnected: Bool {
  369. get { queue.sync { _isConnected } }
  370. set { queue.sync(flags: .barrier) { _isConnected = newValue } }
  371. }
  372. init(isConnected: Bool = true) {
  373. self._isConnected = isConnected
  374. }
  375. func observeConnectivity(timeoutInterval: TimeInterval?, callback: @escaping @Sendable (Bool) -> Void) -> NetworkObserver {
  376. let observer = TestNetworkObserver(
  377. timeoutInterval: timeoutInterval,
  378. callback: callback,
  379. monitor: self
  380. )
  381. queue.sync(flags: .barrier) {
  382. observers.append(observer)
  383. }
  384. return observer
  385. }
  386. /// Simulates network state change and notifies all observers.
  387. func simulateNetworkChange(isConnected: Bool) {
  388. queue.sync(flags: .barrier) {
  389. _isConnected = isConnected
  390. let activeObservers = observers
  391. observers.removeAll()
  392. DispatchQueue.main.async {
  393. activeObservers.forEach { $0.notify(isConnected: isConnected) }
  394. }
  395. }
  396. }
  397. /// Removes an observer from the list.
  398. func removeObserver(_ observer: TestNetworkObserver) {
  399. queue.sync(flags: .barrier) {
  400. observers.removeAll { $0 === observer }
  401. }
  402. }
  403. }
  404. /// Test implementation of NetworkObserver for testing purposes.
  405. final class TestNetworkObserver: @unchecked Sendable, NetworkObserver {
  406. let timeoutInterval: TimeInterval?
  407. let callback: @Sendable (Bool) -> Void
  408. private weak var monitor: TestNetworkMonitor?
  409. private var timeoutWorkItem: DispatchWorkItem?
  410. private let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.TestNetworkObserver", qos: .utility)
  411. init(timeoutInterval: TimeInterval?, callback: @escaping @Sendable (Bool) -> Void, monitor: TestNetworkMonitor) {
  412. self.timeoutInterval = timeoutInterval
  413. self.callback = callback
  414. self.monitor = monitor
  415. // Set up timeout if specified
  416. if let timeoutInterval = timeoutInterval {
  417. let workItem = DispatchWorkItem { [weak self] in
  418. self?.notify(isConnected: false)
  419. }
  420. timeoutWorkItem = workItem
  421. queue.asyncAfter(deadline: .now() + timeoutInterval, execute: workItem)
  422. }
  423. }
  424. func notify(isConnected: Bool) {
  425. queue.async { [weak self] in
  426. guard let self else { return }
  427. // Cancel timeout if we're notifying
  428. timeoutWorkItem?.cancel()
  429. timeoutWorkItem = nil
  430. // Remove from monitor
  431. monitor?.removeObserver(self)
  432. // Call the callback
  433. DispatchQueue.main.async {
  434. self.callback(isConnected)
  435. }
  436. }
  437. }
  438. func cancel() {
  439. queue.async { [weak self] in
  440. guard let self else { return }
  441. // Cancel timeout
  442. timeoutWorkItem?.cancel()
  443. timeoutWorkItem = nil
  444. // Remove from monitor
  445. monitor?.removeObserver(self)
  446. }
  447. }
  448. }