RetryStrategyTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 source = Source.network(URL(string: "url")!)
  189. let retry = DelayRetryStrategy(maxRetryCount: 3, retryInterval: .seconds(0))
  190. let context = RetryContext(
  191. source: source,
  192. error: .responseError(reason: .URLSessionError(error: E()))
  193. )
  194. retry.retry(context: context) { decision in
  195. guard case RetryDecision.retry = decision else {
  196. XCTFail("The decision should be `retry`.")
  197. return
  198. }
  199. exp.fulfill()
  200. }
  201. waitForExpectations(timeout: 3, handler: nil)
  202. }
  203. // MARK: - NetworkRetryStrategy Tests
  204. func testNetworkRetryStrategyRetriesImmediatelyWhenConnected() {
  205. let exp = expectation(description: #function)
  206. let source = Source.network(URL(string: "url")!)
  207. let networkMonitor = TestNetworkMonitor(isConnected: true)
  208. let retry = NetworkRetryStrategy(
  209. timeoutInterval: 30,
  210. networkMonitor: networkMonitor
  211. )
  212. let context = RetryContext(
  213. source: source,
  214. error: .responseError(reason: .URLSessionError(error: E()))
  215. )
  216. retry.retry(context: context) { decision in
  217. guard case RetryDecision.retry(let userInfo) = decision else {
  218. XCTFail("The decision should be `retry` when network is connected")
  219. return
  220. }
  221. XCTAssertNil(userInfo)
  222. exp.fulfill()
  223. }
  224. waitForExpectations(timeout: 1, handler: nil)
  225. }
  226. func testNetworkRetryStrategyStopsForTaskCancelled() {
  227. let exp = expectation(description: #function)
  228. let source = Source.network(URL(string: "url")!)
  229. let networkMonitor = TestNetworkMonitor(isConnected: true)
  230. let retry = NetworkRetryStrategy(
  231. timeoutInterval: 30,
  232. networkMonitor: networkMonitor
  233. )
  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(
  253. timeoutInterval: 30,
  254. networkMonitor: networkMonitor
  255. )
  256. let context = RetryContext(
  257. source: source,
  258. error: .cacheError(reason: .imageNotExisting(key: "any_key"))
  259. )
  260. retry.retry(context: context) { decision in
  261. guard case RetryDecision.stop = decision else {
  262. XCTFail("The decision should be `stop` if the error type is not response error")
  263. return
  264. }
  265. exp.fulfill()
  266. }
  267. waitForExpectations(timeout: 1, handler: nil)
  268. }
  269. func testNetworkRetryStrategyWithTimeout() {
  270. let exp = expectation(description: #function)
  271. let source = Source.network(URL(string: "url")!)
  272. let networkMonitor = TestNetworkMonitor(isConnected: false)
  273. let retry = NetworkRetryStrategy(timeoutInterval: 0.1, networkMonitor: networkMonitor)
  274. let context = RetryContext(
  275. source: source,
  276. error: .responseError(reason: .URLSessionError(error: E()))
  277. )
  278. // Test timeout behavior when network is disconnected
  279. retry.retry(context: context) { decision in
  280. guard case RetryDecision.stop = decision else {
  281. XCTFail("The decision should be `stop` after timeout")
  282. return
  283. }
  284. exp.fulfill()
  285. }
  286. waitForExpectations(timeout: 1, handler: nil)
  287. }
  288. func testNetworkRetryStrategyWaitsForReconnection() {
  289. let exp = expectation(description: #function)
  290. let source = Source.network(URL(string: "url")!)
  291. let networkMonitor = TestNetworkMonitor(isConnected: false)
  292. let retry = NetworkRetryStrategy(
  293. timeoutInterval: 30,
  294. networkMonitor: networkMonitor
  295. )
  296. let context = RetryContext(
  297. source: source,
  298. error: .responseError(reason: .URLSessionError(error: E()))
  299. )
  300. // Start retry when network is disconnected - should wait for reconnection
  301. retry.retry(context: context) { decision in
  302. guard case RetryDecision.retry(let userInfo) = decision else {
  303. XCTFail("The decision should be `retry` when network reconnects")
  304. return
  305. }
  306. XCTAssertNotNil(userInfo) // Should contain the observer
  307. exp.fulfill()
  308. }
  309. // Simulate network reconnection after a short delay
  310. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  311. networkMonitor.simulateNetworkChange(isConnected: true)
  312. }
  313. waitForExpectations(timeout: 1, handler: nil)
  314. }
  315. func testNetworkRetryStrategyCancelsPreviousObserver() {
  316. let exp = expectation(description: #function)
  317. let source = Source.network(URL(string: "url")!)
  318. let networkMonitor = TestNetworkMonitor(isConnected: false)
  319. let retry = NetworkRetryStrategy(
  320. timeoutInterval: 30,
  321. networkMonitor: networkMonitor
  322. )
  323. let context = RetryContext(
  324. source: source,
  325. error: .responseError(reason: .URLSessionError(error: E()))
  326. )
  327. // First retry attempt - should create an observer
  328. retry.retry(context: context) { decision in
  329. // This should not be called since network is disconnected initially
  330. XCTFail("First callback should not be called immediately when network is disconnected")
  331. }
  332. // Second retry attempt - should cancel previous observer
  333. retry.retry(context: context) { decision in
  334. guard case RetryDecision.retry(let userInfo) = decision else {
  335. XCTFail("The second decision should be `retry`")
  336. return
  337. }
  338. XCTAssertNotNil(userInfo)
  339. exp.fulfill()
  340. }
  341. // Simulate network reconnection
  342. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  343. networkMonitor.simulateNetworkChange(isConnected: true)
  344. }
  345. waitForExpectations(timeout: 1, handler: nil)
  346. }
  347. }
  348. private struct E: Error {}
  349. final class StubRetryStrategy: RetryStrategy, @unchecked Sendable {
  350. let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.StubRetryStrategy")
  351. var _count = 0
  352. var count: Int {
  353. get { queue.sync { _count } }
  354. set { queue.sync { _count = newValue } }
  355. }
  356. func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
  357. if count == 0 {
  358. XCTAssertNil(context.userInfo)
  359. } else {
  360. XCTAssertEqual(context.userInfo as! Int, count)
  361. }
  362. XCTAssertEqual(context.retriedCount, count)
  363. count += 1
  364. if count == 3 {
  365. retryHandler(.stop)
  366. } else {
  367. retryHandler(.retry(userInfo: count))
  368. }
  369. }
  370. }
  371. // MARK: - Test Network Monitoring Implementations
  372. /// A test implementation of NetworkMonitoring that allows controlling network state for testing.
  373. final class TestNetworkMonitor: @unchecked Sendable, NetworkMonitoring {
  374. private let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.TestNetworkMonitor", attributes: .concurrent)
  375. private var _isConnected: Bool
  376. private var observers: [TestNetworkObserver] = []
  377. var isConnected: Bool {
  378. get { queue.sync { _isConnected } }
  379. set { queue.sync(flags: .barrier) { _isConnected = newValue } }
  380. }
  381. init(isConnected: Bool = true) {
  382. self._isConnected = isConnected
  383. }
  384. func observeConnectivity(timeoutInterval: TimeInterval?, callback: @escaping @Sendable (Bool) -> Void) -> NetworkObserver {
  385. let observer = TestNetworkObserver(
  386. timeoutInterval: timeoutInterval,
  387. callback: callback,
  388. monitor: self
  389. )
  390. queue.sync(flags: .barrier) {
  391. observers.append(observer)
  392. }
  393. return observer
  394. }
  395. /// Simulates network state change and notifies all observers.
  396. func simulateNetworkChange(isConnected: Bool) {
  397. queue.sync(flags: .barrier) {
  398. _isConnected = isConnected
  399. let activeObservers = observers
  400. observers.removeAll()
  401. DispatchQueue.main.async {
  402. activeObservers.forEach { $0.notify(isConnected: isConnected) }
  403. }
  404. }
  405. }
  406. /// Removes an observer from the list.
  407. func removeObserver(_ observer: TestNetworkObserver) {
  408. queue.sync(flags: .barrier) {
  409. observers.removeAll { $0 === observer }
  410. }
  411. }
  412. }
  413. /// Test implementation of NetworkObserver for testing purposes.
  414. final class TestNetworkObserver: @unchecked Sendable, NetworkObserver {
  415. let timeoutInterval: TimeInterval?
  416. let callback: @Sendable (Bool) -> Void
  417. private weak var monitor: TestNetworkMonitor?
  418. private var timeoutWorkItem: DispatchWorkItem?
  419. private let queue = DispatchQueue(label: "com.onevcat.KingfisherTests.TestNetworkObserver", qos: .utility)
  420. init(timeoutInterval: TimeInterval?, callback: @escaping @Sendable (Bool) -> Void, monitor: TestNetworkMonitor) {
  421. self.timeoutInterval = timeoutInterval
  422. self.callback = callback
  423. self.monitor = monitor
  424. // Set up timeout if specified
  425. if let timeoutInterval = timeoutInterval {
  426. let workItem = DispatchWorkItem { [weak self] in
  427. self?.notify(isConnected: false)
  428. }
  429. timeoutWorkItem = workItem
  430. queue.asyncAfter(deadline: .now() + timeoutInterval, execute: workItem)
  431. }
  432. }
  433. func notify(isConnected: Bool) {
  434. queue.async { [weak self] in
  435. guard let self else { return }
  436. // Cancel timeout if we're notifying
  437. timeoutWorkItem?.cancel()
  438. timeoutWorkItem = nil
  439. // Remove from monitor
  440. monitor?.removeObserver(self)
  441. // Call the callback
  442. DispatchQueue.main.async {
  443. self.callback(isConnected)
  444. }
  445. }
  446. }
  447. func cancel() {
  448. queue.async { [weak self] in
  449. guard let self else { return }
  450. // Cancel timeout
  451. timeoutWorkItem?.cancel()
  452. timeoutWorkItem = nil
  453. // Remove from monitor
  454. monitor?.removeObserver(self)
  455. }
  456. }
  457. }