ImageViewExtensionTests.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. //
  2. // UIImageViewExtensionTests.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/17.
  6. //
  7. // Copyright (c) 2019 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 ImageViewExtensionTests: XCTestCase {
  29. var imageView: KFCrossPlatformImageView!
  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 setUp() {
  39. super.setUp()
  40. imageView = KFCrossPlatformImageView()
  41. KingfisherManager.shared.downloader = ImageDownloader(name: "testDownloader")
  42. KingfisherManager.shared.defaultOptions = [.waitForCache]
  43. cleanDefaultCache()
  44. }
  45. override func tearDown() {
  46. LSNocilla.sharedInstance().clearStubs()
  47. imageView = nil
  48. cleanDefaultCache()
  49. KingfisherManager.shared.defaultOptions = .empty
  50. super.tearDown()
  51. }
  52. func testImageDownloadForImageView() {
  53. let exp = expectation(description: #function)
  54. let url = testURLs[0]
  55. stub(url, data: testImageData, length: 123)
  56. var progressBlockIsCalled = false
  57. imageView.kf.setImage(
  58. with: url,
  59. progressBlock: { _, _ in
  60. progressBlockIsCalled = true
  61. XCTAssertTrue(Thread.isMainThread)
  62. })
  63. {
  64. result in
  65. XCTAssertTrue(progressBlockIsCalled)
  66. XCTAssertNotNil(result.value)
  67. let value = result.value!
  68. XCTAssertTrue(value.image.renderEqual(to: testImage))
  69. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  70. XCTAssertEqual(value.cacheType, .none)
  71. XCTAssertTrue(Thread.isMainThread)
  72. exp.fulfill()
  73. }
  74. waitForExpectations(timeout: 3, handler: nil)
  75. }
  76. func testImageDownloadCompletionHandlerRunningOnMainQueue() {
  77. let exp = expectation(description: #function)
  78. let url = testURLs[0]
  79. stub(url, data: testImageData)
  80. let customQueue = DispatchQueue(label: "com.kingfisher.testQueue")
  81. imageView.kf.setImage(
  82. with: url,
  83. options: [.callbackQueue(.dispatch(customQueue))],
  84. progressBlock: { _, _ in XCTAssertTrue(Thread.isMainThread) })
  85. {
  86. result in
  87. XCTAssertTrue(Thread.isMainThread)
  88. exp.fulfill()
  89. }
  90. waitForExpectations(timeout: 3, handler: nil)
  91. }
  92. func testImageDownloadWithResourceForImageView() {
  93. let exp = expectation(description: #function)
  94. let url = testURLs[0]
  95. stub(url, data: testImageData, length: 123)
  96. var progressBlockIsCalled = false
  97. let resource = ImageResource(downloadURL: url)
  98. imageView.kf.setImage(
  99. with: resource,
  100. progressBlock: { _, _ in progressBlockIsCalled = true })
  101. {
  102. result in
  103. XCTAssertTrue(progressBlockIsCalled)
  104. XCTAssertNotNil(result.value)
  105. let value = result.value!
  106. XCTAssertTrue(value.image.renderEqual(to: testImage))
  107. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  108. XCTAssertEqual(value.cacheType, .none)
  109. XCTAssertTrue(Thread.isMainThread)
  110. exp.fulfill()
  111. }
  112. waitForExpectations(timeout: 3, handler: nil)
  113. }
  114. func testImageDownloadCancelForImageView() {
  115. let exp = expectation(description: #function)
  116. let url = testURLs[0]
  117. let stub = delayedStub(url, data: testImageData, length: 123)
  118. let task = imageView.kf.setImage(
  119. with: url,
  120. progressBlock: { _, _ in XCTFail() })
  121. {
  122. result in
  123. XCTAssertNotNil(result.error)
  124. delay(0.1) { exp.fulfill() }
  125. }
  126. XCTAssertNotNil(task)
  127. task?.cancel()
  128. _ = stub.go()
  129. waitForExpectations(timeout: 3, handler: nil)
  130. }
  131. func testImageDownloadCancelPartialTaskBeforeRequest() {
  132. let exp = expectation(description: #function)
  133. let url = testURLs[0]
  134. let stub = delayedStub(url, data: testImageData)
  135. let group = DispatchGroup()
  136. group.enter()
  137. let task1 = KF.url(url)
  138. .onFailure { _ in group.leave() }
  139. .set(to: imageView)
  140. group.enter()
  141. KF.url(url)
  142. .onSuccess { _ in group.leave() }
  143. .set(to: imageView)
  144. group.enter()
  145. let anotherImageView = KFCrossPlatformImageView()
  146. KF.url(url)
  147. .onSuccess { _ in group.leave() }
  148. .set(to: anotherImageView)
  149. task1?.cancel()
  150. _ = stub.go()
  151. group.notify(queue: .main) {
  152. delay(0.1) { exp.fulfill() }
  153. }
  154. waitForExpectations(timeout: 3, handler: nil)
  155. }
  156. func testImageDownloadCancelAllTasksAfterRequestStarted() {
  157. let exp = expectation(description: #function)
  158. let url = testURLs[0]
  159. let stub = delayedStub(url, data: testImageData)
  160. let group = DispatchGroup()
  161. group.enter()
  162. let task1 = imageView.kf.setImage(with: url) { result in
  163. XCTAssertNotNil(result.error)
  164. group.leave()
  165. }
  166. group.enter()
  167. let task2 = imageView.kf.setImage(with: url) { result in
  168. XCTAssertNotNil(result.error)
  169. group.leave()
  170. }
  171. group.enter()
  172. let task3 = imageView.kf.setImage(with: url) { result in
  173. XCTAssertNotNil(result.error)
  174. group.leave()
  175. }
  176. task1?.cancel()
  177. task2?.cancel()
  178. task3?.cancel()
  179. _ = stub.go()
  180. group.notify(queue: .main) {
  181. delay(0.1) { exp.fulfill() }
  182. }
  183. waitForExpectations(timeout: 3, handler: nil)
  184. }
  185. func testImageDownloadMultipleCaches() {
  186. let cache1 = ImageCache(name: "cache1")
  187. let cache2 = ImageCache(name: "cache2")
  188. cache1.clearDiskCache()
  189. cache2.clearDiskCache()
  190. cleanDefaultCache()
  191. let exp = expectation(description: #function)
  192. let url = testURLs[0]
  193. stub(url, data: testImageData)
  194. let key = url.cacheKey
  195. imageView.kf.setImage(with: url, options: [.targetCache(cache1)]) { result in
  196. XCTAssertTrue(cache1.imageCachedType(forKey: key).cached)
  197. XCTAssertFalse(cache2.imageCachedType(forKey: key).cached)
  198. XCTAssertFalse(KingfisherManager.shared.cache.imageCachedType(forKey: key).cached)
  199. self.imageView.kf.setImage(with: url, options: [.targetCache(cache2), .waitForCache]) { result in
  200. XCTAssertTrue(cache1.imageCachedType(forKey: key).cached)
  201. XCTAssertTrue(cache2.imageCachedType(forKey: key).cached)
  202. XCTAssertFalse(KingfisherManager.shared.cache.imageCachedType(forKey: key).cached)
  203. exp.fulfill()
  204. }
  205. }
  206. waitForExpectations(timeout: 5) { error in
  207. clearCaches([cache1, cache2])
  208. }
  209. }
  210. func testIndicatorViewExisting() {
  211. imageView.kf.indicatorType = .activity
  212. XCTAssertNotNil(imageView.kf.indicator)
  213. XCTAssertTrue(imageView.kf.indicator is ActivityIndicator)
  214. imageView.kf.indicatorType = .none
  215. XCTAssertNil(imageView.kf.indicator)
  216. }
  217. func testCustomizeStructIndicatorExisting() {
  218. struct StructIndicator: Indicator {
  219. let view = KFCrossPlatformView()
  220. func startAnimatingView() {}
  221. func stopAnimatingView() {}
  222. }
  223. imageView.kf.indicatorType = .custom(indicator: StructIndicator())
  224. XCTAssertNotNil(imageView.kf.indicator)
  225. XCTAssertTrue(imageView.kf.indicator is StructIndicator)
  226. imageView.kf.indicatorType = .none
  227. XCTAssertNil(imageView.kf.indicator)
  228. }
  229. func testActivityIndicatorViewAnimating() {
  230. imageView.kf.indicatorType = .activity
  231. let exp = expectation(description: #function)
  232. let url = testURLs[0]
  233. stub(url, data: testImageData)
  234. imageView.kf.setImage(with: url, progressBlock: { receivedSize, totalSize in
  235. let indicator = self.imageView.kf.indicator
  236. XCTAssertNotNil(indicator)
  237. XCTAssertFalse(indicator!.view.isHidden)
  238. })
  239. {
  240. result in
  241. let indicator = self.imageView.kf.indicator
  242. XCTAssertTrue(indicator!.view.isHidden)
  243. exp.fulfill()
  244. }
  245. waitForExpectations(timeout: 3, handler: nil)
  246. }
  247. func testCanUseImageIndicatorViewAnimating() {
  248. imageView.kf.indicatorType = .image(imageData: testImageData)
  249. XCTAssertTrue(imageView.kf.indicator is ImageIndicator)
  250. let image = (imageView.kf.indicator?.view as? KFCrossPlatformImageView)?.image
  251. XCTAssertNotNil(image)
  252. XCTAssertTrue(image!.renderEqual(to: testImage))
  253. let exp = expectation(description: #function)
  254. let url = testURLs[0]
  255. stub(url, data: testImageData)
  256. imageView.kf.setImage(with: url, progressBlock: { receivedSize, totalSize in
  257. let indicator = self.imageView.kf.indicator
  258. XCTAssertNotNil(indicator)
  259. XCTAssertFalse(indicator!.view.isHidden)
  260. })
  261. {
  262. result in
  263. let indicator = self.imageView.kf.indicator
  264. XCTAssertTrue(indicator!.view.isHidden)
  265. exp.fulfill()
  266. }
  267. waitForExpectations(timeout: 3, handler: nil)
  268. }
  269. func testCancelImageTask() {
  270. let exp = expectation(description: #function)
  271. let url = testURLs[0]
  272. let stub = delayedStub(url, data: testImageData)
  273. imageView.kf.setImage(with: url, progressBlock: { _, _ in XCTFail() }) { result in
  274. XCTAssertNotNil(result.error)
  275. XCTAssertTrue(result.error!.isTaskCancelled)
  276. delay(0.1) { exp.fulfill() }
  277. }
  278. self.imageView.kf.cancelDownloadTask()
  279. _ = stub.go()
  280. waitForExpectations(timeout: 3, handler: nil)
  281. }
  282. func testDownloadForMutipleURLs() {
  283. let exp = expectation(description: #function)
  284. stub(testURLs[0], data: testImageData)
  285. stub(testURLs[1], data: testImageData)
  286. let group = DispatchGroup()
  287. group.enter()
  288. imageView.kf.setImage(with: testURLs[0]) { result in
  289. // The download successed, but not the resource we want.
  290. XCTAssertNotNil(result.error)
  291. if case .imageSettingError(
  292. reason: .notCurrentSourceTask(let result, _, let source)) = result.error!
  293. {
  294. XCTAssertEqual(source.url, testURLs[0])
  295. XCTAssertNotEqual(result!.image, self.imageView.image)
  296. } else {
  297. XCTFail()
  298. }
  299. group.leave()
  300. }
  301. group.enter()
  302. self.imageView.kf.setImage(with: testURLs[1]) { result in
  303. XCTAssertNotNil(result.value?.image)
  304. XCTAssertEqual(result.value?.source.url, testURLs[1])
  305. XCTAssertEqual(result.value!.image, self.imageView.image)
  306. group.leave()
  307. }
  308. group.notify(queue: .main, execute: exp.fulfill)
  309. waitForExpectations(timeout: 3, handler: nil)
  310. }
  311. func testSettingNilURL() {
  312. let exp = expectation(description: #function)
  313. let url: URL? = nil
  314. imageView.kf.setImage(with: url, progressBlock: { _, _ in XCTFail() }) {
  315. result in
  316. XCTAssertNotNil(result.error)
  317. guard case .imageSettingError(reason: .emptySource) = result.error! else {
  318. XCTFail()
  319. fatalError()
  320. }
  321. exp.fulfill()
  322. }
  323. waitForExpectations(timeout: 3, handler: nil)
  324. }
  325. func testSettingImageWhileKeepingCurrentOne() {
  326. let exp = expectation(description: #function)
  327. let url = testURLs[0]
  328. stub(url, data: testImageData)
  329. imageView.image = testImage
  330. imageView.kf.setImage(with: url) { result in }
  331. XCTAssertNil(imageView.image)
  332. imageView.image = testImage
  333. imageView.kf.setImage(with: url, options: [.keepCurrentImageWhileLoading]) { result in
  334. XCTAssertEqual(self.imageView.image, result.value!.image)
  335. XCTAssertNotEqual(self.imageView.image, testImage)
  336. exp.fulfill()
  337. }
  338. XCTAssertEqual(testImage, imageView.image)
  339. waitForExpectations(timeout: 3, handler: nil)
  340. }
  341. func testSettingImageKeepingRespectingPlaceholder() {
  342. let exp = expectation(description: #function)
  343. let url = testURLs[0]
  344. stub(url, data: testImageData)
  345. // While current image is nil, set placeholder
  346. imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in }
  347. XCTAssertNotNil(imageView.image)
  348. XCTAssertEqual(testImage, imageView.image)
  349. // While current image is not nil, keep it
  350. let anotherImage = KFCrossPlatformImage(data: testImageJEPGData)
  351. imageView.image = anotherImage
  352. imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in
  353. XCTAssertNotEqual(self.imageView.image, anotherImage)
  354. exp.fulfill()
  355. }
  356. XCTAssertNotNil(imageView.image)
  357. XCTAssertEqual(anotherImage, imageView.image)
  358. waitForExpectations(timeout: 3, handler: nil)
  359. }
  360. func testSetGIFImageOnlyFirstFrameThenFullFrames() {
  361. let exp = expectation(description: #function)
  362. let url = testURLs[0]
  363. stub(url, data: testImageGIFData, length: 123)
  364. func loadFullGIFImage() {
  365. ImageCache.default.clearMemoryCache()
  366. imageView.kf.setImage(with: url, progressBlock: { _, _ in XCTFail() })
  367. {
  368. result in
  369. let image = result.value?.image
  370. XCTAssertNotNil(image)
  371. XCTAssertNotNil(image!.kf.images)
  372. XCTAssertEqual(image!.kf.images?.count, 8)
  373. XCTAssertEqual(result.value!.cacheType, .disk)
  374. XCTAssertTrue(Thread.isMainThread)
  375. exp.fulfill()
  376. }
  377. }
  378. var progressBlockIsCalled = false
  379. imageView.kf.setImage(with: url, options: [.onlyLoadFirstFrame, .waitForCache], progressBlock: { _, _ in
  380. progressBlockIsCalled = true
  381. XCTAssertTrue(Thread.isMainThread)
  382. })
  383. {
  384. result in
  385. XCTAssertTrue(progressBlockIsCalled)
  386. let image = result.value?.image
  387. XCTAssertNotNil(image)
  388. XCTAssertNil(image!.kf.images)
  389. XCTAssert(result.value!.cacheType == .none)
  390. let memory = KingfisherManager.shared.cache.memoryStorage.value(forKey: url.cacheKey)
  391. XCTAssertNotNil(memory)
  392. let disk = try! KingfisherManager.shared.cache.diskStorage.value(forKey: url.cacheKey)
  393. XCTAssertNotNil(disk)
  394. XCTAssertTrue(Thread.isMainThread)
  395. loadFullGIFImage()
  396. }
  397. waitForExpectations(timeout: 3, handler: nil)
  398. }
  399. // https://github.com/onevcat/Kingfisher/issues/1923
  400. func testLoadGIFImageWithDifferentOptions() {
  401. let exp = expectation(description: #function)
  402. let url = testURLs[0]
  403. stub(url, data: testImageGIFData)
  404. imageView.kf.setImage(with: url) { result in
  405. let fullImage = result.value?.image
  406. XCTAssertNotNil(fullImage)
  407. XCTAssertEqual(fullImage?.images?.count, 8)
  408. self.imageView.kf.setImage(with: url, options: [.onlyLoadFirstFrame]) { result in
  409. let firstFrameImage = result.value?.image
  410. XCTAssertNotNil(firstFrameImage)
  411. XCTAssertNil(firstFrameImage?.images)
  412. exp.fulfill()
  413. }
  414. }
  415. waitForExpectations(timeout: 3)
  416. }
  417. // https://github.com/onevcat/Kingfisher/issues/665
  418. // The completion handler should be called even when the image view loading url gets changed.
  419. func testIssue665() {
  420. let exp = expectation(description: #function)
  421. stub(testURLs[0], data: testImageData)
  422. stub(testURLs[1], data: testImageData)
  423. let group = DispatchGroup()
  424. group.enter()
  425. imageView.kf.setImage(with: testURLs[0]) { _ in
  426. group.leave()
  427. }
  428. group.enter()
  429. imageView.kf.setImage(with: testURLs[1]) { _ in
  430. group.leave()
  431. }
  432. group.notify(queue: .main, execute: exp.fulfill)
  433. waitForExpectations(timeout: 3, handler: nil)
  434. }
  435. func testImageSettingWithPlaceholder() {
  436. let exp = expectation(description: #function)
  437. let url = testURLs[0]
  438. stub(url, data: testImageData, length: 123)
  439. let emptyImage = KFCrossPlatformImage()
  440. var processBlockCalled = false
  441. imageView.kf.setImage(
  442. with: url,
  443. placeholder: emptyImage,
  444. progressBlock: { _, _ in
  445. processBlockCalled = true
  446. XCTAssertEqual(self.imageView.image, emptyImage)
  447. })
  448. {
  449. result in
  450. XCTAssertTrue(processBlockCalled)
  451. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  452. exp.fulfill()
  453. }
  454. waitForExpectations(timeout: 3, handler: nil)
  455. }
  456. func testImageSettingWithCustomizePlaceholder() {
  457. let exp = expectation(description: #function)
  458. let url = testURLs[0]
  459. stub(url, data: testImageData, length: 123)
  460. let view = KFCrossPlatformView()
  461. var processBlockCalled = false
  462. imageView.kf.setImage(
  463. with: url,
  464. placeholder: view,
  465. progressBlock: { _, _ in
  466. processBlockCalled = true
  467. XCTAssertNil(self.imageView.image)
  468. XCTAssertTrue(self.imageView.subviews.contains(view))
  469. })
  470. {
  471. result in
  472. XCTAssertTrue(processBlockCalled)
  473. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  474. XCTAssertFalse(self.imageView.subviews.contains(view))
  475. exp.fulfill()
  476. }
  477. waitForExpectations(timeout: 3, handler: nil)
  478. }
  479. func testSettingNonWorkingImageWithCustomizePlaceholderAndFailureImage() {
  480. let exp = expectation(description: #function)
  481. let url = testURLs[0]
  482. stub(url, errorCode: 404)
  483. let view = KFCrossPlatformView()
  484. imageView.kf.setImage(
  485. with: url,
  486. placeholder: view,
  487. options: [.onFailureImage(testImage)])
  488. {
  489. result in
  490. XCTAssertEqual(self.imageView.image, testImage)
  491. XCTAssertFalse(self.imageView.subviews.contains(view))
  492. exp.fulfill()
  493. }
  494. waitForExpectations(timeout: 3, handler: nil)
  495. }
  496. func testSettingNonWorkingImageWithFailureImage() {
  497. let exp = expectation(description: #function)
  498. let url = testURLs[0]
  499. stub(url, errorCode: 404)
  500. imageView.kf.setImage(with: url, options: [.onFailureImage(testImage)]) {
  501. result in
  502. XCTAssertNil(result.value)
  503. if case KingfisherError.responseError(let reason) = result.error!,
  504. case .URLSessionError(error: let nsError) = reason
  505. {
  506. XCTAssertEqual((nsError as NSError).code, 404)
  507. } else {
  508. XCTFail()
  509. }
  510. XCTAssertEqual(self.imageView.image, testImage)
  511. exp.fulfill()
  512. }
  513. XCTAssertNil(imageView.image)
  514. waitForExpectations(timeout: 5, handler: nil)
  515. }
  516. func testSettingNonWorkingImageWithEmptyFailureImage() {
  517. let exp = expectation(description: #function)
  518. let url = testURLs[0]
  519. stub(url, errorCode: 404)
  520. imageView.kf.setImage(with: url, placeholder: testImage, options: [.onFailureImage(nil)]) {
  521. result in
  522. XCTAssertNil(result.value)
  523. XCTAssertNil(self.imageView.image)
  524. exp.fulfill()
  525. }
  526. XCTAssertEqual(testImage, imageView.image)
  527. waitForExpectations(timeout: 5, handler: nil)
  528. }
  529. func testSettingNonWorkingImageWithoutFailureImage() {
  530. let exp = expectation(description: #function)
  531. let url = testURLs[0]
  532. stub(url, errorCode: 404)
  533. imageView.kf.setImage(with: url, placeholder: testImage) {
  534. result in
  535. XCTAssertNil(result.value)
  536. XCTAssertEqual(testImage, self.imageView.image)
  537. exp.fulfill()
  538. }
  539. XCTAssertEqual(testImage, imageView.image)
  540. waitForExpectations(timeout: 5, handler: nil)
  541. }
  542. // https://github.com/onevcat/Kingfisher/issues/1053
  543. func testSetSameURLWithDifferentProcessors() {
  544. let exp = expectation(description: #function)
  545. let url = testURLs[0]
  546. stub(url, data: testImageData)
  547. let size1 = CGSize(width: 10, height: 10)
  548. let p1 = ResizingImageProcessor(referenceSize: size1)
  549. let size2 = CGSize(width: 20, height: 20)
  550. let p2 = ResizingImageProcessor(referenceSize: size2)
  551. let group = DispatchGroup()
  552. group.enter()
  553. imageView.kf.setImage(with: url, options: [.processor(p1)]) { result in
  554. XCTAssertNotNil(result.error)
  555. XCTAssertTrue(result.error!.isNotCurrentTask)
  556. group.leave()
  557. }
  558. group.enter()
  559. imageView.kf.setImage(with: url, options: [.processor(p2)]) { result in
  560. XCTAssertNotNil(result.value)
  561. XCTAssertEqual(result.value!.image.size, size2)
  562. group.leave()
  563. }
  564. group.notify(queue: .main) { exp.fulfill() }
  565. waitForExpectations(timeout: 3, handler: nil)
  566. }
  567. func testMemoryImageCacheExtendingExpirationTask() {
  568. let exp = expectation(description: #function)
  569. let url = testURLs[0]
  570. stub(url, data: testImageData)
  571. let options: KingfisherOptionsInfo = [.cacheMemoryOnly, .memoryCacheExpiration(.seconds(1)), .memoryCacheAccessExtendingExpiration(.expirationTime(.seconds(100)))]
  572. imageView.kf.setImage(with: url, options: options) { result in
  573. XCTAssertNotNil(result.value?.image)
  574. XCTAssertTrue(result.value!.cacheType == .none)
  575. let cacheKey = result.value!.source.cacheKey as NSString
  576. let expirationTime1 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  577. XCTAssertNotNil(expirationTime1)
  578. delay(0.1, block: {
  579. self.imageView.kf.setImage(with: url, options: options) { result in
  580. XCTAssertNotNil(result.value?.image)
  581. XCTAssertTrue(result.value!.cacheType == .memory)
  582. let expirationTime2 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  583. XCTAssertNotNil(expirationTime2)
  584. XCTAssertNotEqual(expirationTime1, expirationTime2)
  585. XCTAssert(expirationTime1!.isPast(referenceDate: expirationTime2!))
  586. XCTAssertGreaterThan(expirationTime2!.timeIntervalSince(expirationTime1!), 10)
  587. exp.fulfill()
  588. }
  589. })
  590. }
  591. waitForExpectations(timeout: 3, handler: nil)
  592. }
  593. func testMemoryImageCacheNotExtendingExpirationTask() {
  594. let exp = expectation(description: #function)
  595. let url = testURLs[0]
  596. stub(url, data: testImageData)
  597. let options: KingfisherOptionsInfo = [.cacheMemoryOnly, .memoryCacheExpiration(.seconds(1)), .memoryCacheAccessExtendingExpiration(.none)]
  598. imageView.kf.setImage(with: url, options: options) { result in
  599. XCTAssertNotNil(result.value?.image)
  600. XCTAssertTrue(result.value!.cacheType == .none)
  601. let cacheKey = result.value!.source.cacheKey as NSString
  602. let expirationTime1 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  603. XCTAssertNotNil(expirationTime1)
  604. delay(0.1, block: {
  605. self.imageView.kf.setImage(with: url, options: options) { result in
  606. XCTAssertNotNil(result.value?.image)
  607. XCTAssertTrue(result.value!.cacheType == .memory)
  608. let expirationTime2 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  609. XCTAssertNotNil(expirationTime2)
  610. XCTAssertEqual(expirationTime1, expirationTime2)
  611. exp.fulfill()
  612. }
  613. })
  614. }
  615. waitForExpectations(timeout: 3, handler: nil)
  616. }
  617. func testDiskImageCacheExtendingExpirationTask() {
  618. let exp = expectation(description: #function)
  619. let url = testURLs[0]
  620. stub(url, data: testImageData)
  621. let options: KingfisherOptionsInfo = [.memoryCacheExpiration(.expired),
  622. .diskCacheExpiration(.seconds(2)),
  623. .diskCacheAccessExtendingExpiration(.expirationTime(.seconds(100)))]
  624. imageView.kf.setImage(with: url, options: options) { result in
  625. XCTAssertNotNil(result.value?.image)
  626. XCTAssertTrue(result.value!.cacheType == .none)
  627. delay(1, block: {
  628. self.imageView.kf.setImage(with: url, options: options) { result in
  629. XCTAssertNotNil(result.value?.image)
  630. XCTAssertTrue(result.value!.cacheType == .disk)
  631. delay(2, block: {
  632. self.imageView.kf.setImage(with: url, options: options) { result in
  633. XCTAssertNotNil(result.value?.image)
  634. XCTAssertTrue(result.value!.cacheType == .disk)
  635. exp.fulfill()
  636. }
  637. })
  638. }
  639. })
  640. }
  641. waitForExpectations(timeout: 5, handler: nil)
  642. }
  643. func testDiskImageCacheNotExtendingExpirationTask() {
  644. let exp = expectation(description: #function)
  645. let url = testURLs[0]
  646. stub(url, data: testImageData)
  647. let options: KingfisherOptionsInfo = [.memoryCacheExpiration(.expired),
  648. .diskCacheExpiration(.seconds(2)),
  649. .diskCacheAccessExtendingExpiration(.none)]
  650. imageView.kf.setImage(with: url, options: options) { result in
  651. XCTAssertNotNil(result.value?.image)
  652. XCTAssertTrue(result.value!.cacheType == .none)
  653. delay(1, block: {
  654. self.imageView.kf.setImage(with: url, options: options) { result in
  655. XCTAssertNotNil(result.value?.image)
  656. XCTAssertTrue(result.value!.cacheType == .disk)
  657. delay(2, block: {
  658. self.imageView.kf.setImage(with: url, options: options) { result in
  659. XCTAssertNotNil(result.value?.image)
  660. XCTAssertTrue(result.value!.cacheType == .none)
  661. exp.fulfill()
  662. }
  663. })
  664. }
  665. })
  666. }
  667. waitForExpectations(timeout: 5, handler: nil)
  668. }
  669. func testImageSettingWithAlternativeSource() {
  670. let exp = expectation(description: #function)
  671. let url = testURLs[0]
  672. stub(url, data: testImageData)
  673. let brokenURL = URL(string: "brokenurl")!
  674. stub(brokenURL, data: Data())
  675. imageView.kf.setImage(
  676. with: .network(brokenURL),
  677. options: [.alternativeSources([.network(url)])]
  678. ) { result in
  679. XCTAssertNotNil(result.value)
  680. XCTAssertEqual(result.value!.source.url, url)
  681. XCTAssertEqual(result.value!.originalSource.url, brokenURL)
  682. exp.fulfill()
  683. }
  684. waitForExpectations(timeout: 1, handler: nil)
  685. }
  686. func testImageSettingCanCancelAlternativeSource() {
  687. let exp = expectation(description: #function)
  688. let url = testURLs[0]
  689. let dataStub = delayedStub(url, data: testImageData)
  690. let brokenURL = testURLs[1]
  691. let brokenStub = delayedStub(brokenURL, data: Data())
  692. var finishCalled = false
  693. delay(0.1) {
  694. _ = brokenStub.go()
  695. }
  696. delay(0.3) {
  697. self.imageView.kf.cancelDownloadTask()
  698. }
  699. delay(0.5) {
  700. _ = dataStub.go()
  701. XCTAssertTrue(finishCalled)
  702. exp.fulfill()
  703. }
  704. imageView.kf.setImage(
  705. with: .network(brokenURL),
  706. options: [.alternativeSources([.network(url)])]
  707. ) { result in
  708. finishCalled = true
  709. XCTAssertNotNil(result.error)
  710. guard case .requestError(reason: .taskCancelled(let task, _)) = result.error! else {
  711. XCTFail("The error should be a task cancelled.")
  712. return
  713. }
  714. XCTAssertEqual(task.task.originalRequest?.url, url, "Should be the alternatived url cancelled.")
  715. }
  716. waitForExpectations(timeout: 1, handler: nil)
  717. }
  718. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  719. func testLowDataModeSource() {
  720. let exp = expectation(description: #function)
  721. let url = testURLs[0]
  722. stub(url, data: testImageData)
  723. // Stub a failure of `.constrained`. It is what happens when an image downloading fails when low data mode on.
  724. let brokenURL = testURLs[1]
  725. let error = URLError(
  726. .notConnectedToInternet,
  727. userInfo: [NSURLErrorNetworkUnavailableReasonKey: URLError.NetworkUnavailableReason.constrained.rawValue]
  728. )
  729. stub(brokenURL, error: error)
  730. imageView.kf.setImage(with: .network(brokenURL), options: [.lowDataMode(.network(url))]) { result in
  731. XCTAssertNotNil(result.value)
  732. XCTAssertEqual(result.value?.source.url, url)
  733. XCTAssertEqual(result.value?.originalSource.url, brokenURL)
  734. exp.fulfill()
  735. }
  736. waitForExpectations(timeout: 1, handler: nil)
  737. }
  738. }
  739. extension KFCrossPlatformView: Placeholder {}