UIImageViewExtensionTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // UIImageViewExtensionTests.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/17.
  6. //
  7. // Copyright (c) 2015 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 UIKit
  27. import XCTest
  28. @testable import Kingfisher
  29. class UIImageViewExtensionTests: XCTestCase {
  30. var imageView: UIImageView!
  31. override class func setUp() {
  32. super.setUp()
  33. LSNocilla.sharedInstance().start()
  34. }
  35. override class func tearDown() {
  36. super.tearDown()
  37. LSNocilla.sharedInstance().stop()
  38. }
  39. override func setUp() {
  40. super.setUp()
  41. // Put setup code here. This method is called before the invocation of each test method in the class.
  42. imageView = UIImageView()
  43. KingfisherManager.sharedManager.downloader = ImageDownloader(name: "testDownloader")
  44. cleanDefaultCache()
  45. }
  46. override func tearDown() {
  47. // Put teardown code here. This method is called after the invocation of each test method in the class.
  48. LSNocilla.sharedInstance().clearStubs()
  49. imageView = nil
  50. cleanDefaultCache()
  51. super.tearDown()
  52. }
  53. func testImageDownloadForImageView() {
  54. let expectation = expectationWithDescription("wait for downloading image")
  55. let URLString = testKeys[0]
  56. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  57. let URL = NSURL(string: URLString)!
  58. var progressBlockIsCalled = false
  59. imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  60. progressBlockIsCalled = true
  61. }) { (image, error, cacheType, imageURL) -> () in
  62. expectation.fulfill()
  63. XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.")
  64. XCTAssert(image != nil, "Downloaded image should exist.")
  65. XCTAssert(image! == testImage, "Downloaded image should be the same as test image.")
  66. XCTAssert(self.imageView.image! == testImage, "Downloaded image should be already set to the image property.")
  67. XCTAssert(self.imageView.kf_webURL == imageURL, "Web URL should equal to the downloaded url.")
  68. XCTAssert(cacheType == .None, "The cache type should be none here. This image was just downloaded.")
  69. }
  70. waitForExpectationsWithTimeout(5, handler: nil)
  71. }
  72. func testImageDownloadWithResourceForImageView() {
  73. let expectation = expectationWithDescription("wait for downloading image")
  74. let URLString = testKeys[0]
  75. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  76. let URL = NSURL(string: URLString)!
  77. let resource = Resource(downloadURL: URL)
  78. var progressBlockIsCalled = false
  79. imageView.kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  80. progressBlockIsCalled = true
  81. }) { (image, error, cacheType, imageURL) -> () in
  82. expectation.fulfill()
  83. XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.")
  84. XCTAssert(image != nil, "Downloaded image should exist.")
  85. XCTAssert(image! == testImage, "Downloaded image should be the same as test image.")
  86. XCTAssert(self.imageView.image! == testImage, "Downloaded image should be already set to the image property.")
  87. XCTAssert(self.imageView.kf_webURL == imageURL, "Web URL should equal to the downloaded url.")
  88. XCTAssert(cacheType == .None, "The cache type should be none here. This image was just downloaded.")
  89. }
  90. waitForExpectationsWithTimeout(5, handler: nil)
  91. }
  92. func testImageDownloadCancelForImageView() {
  93. let expectation = expectationWithDescription("wait for downloading image")
  94. let URLString = testKeys[0]
  95. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  96. let URL = NSURL(string: URLString)!
  97. var progressBlockIsCalled = false
  98. var completionBlockIsCalled = false
  99. let task = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  100. progressBlockIsCalled = true
  101. }) { (image, error, cacheType, imageURL) -> () in
  102. completionBlockIsCalled = true
  103. }
  104. task.cancel()
  105. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.09)), dispatch_get_main_queue()) { () -> Void in
  106. expectation.fulfill()
  107. XCTAssert(progressBlockIsCalled == false, "ProgressBlock should not be called since it is canceled.")
  108. XCTAssert(completionBlockIsCalled == false, "CompletionBlock should not be called since it is canceled.")
  109. }
  110. waitForExpectationsWithTimeout(5, handler: nil)
  111. }
  112. func testImageDownloadCancelForImageViewAfterRequestStarted() {
  113. let expectation = expectationWithDescription("wait for downloading image")
  114. let URLString = testKeys[0]
  115. let stub = stubRequest("GET", URLString).andReturn(200).withBody(testImageData).delay()
  116. let URL = NSURL(string: URLString)!
  117. var progressBlockIsCalled = false
  118. var completionBlockIsCalled = false
  119. let task = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  120. progressBlockIsCalled = true
  121. }) { (image, error, cacheType, imageURL) -> () in
  122. XCTAssertNotNil(error)
  123. XCTAssertEqual(error?.code, NSURLErrorCancelled)
  124. completionBlockIsCalled = true
  125. }
  126. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.1)), dispatch_get_main_queue()) { () -> Void in
  127. task.cancel()
  128. stub.go()
  129. }
  130. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.2)), dispatch_get_main_queue()) { () -> Void in
  131. expectation.fulfill()
  132. XCTAssert(progressBlockIsCalled == false, "ProgressBlock should not be called since it is canceled.")
  133. XCTAssert(completionBlockIsCalled == true, "CompletionBlock should not be called since it is canceled.")
  134. }
  135. waitForExpectationsWithTimeout(5, handler: nil)
  136. }
  137. func testImageDownloadCancelPartialTaskBeforeRequest() {
  138. let expectation = expectationWithDescription("wait for downloading image")
  139. let URLString = testKeys[0]
  140. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  141. let URL = NSURL(string: URLString)!
  142. var task1Completion = false
  143. var task2Completion = false
  144. var task3Completion = false
  145. let task1 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  146. }) { (image, error, cacheType, imageURL) -> () in
  147. task1Completion = true
  148. }
  149. let _ = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  150. }) { (image, error, cacheType, imageURL) -> () in
  151. XCTAssertNotNil(image)
  152. task2Completion = true
  153. }
  154. let _ = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  155. }) { (image, error, cacheType, imageURL) -> () in
  156. XCTAssertNotNil(image)
  157. task3Completion = true
  158. }
  159. task1.cancel()
  160. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.2)), dispatch_get_main_queue()) { () -> Void in
  161. expectation.fulfill()
  162. XCTAssert(task1Completion == false, "Task 1 should be not completed since it is cancelled before downloading started.")
  163. XCTAssert(task2Completion == true, "Task 2 should be completed.")
  164. XCTAssert(task3Completion == true, "Task 3 should be completed.")
  165. }
  166. waitForExpectationsWithTimeout(5, handler: nil)
  167. }
  168. func testImageDownloadCancelPartialTaskAfterRequestStarted() {
  169. let expectation = expectationWithDescription("wait for downloading image")
  170. let URLString = testKeys[0]
  171. let stub = stubRequest("GET", URLString).andReturn(200).withBody(testImageData).delay()
  172. let URL = NSURL(string: URLString)!
  173. var task1Completion = false
  174. var task2Completion = false
  175. var task3Completion = false
  176. let task1 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  177. }) { (image, error, cacheType, imageURL) -> () in
  178. XCTAssertNotNil(image)
  179. task1Completion = true
  180. }
  181. let _ = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  182. }) { (image, error, cacheType, imageURL) -> () in
  183. XCTAssertNotNil(image)
  184. task2Completion = true
  185. }
  186. let _ = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  187. }) { (image, error, cacheType, imageURL) -> () in
  188. XCTAssertNotNil(image)
  189. task3Completion = true
  190. }
  191. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.1)), dispatch_get_main_queue()) { () -> Void in
  192. task1.cancel()
  193. stub.go()
  194. }
  195. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.2)), dispatch_get_main_queue()) { () -> Void in
  196. expectation.fulfill()
  197. XCTAssert(task1Completion == true, "Task 1 should be completed since task 2 and 3 are not cancelled and they are sharing the same downloading process.")
  198. XCTAssert(task2Completion == true, "Task 2 should be completed.")
  199. XCTAssert(task3Completion == true, "Task 3 should be completed.")
  200. }
  201. waitForExpectationsWithTimeout(5, handler: nil)
  202. }
  203. func testImageDownloadCancelAllTasksAfterRequestStarted() {
  204. let expectation = expectationWithDescription("wait for downloading image")
  205. let URLString = testKeys[0]
  206. let stub = stubRequest("GET", URLString).andReturn(200).withBody(testImageData).delay()
  207. let URL = NSURL(string: URLString)!
  208. var task1Completion = false
  209. var task2Completion = false
  210. var task3Completion = false
  211. let task1 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  212. }) { (image, error, cacheType, imageURL) -> () in
  213. XCTAssertNotNil(error)
  214. XCTAssertEqual(error?.code, NSURLErrorCancelled)
  215. task1Completion = true
  216. }
  217. let task2 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  218. }) { (image, error, cacheType, imageURL) -> () in
  219. XCTAssertNotNil(error)
  220. XCTAssertEqual(error?.code, NSURLErrorCancelled)
  221. task2Completion = true
  222. }
  223. let task3 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  224. }) { (image, error, cacheType, imageURL) -> () in
  225. XCTAssertNotNil(error)
  226. XCTAssertEqual(error?.code, NSURLErrorCancelled)
  227. task3Completion = true
  228. }
  229. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.1)), dispatch_get_main_queue()) { () -> Void in
  230. task1.cancel()
  231. task2.cancel()
  232. task3.cancel()
  233. stub.go()
  234. }
  235. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.2)), dispatch_get_main_queue()) { () -> Void in
  236. expectation.fulfill()
  237. XCTAssert(task1Completion == true, "Task 1 should be completed with error.")
  238. XCTAssert(task2Completion == true, "Task 2 should be completed with error.")
  239. XCTAssert(task3Completion == true, "Task 3 should be completed with error.")
  240. }
  241. waitForExpectationsWithTimeout(5, handler: nil)
  242. }
  243. func testImageDownalodMultipleCaches() {
  244. let cache1 = ImageCache(name: "cache1")
  245. let cache2 = ImageCache(name: "cache2")
  246. cache1.clearDiskCache(true)
  247. cache2.clearDiskCache(true)
  248. let expectation = expectationWithDescription("wait for downloading image")
  249. let URLString = testKeys[0]
  250. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  251. let URL = NSURL(string: URLString)!
  252. imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: [.TargetCache(cache1)], progressBlock: { (receivedSize, totalSize) -> () in
  253. }) { (image, error, cacheType, imageURL) -> () in
  254. XCTAssertTrue(cache1.isImageCachedForKey(URLString).cached, "This image should be cached in cache1.")
  255. XCTAssertFalse(cache2.isImageCachedForKey(URLString).cached, "This image should not be cached in cache2.")
  256. XCTAssertFalse(KingfisherManager.sharedManager.cache.isImageCachedForKey(URLString).cached, "This image should not be cached in default cache.")
  257. self.imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: [.TargetCache(cache2)], progressBlock: { (receivedSize, totalSize) -> () in
  258. }, completionHandler: { (image, error, cacheType, imageURL) -> () in
  259. XCTAssertTrue(cache1.isImageCachedForKey(URLString).cached, "This image should be cached in cache1.")
  260. XCTAssertTrue(cache2.isImageCachedForKey(URLString).cached, "This image should be cached in cache2.")
  261. XCTAssertFalse(KingfisherManager.sharedManager.cache.isImageCachedForKey(URLString).cached, "This image should not be cached in default cache.")
  262. clearCaches([cache1, cache2])
  263. expectation.fulfill()
  264. })
  265. }
  266. waitForExpectationsWithTimeout(5, handler: { (error) -> Void in
  267. clearCaches([cache1, cache2])
  268. })
  269. }
  270. func testIndicatorViewExisting() {
  271. imageView.kf_showIndicatorWhenLoading = true
  272. XCTAssertNotNil(imageView.kf_indicator, "The indicator view should exist when showIndicatorWhenLoading is true")
  273. imageView.kf_showIndicatorWhenLoading = false
  274. XCTAssertNil(imageView.kf_indicator, "The indicator view should be removed when showIndicatorWhenLoading set to false")
  275. }
  276. func testIndicatorViewAnimating() {
  277. imageView.kf_showIndicatorWhenLoading = true
  278. let expectation = expectationWithDescription("wait for downloading image")
  279. let URLString = testKeys[0]
  280. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  281. let URL = NSURL(string: URLString)!
  282. imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  283. let indicator = self.imageView.kf_indicator
  284. XCTAssertNotNil(indicator, "The indicator view should exist when showIndicatorWhenLoading is true")
  285. XCTAssertTrue(indicator!.isAnimating(), "The indicator should be animating when loading")
  286. }) { (image, error, cacheType, imageURL) -> () in
  287. let indicator = self.imageView.kf_indicator
  288. XCTAssertFalse(indicator!.isAnimating(), "The indicator should stop after loading")
  289. expectation.fulfill()
  290. }
  291. waitForExpectationsWithTimeout(5, handler: nil)
  292. }
  293. func testCacnelImageTask() {
  294. let expectation = expectationWithDescription("wait for downloading image")
  295. let URLString = testKeys[0]
  296. let stub = stubRequest("GET", URLString).andReturn(200).withBody(testImageData).delay()
  297. let URL = NSURL(string: URLString)!
  298. imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
  299. XCTFail("Progress block should not be called.")
  300. }) { (image, error, cacheType, imageURL) -> () in
  301. XCTAssertNotNil(error)
  302. XCTAssertEqual(error?.code, NSURLErrorCancelled)
  303. expectation.fulfill()
  304. }
  305. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.1)), dispatch_get_main_queue()) { () -> Void in
  306. self.imageView.kf_cancelDownloadTask()
  307. stub.go()
  308. }
  309. waitForExpectationsWithTimeout(5, handler: nil)
  310. }
  311. }