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