RetryStrategyTests.swift 19 KB

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