ImageViewExtensionTests.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. @MainActor 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. @MainActor 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. @MainActor 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 = KF.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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor 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. @MainActor func testDownloadForMultipleURLs() {
  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 succeeded, but not with 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. XCTAssertEqual(result?.originalSource.url, testURLs[0])
  296. XCTAssertNotEqual(result!.image, self.imageView.image)
  297. } else {
  298. XCTFail()
  299. }
  300. group.leave()
  301. }
  302. group.enter()
  303. self.imageView.kf.setImage(with: testURLs[1]) { result in
  304. XCTAssertNotNil(result.value?.image)
  305. XCTAssertEqual(result.value?.source.url, testURLs[1])
  306. XCTAssertEqual(result.value!.image, self.imageView.image)
  307. group.leave()
  308. }
  309. group.notify(queue: .main, execute: exp.fulfill)
  310. waitForExpectations(timeout: 3, handler: nil)
  311. }
  312. @MainActor func testSettingNilURL() {
  313. let exp = expectation(description: #function)
  314. let url: URL? = nil
  315. imageView.kf.setImage(with: url, progressBlock: { _, _ in XCTFail() }) {
  316. result in
  317. XCTAssertNotNil(result.error)
  318. guard case .imageSettingError(reason: .emptySource) = result.error! else {
  319. XCTFail()
  320. fatalError()
  321. }
  322. exp.fulfill()
  323. }
  324. waitForExpectations(timeout: 3, handler: nil)
  325. }
  326. @MainActor func testSettingImageWhileKeepingCurrentOne() {
  327. let exp = expectation(description: #function)
  328. let url = testURLs[0]
  329. stub(url, data: testImageData)
  330. imageView.image = testImage
  331. imageView.kf.setImage(with: url) { result in }
  332. XCTAssertNil(imageView.image)
  333. imageView.image = testImage
  334. imageView.kf.setImage(with: url, options: [.keepCurrentImageWhileLoading]) { result in
  335. XCTAssertEqual(self.imageView.image, result.value!.image)
  336. XCTAssertNotEqual(self.imageView.image, testImage)
  337. exp.fulfill()
  338. }
  339. XCTAssertEqual(testImage, imageView.image)
  340. waitForExpectations(timeout: 3, handler: nil)
  341. }
  342. @MainActor func testSettingImageKeepingRespectingPlaceholder() {
  343. let exp = expectation(description: #function)
  344. // While current image is nil, set placeholder
  345. let url = testURLs[0]
  346. imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in
  347. exp.fulfill()
  348. }
  349. XCTAssertEqual(testImage, imageView.image)
  350. waitForExpectations(timeout: 3, handler: nil)
  351. }
  352. @MainActor func testMe() {
  353. let exp = expectation(description: #function)
  354. let url = testURLs[0]
  355. stub(url, data: testImageData)
  356. // While current image is not nil, keep it
  357. let anotherImage = KFCrossPlatformImage(data: testImageJEPGData)
  358. imageView.image = anotherImage
  359. imageView.kf.setImage(with: url, placeholder: testImage, options: [.keepCurrentImageWhileLoading]) { result in
  360. XCTAssertNotEqual(self.imageView.image, anotherImage)
  361. exp.fulfill()
  362. }
  363. XCTAssertEqual(anotherImage, imageView.image)
  364. waitForExpectations(timeout: 3, handler: nil)
  365. }
  366. @MainActor func testSetGIFImageOnlyFirstFrameThenFullFrames() {
  367. let exp = expectation(description: #function)
  368. let url = testURLs[0]
  369. stub(url, data: testImageGIFData, length: 123)
  370. func loadFullGIFImage() {
  371. ImageCache.default.clearMemoryCache()
  372. imageView.kf.setImage(with: url, progressBlock: { _, _ in XCTFail() })
  373. {
  374. result in
  375. let image = result.value?.image
  376. XCTAssertNotNil(image)
  377. XCTAssertNotNil(image!.kf.images)
  378. XCTAssertEqual(image!.kf.images?.count, 8)
  379. XCTAssertEqual(result.value!.cacheType, .disk)
  380. XCTAssertTrue(Thread.isMainThread)
  381. exp.fulfill()
  382. }
  383. }
  384. var progressBlockIsCalled = false
  385. imageView.kf.setImage(with: url, options: [.onlyLoadFirstFrame, .waitForCache], progressBlock: { _, _ in
  386. progressBlockIsCalled = true
  387. XCTAssertTrue(Thread.isMainThread)
  388. })
  389. {
  390. result in
  391. XCTAssertTrue(progressBlockIsCalled)
  392. let image = result.value?.image
  393. XCTAssertNotNil(image)
  394. XCTAssertNil(image!.kf.images)
  395. XCTAssert(result.value!.cacheType == .none)
  396. let memory = KingfisherManager.shared.cache.memoryStorage.value(forKey: url.cacheKey)
  397. XCTAssertNotNil(memory)
  398. let disk = try! KingfisherManager.shared.cache.diskStorage.value(forKey: url.cacheKey)
  399. XCTAssertNotNil(disk)
  400. XCTAssertTrue(Thread.isMainThread)
  401. loadFullGIFImage()
  402. }
  403. waitForExpectations(timeout: 3, handler: nil)
  404. }
  405. // https://github.com/onevcat/Kingfisher/issues/1923
  406. @MainActor func testLoadGIFImageWithDifferentOptions() {
  407. let exp = expectation(description: #function)
  408. let url = testURLs[0]
  409. stub(url, data: testImageGIFData)
  410. imageView.kf.setImage(with: url) { result in
  411. let fullImage = result.value?.image
  412. XCTAssertNotNil(fullImage)
  413. XCTAssertEqual(fullImage!.kf.images?.count, 8)
  414. self.imageView.kf.setImage(with: url, options: [.onlyLoadFirstFrame]) { result in
  415. let firstFrameImage = result.value?.image
  416. XCTAssertNotNil(firstFrameImage)
  417. XCTAssertNil(firstFrameImage!.kf.images)
  418. exp.fulfill()
  419. }
  420. }
  421. waitForExpectations(timeout: 3)
  422. }
  423. // https://github.com/onevcat/Kingfisher/issues/665
  424. // The completion handler should be called even when the image view loading url gets changed.
  425. @MainActor func testIssue665() {
  426. let exp = expectation(description: #function)
  427. stub(testURLs[0], data: testImageData)
  428. stub(testURLs[1], data: testImageData)
  429. let group = DispatchGroup()
  430. group.enter()
  431. imageView.kf.setImage(with: testURLs[0]) { _ in
  432. group.leave()
  433. }
  434. group.enter()
  435. imageView.kf.setImage(with: testURLs[1]) { _ in
  436. group.leave()
  437. }
  438. group.notify(queue: .main, execute: exp.fulfill)
  439. waitForExpectations(timeout: 3, handler: nil)
  440. }
  441. @MainActor func testImageSettingWithPlaceholder() {
  442. let exp = expectation(description: #function)
  443. let url = testURLs[0]
  444. stub(url, data: testImageData, length: 123)
  445. let emptyImage = KFCrossPlatformImage()
  446. var processBlockCalled = false
  447. imageView.kf.setImage(
  448. with: url,
  449. placeholder: emptyImage,
  450. progressBlock: { _, _ in
  451. processBlockCalled = true
  452. XCTAssertEqual(self.imageView.image, emptyImage)
  453. })
  454. {
  455. result in
  456. XCTAssertTrue(processBlockCalled)
  457. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  458. exp.fulfill()
  459. }
  460. waitForExpectations(timeout: 3, handler: nil)
  461. }
  462. @MainActor func testImageSettingWithCustomizePlaceholder() {
  463. let exp = expectation(description: #function)
  464. let url = testURLs[0]
  465. stub(url, data: testImageData, length: 123)
  466. let view = KFCrossPlatformView()
  467. var processBlockCalled = false
  468. imageView.kf.setImage(
  469. with: url,
  470. placeholder: view,
  471. progressBlock: { _, _ in
  472. processBlockCalled = true
  473. XCTAssertNil(self.imageView.image)
  474. XCTAssertTrue(self.imageView.subviews.contains(view))
  475. })
  476. {
  477. result in
  478. XCTAssertTrue(processBlockCalled)
  479. XCTAssertTrue(self.imageView.image!.renderEqual(to: testImage))
  480. XCTAssertFalse(self.imageView.subviews.contains(view))
  481. exp.fulfill()
  482. }
  483. waitForExpectations(timeout: 3, handler: nil)
  484. }
  485. @MainActor func testSettingNonWorkingImageWithCustomizePlaceholderAndFailureImage() {
  486. let exp = expectation(description: #function)
  487. let url = testURLs[0]
  488. stub(url, errorCode: 404)
  489. let view = KFCrossPlatformView()
  490. imageView.kf.setImage(
  491. with: url,
  492. placeholder: view,
  493. options: [.onFailureImage(testImage)])
  494. {
  495. result in
  496. XCTAssertEqual(self.imageView.image, testImage)
  497. XCTAssertFalse(self.imageView.subviews.contains(view))
  498. exp.fulfill()
  499. }
  500. waitForExpectations(timeout: 3, handler: nil)
  501. }
  502. @MainActor func testSettingNonWorkingImageWithFailureImage() {
  503. let exp = expectation(description: #function)
  504. let url = testURLs[0]
  505. stub(url, errorCode: 404)
  506. imageView.kf.setImage(with: url, options: [.onFailureImage(testImage)]) {
  507. result in
  508. XCTAssertNil(result.value)
  509. if case KingfisherError.responseError(let reason) = result.error!,
  510. case .URLSessionError(error: let nsError) = reason
  511. {
  512. XCTAssertEqual((nsError as NSError).code, 404)
  513. } else {
  514. XCTFail()
  515. }
  516. XCTAssertEqual(self.imageView.image, testImage)
  517. exp.fulfill()
  518. }
  519. XCTAssertNil(imageView.image)
  520. waitForExpectations(timeout: 5, handler: nil)
  521. }
  522. @MainActor func testSettingNonWorkingImageWithEmptyFailureImage() {
  523. let exp = expectation(description: #function)
  524. let url = testURLs[0]
  525. stub(url, errorCode: 404)
  526. imageView.kf.setImage(with: url, placeholder: testImage, options: [.onFailureImage(nil)]) {
  527. result in
  528. XCTAssertNil(result.value)
  529. XCTAssertNil(self.imageView.image)
  530. exp.fulfill()
  531. }
  532. XCTAssertEqual(testImage, imageView.image)
  533. waitForExpectations(timeout: 5, handler: nil)
  534. }
  535. @MainActor func testSettingNonWorkingImageWithoutFailureImage() {
  536. let exp = expectation(description: #function)
  537. let url = testURLs[0]
  538. stub(url, errorCode: 404)
  539. imageView.kf.setImage(with: url, placeholder: testImage) {
  540. result in
  541. XCTAssertNil(result.value)
  542. XCTAssertEqual(testImage, self.imageView.image)
  543. exp.fulfill()
  544. }
  545. XCTAssertEqual(testImage, imageView.image)
  546. waitForExpectations(timeout: 5, handler: nil)
  547. }
  548. // https://github.com/onevcat/Kingfisher/issues/1053
  549. @MainActor func testSetSameURLWithDifferentProcessors() {
  550. let exp = expectation(description: #function)
  551. let url = testURLs[0]
  552. stub(url, data: testImageData)
  553. let size1 = CGSize(width: 10, height: 10)
  554. let p1 = ResizingImageProcessor(referenceSize: size1)
  555. let size2 = CGSize(width: 20, height: 20)
  556. let p2 = ResizingImageProcessor(referenceSize: size2)
  557. let group = DispatchGroup()
  558. group.enter()
  559. imageView.kf.setImage(with: url, options: [.processor(p1), .cacheMemoryOnly]) { result in
  560. XCTAssertNotNil(result.error)
  561. XCTAssertTrue(result.error!.isNotCurrentTask)
  562. group.leave()
  563. }
  564. group.enter()
  565. imageView.kf.setImage(with: url, options: [.processor(p2), .cacheMemoryOnly]) { result in
  566. XCTAssertNotNil(result.value)
  567. XCTAssertEqual(result.value!.image.size, size2)
  568. group.leave()
  569. }
  570. group.notify(queue: .main) { exp.fulfill() }
  571. waitForExpectations(timeout: 5, handler: nil)
  572. }
  573. @MainActor func testMemoryImageCacheExtendingExpirationTask() {
  574. let exp = expectation(description: #function)
  575. let url = testURLs[0]
  576. stub(url, data: testImageData)
  577. let options: KingfisherOptionsInfo = [.cacheMemoryOnly, .memoryCacheExpiration(.seconds(1)), .memoryCacheAccessExtendingExpiration(.expirationTime(.seconds(100)))]
  578. imageView.kf.setImage(with: url, options: options) { result in
  579. XCTAssertNotNil(result.value?.image)
  580. XCTAssertTrue(result.value!.cacheType == .none)
  581. let cacheKey = result.value!.source.cacheKey as NSString
  582. let expirationTime1 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  583. XCTAssertNotNil(expirationTime1)
  584. delay(0.1, block: {
  585. self.imageView.kf.setImage(with: url, options: options) { result in
  586. XCTAssertNotNil(result.value?.image)
  587. XCTAssertTrue(result.value!.cacheType == .memory)
  588. let expirationTime2 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  589. XCTAssertNotNil(expirationTime2)
  590. XCTAssertNotEqual(expirationTime1, expirationTime2)
  591. XCTAssert(expirationTime1!.isPast(referenceDate: expirationTime2!))
  592. XCTAssertGreaterThan(expirationTime2!.timeIntervalSince(expirationTime1!), 10)
  593. exp.fulfill()
  594. }
  595. })
  596. }
  597. waitForExpectations(timeout: 3, handler: nil)
  598. }
  599. @MainActor func testMemoryImageCacheNotExtendingExpirationTask() {
  600. let exp = expectation(description: #function)
  601. let url = testURLs[0]
  602. stub(url, data: testImageData)
  603. let options: KingfisherOptionsInfo = [.cacheMemoryOnly, .memoryCacheExpiration(.seconds(1)), .memoryCacheAccessExtendingExpiration(.none)]
  604. imageView.kf.setImage(with: url, options: options) { result in
  605. XCTAssertNotNil(result.value?.image)
  606. XCTAssertTrue(result.value!.cacheType == .none)
  607. let cacheKey = result.value!.source.cacheKey as NSString
  608. let expirationTime1 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  609. XCTAssertNotNil(expirationTime1)
  610. delay(0.1, block: {
  611. self.imageView.kf.setImage(with: url, options: options) { result in
  612. XCTAssertNotNil(result.value?.image)
  613. XCTAssertTrue(result.value!.cacheType == .memory)
  614. let expirationTime2 = ImageCache.default.memoryStorage.storage.object(forKey: cacheKey)?.estimatedExpiration
  615. XCTAssertNotNil(expirationTime2)
  616. XCTAssertEqual(expirationTime1, expirationTime2)
  617. exp.fulfill()
  618. }
  619. })
  620. }
  621. waitForExpectations(timeout: 3, handler: nil)
  622. }
  623. @MainActor func testDiskImageCacheExtendingExpirationTask() {
  624. let exp = expectation(description: #function)
  625. let url = testURLs[0]
  626. stub(url, data: testImageData)
  627. let options: KingfisherOptionsInfo = [.memoryCacheExpiration(.expired),
  628. .diskCacheExpiration(.seconds(2)),
  629. .diskCacheAccessExtendingExpiration(.expirationTime(.seconds(100)))]
  630. imageView.kf.setImage(with: url, options: options) { result in
  631. XCTAssertNotNil(result.value?.image)
  632. XCTAssertTrue(result.value!.cacheType == .none)
  633. delay(1, block: {
  634. self.imageView.kf.setImage(with: url, options: options) { result in
  635. XCTAssertNotNil(result.value?.image)
  636. XCTAssertTrue(result.value!.cacheType == .disk)
  637. delay(2, block: {
  638. self.imageView.kf.setImage(with: url, options: options) { result in
  639. XCTAssertNotNil(result.value?.image)
  640. XCTAssertTrue(result.value!.cacheType == .disk)
  641. exp.fulfill()
  642. }
  643. })
  644. }
  645. })
  646. }
  647. waitForExpectations(timeout: 5, handler: nil)
  648. }
  649. @MainActor func testDiskImageCacheNotExtendingExpirationTask() {
  650. let exp = expectation(description: #function)
  651. let url = testURLs[0]
  652. stub(url, data: testImageData)
  653. let options: KingfisherOptionsInfo = [.memoryCacheExpiration(.expired),
  654. .diskCacheExpiration(.seconds(2)),
  655. .diskCacheAccessExtendingExpiration(.none)]
  656. imageView.kf.setImage(with: url, options: options) { result in
  657. XCTAssertNotNil(result.value?.image)
  658. XCTAssertTrue(result.value!.cacheType == .none)
  659. delay(1, block: {
  660. self.imageView.kf.setImage(with: url, options: options) { result in
  661. XCTAssertNotNil(result.value?.image)
  662. XCTAssertTrue(result.value!.cacheType == .disk)
  663. delay(2, block: {
  664. self.imageView.kf.setImage(with: url, options: options) { result in
  665. XCTAssertNotNil(result.value?.image)
  666. XCTAssertTrue(result.value!.cacheType == .none)
  667. exp.fulfill()
  668. }
  669. })
  670. }
  671. })
  672. }
  673. waitForExpectations(timeout: 5, handler: nil)
  674. }
  675. @MainActor func testImageSettingWithAlternativeSource() {
  676. let exp = expectation(description: #function)
  677. let url = testURLs[0]
  678. stub(url, data: testImageData)
  679. let brokenURL = URL(string: "brokenurl")!
  680. stub(brokenURL, data: Data())
  681. imageView.kf.setImage(
  682. with: .network(brokenURL),
  683. options: [.alternativeSources([.network(url)])]
  684. ) { result in
  685. XCTAssertNotNil(result.value)
  686. XCTAssertEqual(result.value!.source.url, url)
  687. XCTAssertEqual(result.value!.originalSource.url, brokenURL)
  688. exp.fulfill()
  689. }
  690. waitForExpectations(timeout: 3, handler: nil)
  691. }
  692. @MainActor func testImageSettingCanCancelAlternativeSource() {
  693. let exp = expectation(description: #function)
  694. let url = testURLs[0]
  695. let dataStub = delayedStub(url, data: testImageData)
  696. let brokenURL = testURLs[1]
  697. let brokenStub = delayedStub(brokenURL, data: Data())
  698. var finishCalled = false
  699. delay(0.1) {
  700. _ = brokenStub.go()
  701. }
  702. delay(0.3) {
  703. self.imageView.kf.cancelDownloadTask()
  704. }
  705. delay(0.5) {
  706. _ = dataStub.go()
  707. XCTAssertTrue(finishCalled)
  708. exp.fulfill()
  709. }
  710. imageView.kf.setImage(
  711. with: .network(brokenURL),
  712. options: [.alternativeSources([.network(url)])]
  713. ) { result in
  714. finishCalled = true
  715. XCTAssertNotNil(result.error)
  716. guard case .requestError(reason: .taskCancelled(let task, _)) = result.error! else {
  717. XCTFail("The error should be a task cancelled.")
  718. return
  719. }
  720. XCTAssertEqual(task.task.originalRequest?.url, url, "Should be the alternative url cancelled.")
  721. }
  722. waitForExpectations(timeout: 3, handler: nil)
  723. }
  724. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  725. @MainActor func testLowDataModeSource() {
  726. let exp = expectation(description: #function)
  727. let url = testURLs[0]
  728. stub(url, data: testImageData)
  729. // Stub a failure of `.constrained`. It is what happens when an image downloading fails when low data mode on.
  730. let brokenURL = testURLs[1]
  731. let error = URLError(
  732. .notConnectedToInternet,
  733. userInfo: [NSURLErrorNetworkUnavailableReasonKey: URLError.NetworkUnavailableReason.constrained.rawValue]
  734. )
  735. stub(brokenURL, error: error)
  736. imageView.kf.setImage(with: .network(brokenURL), options: [.lowDataMode(.network(url))]) { result in
  737. XCTAssertNotNil(result.value)
  738. XCTAssertEqual(result.value?.source.url, url)
  739. XCTAssertEqual(result.value?.originalSource.url, brokenURL)
  740. exp.fulfill()
  741. }
  742. waitForExpectations(timeout: 3, handler: nil)
  743. }
  744. }
  745. #if compiler(>=6)
  746. extension KFCrossPlatformView: @retroactive Placeholder {}
  747. #else
  748. extension KFCrossPlatformView: Placeholder {}
  749. #endif