ImageViewExtensionTests.swift 31 KB

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