2
0

ImagePrefetcherTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //
  2. // ImagePrefetcherTests.swift
  3. // Kingfisher
  4. //
  5. // Created by Claire Knight <claire.knight@moggytech.co.uk> on 24/02/2016
  6. //
  7. // Copyright (c) 2018 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. import Kingfisher
  28. #if os(macOS)
  29. import AppKit
  30. #else
  31. import UIKit
  32. #endif
  33. class ImagePrefetcherTests: XCTestCase {
  34. override class func setUp() {
  35. super.setUp()
  36. LSNocilla.sharedInstance().start()
  37. }
  38. override class func tearDown() {
  39. super.tearDown()
  40. LSNocilla.sharedInstance().stop()
  41. }
  42. override func setUp() {
  43. super.setUp()
  44. // Put setup code here. This method is called before the invocation of each test method in the class.
  45. cleanDefaultCache()
  46. }
  47. override func tearDown() {
  48. // Put teardown code here. This method is called after the invocation of each test method in the class.
  49. cleanDefaultCache()
  50. super.tearDown()
  51. }
  52. func testPrefetchingImages() {
  53. let expectation = self.expectation(description: "wait for prefetching images")
  54. var urls = [URL]()
  55. for URLString in testKeys {
  56. _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
  57. urls.append(URL(string: URLString)!)
  58. }
  59. var progressCalledCount = 0
  60. let prefetcher = ImagePrefetcher(urls: urls, options: nil,
  61. progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  62. progressCalledCount += 1
  63. },
  64. completionHandler: {(skippedResources, failedResources, completedResources) -> Void in
  65. expectation.fulfill()
  66. XCTAssertEqual(skippedResources.count, 0, "There should be no items skipped.")
  67. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  68. XCTAssertEqual(completedResources.count, urls.count, "All resources prefetching should be completed.")
  69. XCTAssertEqual(progressCalledCount, urls.count, "Progress should be called the same time of download count.")
  70. for url in urls {
  71. XCTAssertTrue(KingfisherManager.shared.cache.imageCachedType(forKey: url.absoluteString).cached)
  72. }
  73. })
  74. prefetcher.start()
  75. waitForExpectations(timeout: 5, handler: nil)
  76. }
  77. func testCancelPrefetching() {
  78. let expectation = self.expectation(description: "wait for prefetching images")
  79. var urls = [URL]()
  80. var responses = [LSStubResponseDSL!]()
  81. for URLString in testKeys {
  82. let response = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)?.delay()
  83. responses.append(response)
  84. urls.append(URL(string: URLString)!)
  85. }
  86. let maxConcurrentCount = 2
  87. let prefetcher = ImagePrefetcher(urls: urls, options: nil,
  88. progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  89. },
  90. completionHandler: {(skippedResources, failedResources, completedResources) -> Void in
  91. XCTAssertEqual(skippedResources.count, 0, "There should be no items skipped.")
  92. XCTAssertEqual(failedResources.count, urls.count, "The failed count should be the same with started downloads due to cancellation.")
  93. XCTAssertEqual(completedResources.count, 0, "None resources prefetching should complete.")
  94. expectation.fulfill()
  95. })
  96. prefetcher.maxConcurrentDownloads = maxConcurrentCount
  97. prefetcher.start()
  98. prefetcher.stop()
  99. delay(0.1) { responses.forEach { _ = $0!.go() } }
  100. waitForExpectations(timeout: 5, handler: nil)
  101. }
  102. func testPrefetcherCouldSkipCachedImages() {
  103. let expectation = self.expectation(description: "wait for prefetching images")
  104. KingfisherManager.shared.cache.store(Image(), forKey: testKeys[0])
  105. var urls = [URL]()
  106. for URLString in testKeys {
  107. _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
  108. urls.append(URL(string: URLString)!)
  109. }
  110. let prefetcher = ImagePrefetcher(urls: urls, options: nil, progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  111. }) { (skippedResources, failedResources, completedResources) -> Void in
  112. expectation.fulfill()
  113. XCTAssertEqual(skippedResources.count, 1, "There should be 1 item skipped.")
  114. XCTAssertEqual(skippedResources[0].downloadURL.absoluteString, testKeys[0], "The correct image key should be skipped.")
  115. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  116. XCTAssertEqual(completedResources.count, urls.count - 1, "All resources prefetching should be completed.")
  117. }
  118. prefetcher.start()
  119. waitForExpectations(timeout: 5, handler: nil)
  120. }
  121. func testPrefetcherForceRefreshDownloadImages() {
  122. let expectation = self.expectation(description: "wait for prefetching images")
  123. // Store an image in cache.
  124. KingfisherManager.shared.cache.store(Image(), forKey: testKeys[0])
  125. var urls = [URL]()
  126. for URLString in testKeys {
  127. _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
  128. urls.append(URL(string: URLString)!)
  129. }
  130. // Use `.ForceRefresh` to download it forcely.
  131. let prefetcher = ImagePrefetcher(urls: urls, options: [.forceRefresh], progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  132. }) { (skippedResources, failedResources, completedResources) -> Void in
  133. expectation.fulfill()
  134. XCTAssertEqual(skippedResources.count, 0, "There should be no item skipped.")
  135. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  136. XCTAssertEqual(completedResources.count, urls.count, "All resources prefetching should be completed.")
  137. }
  138. prefetcher.start()
  139. waitForExpectations(timeout: 5, handler: nil)
  140. }
  141. func testPrefetchWithWrongInitParameters() {
  142. let expectation = self.expectation(description: "wait for prefetching images")
  143. let prefetcher = ImagePrefetcher(urls: [], options: nil, progressBlock: nil) { (skippedResources, failedResources, completedResources) -> Void in
  144. expectation.fulfill()
  145. XCTAssertEqual(skippedResources.count, 0, "There should be no item skipped.")
  146. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  147. XCTAssertEqual(completedResources.count, 0, "There should be no completed downloading.")
  148. }
  149. prefetcher.start()
  150. waitForExpectations(timeout: 5, handler: nil)
  151. }
  152. func testFetchWithProcessor() {
  153. let expectation = self.expectation(description: "wait for prefetching images")
  154. var urls = [URL]()
  155. for URLString in testKeys {
  156. _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)
  157. urls.append(URL(string: URLString)!)
  158. }
  159. let p = RoundCornerImageProcessor(cornerRadius: 20)
  160. func prefetchAgain() {
  161. var progressCalledCount = 0
  162. let prefetcher = ImagePrefetcher(urls: urls, options: [.processor(p)],
  163. progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  164. progressCalledCount += 1
  165. },
  166. completionHandler: {(skippedResources, failedResources, completedResources) -> Void in
  167. XCTAssertEqual(skippedResources.count, urls.count, "There should be one item skipped since it is just prefetched.")
  168. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  169. XCTAssertEqual(completedResources.count, 0, "No need to prefetch anymore")
  170. XCTAssertEqual(progressCalledCount, urls.count, "Progress should be called the same time of download count.")
  171. for url in urls {
  172. XCTAssertTrue(KingfisherManager.shared.cache.imageCachedType(forKey: url.absoluteString, processorIdentifier: p.identifier).cached)
  173. }
  174. expectation.fulfill()
  175. })
  176. prefetcher.start()
  177. }
  178. var progressCalledCount = 0
  179. let prefetcher = ImagePrefetcher(urls: urls, options: [.processor(p)],
  180. progressBlock: { (skippedResources, failedResources, completedResources) -> Void in
  181. progressCalledCount += 1
  182. },
  183. completionHandler: {(skippedResources, failedResources, completedResources) -> Void in
  184. XCTAssertEqual(skippedResources.count, 0, "There should be no items skipped.")
  185. XCTAssertEqual(failedResources.count, 0, "There should be no failed downloading.")
  186. XCTAssertEqual(completedResources.count, urls.count, "All resources prefetching should be completed.")
  187. XCTAssertEqual(progressCalledCount, urls.count, "Progress should be called the same time of download count.")
  188. for url in urls {
  189. XCTAssertTrue(KingfisherManager.shared.cache.imageCachedType(forKey: url.absoluteString, processorIdentifier: p.identifier).cached)
  190. }
  191. prefetchAgain()
  192. })
  193. prefetcher.start()
  194. waitForExpectations(timeout: 5, handler: nil)
  195. }
  196. }