ImageCacheTests.swift 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. //
  2. // ImageCacheTests.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/10.
  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 ImageCacheTests: XCTestCase {
  29. var cache: ImageCache!
  30. var observer: NSObjectProtocol!
  31. override func setUp() {
  32. super.setUp()
  33. let uuid = UUID().uuidString
  34. let cacheName = "test-\(uuid)"
  35. cache = ImageCache(name: cacheName)
  36. }
  37. override func tearDown() {
  38. clearCaches([cache])
  39. cache = nil
  40. if let o = observer {
  41. NotificationCenter.default.removeObserver(o)
  42. observer = nil
  43. }
  44. super.tearDown()
  45. }
  46. func testInvalidCustomCachePath() {
  47. let customPath = "/path/to/image/cache"
  48. let url = URL(fileURLWithPath: customPath)
  49. XCTAssertThrowsError(try ImageCache(name: "test", cacheDirectoryURL: url)) { error in
  50. guard case KingfisherError.cacheError(reason: .cannotCreateDirectory(let path, _)) = error else {
  51. XCTFail("Should be KingfisherError with cacheError reason.")
  52. return
  53. }
  54. XCTAssertEqual(path, customPath + "/com.onevcat.Kingfisher.ImageCache.test")
  55. }
  56. }
  57. func testCustomCachePath() {
  58. let cacheURL = try! FileManager.default.url(
  59. for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  60. let subFolder = cacheURL.appendingPathComponent("temp")
  61. let customPath = subFolder.path
  62. let cache = try! ImageCache(name: "test", cacheDirectoryURL: subFolder)
  63. XCTAssertEqual(
  64. cache.diskStorage.directoryURL.path,
  65. (customPath as NSString).appendingPathComponent("com.onevcat.Kingfisher.ImageCache.test"))
  66. clearCaches([cache])
  67. }
  68. func testCustomCachePathByBlock() {
  69. let cache = try! ImageCache(name: "test", cacheDirectoryURL: nil, diskCachePathClosure: { (url, path) -> URL in
  70. let modifiedPath = path + "-modified"
  71. return url.appendingPathComponent(modifiedPath, isDirectory: true)
  72. })
  73. let cacheURL = try! FileManager.default.url(
  74. for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  75. XCTAssertEqual(
  76. cache.diskStorage.directoryURL.path,
  77. (cacheURL.path as NSString).appendingPathComponent("com.onevcat.Kingfisher.ImageCache.test-modified"))
  78. clearCaches([cache])
  79. }
  80. func testMaxCachePeriodInSecond() {
  81. cache.diskStorage.config.expiration = .seconds(1)
  82. XCTAssertEqual(cache.diskStorage.config.expiration.timeInterval, 1)
  83. }
  84. func testMaxMemorySize() {
  85. cache.memoryStorage.config.totalCostLimit = 1
  86. XCTAssert(cache.memoryStorage.config.totalCostLimit == 1, "maxMemoryCost should be able to be set.")
  87. }
  88. func testMaxDiskCacheSize() {
  89. cache.diskStorage.config.sizeLimit = 1
  90. XCTAssert(cache.diskStorage.config.sizeLimit == 1, "maxDiskCacheSize should be able to be set.")
  91. }
  92. func testClearDiskCache() {
  93. let exp = expectation(description: #function)
  94. let key = testKeys[0]
  95. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  96. self.cache.clearMemoryCache()
  97. let cacheResult = self.cache.imageCachedType(forKey: key)
  98. XCTAssertTrue(cacheResult.cached)
  99. XCTAssertEqual(cacheResult, .disk)
  100. self.cache.clearDiskCache {
  101. let cacheResult = self.cache.imageCachedType(forKey: key)
  102. XCTAssertFalse(cacheResult.cached)
  103. exp.fulfill()
  104. }
  105. }
  106. waitForExpectations(timeout: 3, handler:nil)
  107. }
  108. func testClearDiskCacheAsync() async throws {
  109. let key = testKeys[0]
  110. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  111. cache.clearMemoryCache()
  112. var cacheResult = self.cache.imageCachedType(forKey: key)
  113. XCTAssertTrue(cacheResult.cached)
  114. XCTAssertEqual(cacheResult, .disk)
  115. await cache.clearDiskCache()
  116. cacheResult = cache.imageCachedType(forKey: key)
  117. XCTAssertFalse(cacheResult.cached)
  118. }
  119. func testClearMemoryCache() {
  120. let exp = expectation(description: #function)
  121. let key = testKeys[0]
  122. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  123. self.cache.clearMemoryCache()
  124. self.cache.retrieveImage(forKey: key) { result in
  125. XCTAssertNotNil(result.value?.image)
  126. XCTAssertEqual(result.value?.cacheType, .disk)
  127. exp.fulfill()
  128. }
  129. }
  130. waitForExpectations(timeout: 3, handler: nil)
  131. }
  132. func testClearMemoryCacheAsync() async throws {
  133. let key = testKeys[0]
  134. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  135. cache.clearMemoryCache()
  136. let result = try await cache.retrieveImage(forKey: key)
  137. XCTAssertNotNil(result.image)
  138. XCTAssertEqual(result.cacheType, .disk)
  139. }
  140. func testNoImageFound() {
  141. let exp = expectation(description: #function)
  142. cache.retrieveImage(forKey: testKeys[0]) { result in
  143. XCTAssertNotNil(result.value)
  144. XCTAssertNil(result.value!.image)
  145. exp.fulfill()
  146. }
  147. waitForExpectations(timeout: 3, handler: nil)
  148. }
  149. func testNoImageFoundAsync() async throws {
  150. let result = try await cache.retrieveImage(forKey: testKeys[0])
  151. XCTAssertNil(result.image)
  152. }
  153. func testCachedFileDoesNotExist() {
  154. let URLString = testKeys[0]
  155. let url = URL(string: URLString)!
  156. let exists = cache.imageCachedType(forKey: url.cacheKey).cached
  157. XCTAssertFalse(exists)
  158. }
  159. func testStoreImageInMemory() {
  160. let exp = expectation(description: #function)
  161. let key = testKeys[0]
  162. cache.store(testImage, forKey: key, toDisk: false) { _ in
  163. self.cache.retrieveImage(forKey: key) { result in
  164. XCTAssertNotNil(result.value?.image)
  165. XCTAssertEqual(result.value?.cacheType, .memory)
  166. exp.fulfill()
  167. }
  168. }
  169. waitForExpectations(timeout: 3, handler: nil)
  170. }
  171. func testStoreImageInMemoryAsync() async throws {
  172. let key = testKeys[0]
  173. try await cache.store(testImage, forKey: key, toDisk: false)
  174. let result = try await cache.retrieveImage(forKey: key)
  175. XCTAssertNotNil(result.image)
  176. XCTAssertEqual(result.cacheType, .memory)
  177. }
  178. func testStoreGIFToDiskWithNilOriginalShouldPreserveGIFFormat() {
  179. struct TestProcessor: ImageProcessor {
  180. let identifier: String = "com.onevcat.KingfisherTests.TestProcessor"
  181. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  182. switch item {
  183. case .image(let image): return image
  184. case .data(let data): return DefaultImageProcessor.default.process(item: .data(data), options: options)
  185. }
  186. }
  187. }
  188. let exp = expectation(description: #function)
  189. let image = KingfisherWrapper<KFCrossPlatformImage>.animatedImage(data: testImageGIFData, options: .init())!
  190. XCTAssertEqual(image.kf.gifRepresentation()?.kf.imageFormat, .GIF)
  191. let options = KingfisherParsedOptionsInfo([.processor(TestProcessor())])
  192. let key = "test-gif"
  193. cache.store(image, original: nil, forKey: key, options: options, toDisk: true) { _ in
  194. do {
  195. let storedKey = key.computedKey(with: TestProcessor().identifier)
  196. let storedData = try self.cache.diskStorage.value(forKey: storedKey)
  197. XCTAssertEqual(storedData?.kf.imageFormat, .GIF)
  198. } catch {
  199. XCTFail("Unexpected error: \(error)")
  200. }
  201. exp.fulfill()
  202. }
  203. waitForExpectations(timeout: 3, handler: nil)
  204. }
  205. func testCopyKingfisherStateShouldKeepEmbeddedGIFDataForDiskCache() {
  206. struct TestProcessor: ImageProcessor {
  207. let identifier: String = "com.onevcat.KingfisherTests.TestProcessor.CopyState"
  208. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  209. switch item {
  210. case .image(let image):
  211. #if os(macOS)
  212. guard let cgImage = image.kf.cgImage else { return image }
  213. let newImage = KFCrossPlatformImage(cgImage: cgImage, size: image.kf.size)
  214. image.kf.copyKingfisherState(to: newImage)
  215. return newImage
  216. #else
  217. guard let cgImage = image.cgImage else { return image }
  218. let newImage = KFCrossPlatformImage(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation)
  219. image.kf.copyKingfisherState(to: newImage)
  220. return newImage
  221. #endif
  222. case .data(let data):
  223. return DefaultImageProcessor.default.process(item: .data(data), options: options)
  224. }
  225. }
  226. }
  227. let exp = expectation(description: #function)
  228. let image = KingfisherWrapper<KFCrossPlatformImage>.animatedImage(data: testImageGIFData, options: .init())!
  229. XCTAssertEqual(image.kf.gifRepresentation()?.kf.imageFormat, .GIF)
  230. let options = KingfisherParsedOptionsInfo([.processor(TestProcessor())])
  231. let key = "test-gif-copy-state"
  232. cache.store(image, original: nil, forKey: key, options: options, toDisk: true) { _ in
  233. do {
  234. let storedKey = key.computedKey(with: TestProcessor().identifier)
  235. let storedData = try self.cache.diskStorage.value(forKey: storedKey)
  236. XCTAssertEqual(storedData?.kf.imageFormat, .GIF)
  237. } catch {
  238. XCTFail("Unexpected error: \(error)")
  239. }
  240. exp.fulfill()
  241. }
  242. waitForExpectations(timeout: 3, handler: nil)
  243. }
  244. func testStoreMultipleImages() {
  245. let exp = expectation(description: #function)
  246. storeMultipleImages {
  247. let diskCachePath = self.cache.diskStorage.directoryURL.path
  248. var files: [String] = []
  249. do {
  250. files = try FileManager.default.contentsOfDirectory(atPath: diskCachePath)
  251. } catch _ {
  252. XCTFail()
  253. }
  254. XCTAssertEqual(files.count, testKeys.count)
  255. exp.fulfill()
  256. }
  257. waitForExpectations(timeout: 3, handler: nil)
  258. }
  259. func testStoreMultipleImagesAsync() async throws {
  260. await storeMultipleImages()
  261. let diskCachePath = cache.diskStorage.directoryURL.path
  262. let files = try FileManager.default.contentsOfDirectory(atPath: diskCachePath)
  263. XCTAssertEqual(files.count, testKeys.count)
  264. }
  265. func testCachedFileExists() {
  266. let exp = expectation(description: #function)
  267. let key = testKeys[0]
  268. let url = URL(string: key)!
  269. let exists = cache.imageCachedType(forKey: url.cacheKey).cached
  270. XCTAssertFalse(exists)
  271. cache.retrieveImage(forKey: key) { result in
  272. switch result {
  273. case .success(let value):
  274. XCTAssertNil(value.image)
  275. XCTAssertEqual(value.cacheType, .none)
  276. case .failure:
  277. XCTFail()
  278. return
  279. }
  280. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  281. self.cache.retrieveImage(forKey: key) { result in
  282. XCTAssertNotNil(result.value?.image)
  283. XCTAssertEqual(result.value?.cacheType, .memory)
  284. self.cache.clearMemoryCache()
  285. self.cache.retrieveImage(forKey: key) { result in
  286. XCTAssertNotNil(result.value?.image)
  287. XCTAssertEqual(result.value?.cacheType, .disk)
  288. exp.fulfill()
  289. }
  290. }
  291. }
  292. }
  293. waitForExpectations(timeout: 3, handler: nil)
  294. }
  295. func testCachedFileExistsAsync() async throws {
  296. let key = testKeys[0]
  297. let url = URL(string: key)!
  298. let exists = cache.imageCachedType(forKey: url.cacheKey).cached
  299. XCTAssertFalse(exists)
  300. var result = try await cache.retrieveImage(forKey: key)
  301. XCTAssertNil(result.image)
  302. XCTAssertEqual(result.cacheType, .none)
  303. try await cache.store(testImage, forKey: key, toDisk: true)
  304. result = try await cache.retrieveImage(forKey: key)
  305. XCTAssertNotNil(result.image)
  306. XCTAssertEqual(result.cacheType, .memory)
  307. cache.clearMemoryCache()
  308. result = try await cache.retrieveImage(forKey: key)
  309. XCTAssertNotNil(result.image)
  310. XCTAssertEqual(result.cacheType, .disk)
  311. }
  312. func testCachedFileWithCustomPathExtensionExists() {
  313. cache.diskStorage.config.pathExtension = "jpg"
  314. let exp = expectation(description: #function)
  315. let key = testKeys[0]
  316. let url = URL(string: key)!
  317. cache.store(testImage, forKey: key, toDisk: true) { _ in
  318. let cachePath = self.cache.cachePath(forKey: url.cacheKey)
  319. XCTAssertTrue(cachePath.hasSuffix(".jpg"))
  320. exp.fulfill()
  321. }
  322. waitForExpectations(timeout: 3, handler: nil)
  323. }
  324. func testCachedFileWithCustomPathExtensionExistsAsync() async throws {
  325. cache.diskStorage.config.pathExtension = "jpg"
  326. let key = testKeys[0]
  327. let url = URL(string: key)!
  328. try await cache.store(testImage, forKey: key, toDisk: true)
  329. let cachePath = self.cache.cachePath(forKey: url.cacheKey)
  330. XCTAssertTrue(cachePath.hasSuffix(".jpg"))
  331. }
  332. @MainActor func testCachedImageIsFetchedSynchronouslyFromTheMemoryCache() {
  333. cache.store(testImage, forKey: testKeys[0], toDisk: false)
  334. var image: KFCrossPlatformImage? = nil
  335. cache.retrieveImage(forKey: testKeys[0]) { result in
  336. MainActor.assumeIsolated {
  337. image = try? result.get().image
  338. }
  339. }
  340. XCTAssertEqual(testImage, image)
  341. }
  342. func testCachedImageIsFetchedSynchronouslyFromTheMemoryCacheAsync() async throws {
  343. try await cache.store(testImage, forKey: testKeys[0], toDisk: false)
  344. let result = try await cache.retrieveImage(forKey: testKeys[0])
  345. XCTAssertEqual(testImage, result.image)
  346. }
  347. func testIsImageCachedForKey() {
  348. let exp = expectation(description: #function)
  349. let key = testKeys[0]
  350. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  351. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  352. XCTAssertTrue(self.cache.imageCachedType(forKey: key).cached)
  353. exp.fulfill()
  354. }
  355. waitForExpectations(timeout: 3, handler: nil)
  356. }
  357. func testIsImageCachedForKeyAsync() async throws {
  358. let key = testKeys[0]
  359. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  360. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  361. XCTAssertTrue(cache.imageCachedType(forKey: key).cached)
  362. }
  363. func testCleanDiskCacheNotification() {
  364. let exp = expectation(description: #function)
  365. let key = testKeys[0]
  366. cache.diskStorage.config.expiration = .seconds(0.1)
  367. let selfCache = self.cache
  368. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  369. self.observer = NotificationCenter.default.addObserver(
  370. forName: .KingfisherDidCleanDiskCache,
  371. object: self.cache,
  372. queue: .main
  373. ) { noti in
  374. let receivedCache = noti.object as? ImageCache
  375. XCTAssertNotNil(receivedCache)
  376. XCTAssertTrue(receivedCache === selfCache)
  377. guard let hashes = noti.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else {
  378. XCTFail("Notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'")
  379. exp.fulfill()
  380. return
  381. }
  382. XCTAssertEqual(hashes.count, 1)
  383. XCTAssertEqual(hashes.first!, selfCache!.hash(forKey: key))
  384. exp.fulfill()
  385. }
  386. delay(2) { // File writing in disk cache has an approximate (round) creating time. 1 second is not enough.
  387. self.cache.cleanExpiredDiskCache()
  388. }
  389. }
  390. waitForExpectations(timeout: 5, handler: nil)
  391. }
  392. func testCannotRetrieveCacheWithProcessorIdentifier() {
  393. let exp = expectation(description: #function)
  394. let key = testKeys[0]
  395. let p = RoundCornerImageProcessor(cornerRadius: 40)
  396. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  397. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  398. XCTAssertNotNil(result.value)
  399. XCTAssertNil(result.value!.image)
  400. exp.fulfill()
  401. }
  402. }
  403. waitForExpectations(timeout: 3, handler: nil)
  404. }
  405. func testCannotRetrieveCacheWithProcessorIdentifierAsync() async throws {
  406. let key = testKeys[0]
  407. let p = RoundCornerImageProcessor(cornerRadius: 40)
  408. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  409. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  410. XCTAssertNotNil(result)
  411. XCTAssertNil(result.image)
  412. }
  413. func testRetrieveCacheWithProcessorIdentifier() {
  414. let exp = expectation(description: #function)
  415. let key = testKeys[0]
  416. let p = RoundCornerImageProcessor(cornerRadius: 40)
  417. cache.store(
  418. testImage,
  419. original: testImageData,
  420. forKey: key,
  421. processorIdentifier: p.identifier,
  422. toDisk: true)
  423. {
  424. _ in
  425. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  426. XCTAssertNotNil(result.value?.image)
  427. exp.fulfill()
  428. }
  429. }
  430. waitForExpectations(timeout: 3, handler: nil)
  431. }
  432. func testRetrieveCacheWithProcessorIdentifierAsync() async throws {
  433. let key = testKeys[0]
  434. let p = RoundCornerImageProcessor(cornerRadius: 40)
  435. try await cache.store(
  436. testImage,
  437. original: testImageData,
  438. forKey: key,
  439. processorIdentifier: p.identifier,
  440. toDisk: true
  441. )
  442. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  443. XCTAssertNotNil(result.image)
  444. }
  445. func testDefaultCache() {
  446. let exp = expectation(description: #function)
  447. let key = testKeys[0]
  448. let cache = ImageCache.default
  449. cache.store(testImage, forKey: key) { _ in
  450. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  451. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  452. cleanDefaultCache()
  453. exp.fulfill()
  454. }
  455. waitForExpectations(timeout: 3, handler: nil)
  456. }
  457. func testDefaultCacheAsync() async throws {
  458. let key = testKeys[0]
  459. let cache = ImageCache.default
  460. try await cache.store(testImage, forKey: key)
  461. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  462. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  463. cleanDefaultCache()
  464. }
  465. func testRetrieveDiskCacheSynchronously() {
  466. let exp = expectation(description: #function)
  467. let key = testKeys[0]
  468. cache.store(testImage, forKey: key, toDisk: true) { _ in
  469. var cacheType = self.cache.imageCachedType(forKey: key)
  470. XCTAssertEqual(cacheType, .memory)
  471. self.cache.memoryStorage.remove(forKey: key)
  472. cacheType = self.cache.imageCachedType(forKey: key)
  473. XCTAssertEqual(cacheType, .disk)
  474. let dispatched = LockIsolated(false)
  475. self.cache.retrieveImageInDiskCache(forKey: key, options: [.loadDiskFileSynchronously]) {
  476. result in
  477. XCTAssertFalse(dispatched.value)
  478. exp.fulfill()
  479. }
  480. // This should be called after the completion handler above.
  481. dispatched.setValue(true)
  482. }
  483. waitForExpectations(timeout: 3, handler: nil)
  484. }
  485. func testRetrieveDiskCacheAsynchronously() {
  486. let exp = expectation(description: #function)
  487. let key = testKeys[0]
  488. cache.store(testImage, forKey: key, toDisk: true) { _ in
  489. var cacheType = self.cache.imageCachedType(forKey: key)
  490. XCTAssertEqual(cacheType, .memory)
  491. self.cache.memoryStorage.remove(forKey: key)
  492. cacheType = self.cache.imageCachedType(forKey: key)
  493. XCTAssertEqual(cacheType, .disk)
  494. let dispatched = LockIsolated(false)
  495. self.cache.retrieveImageInDiskCache(forKey: key, options: nil) {
  496. result in
  497. XCTAssertTrue(dispatched.value)
  498. exp.fulfill()
  499. }
  500. // This should be called before the completion handler above.
  501. dispatched.setValue(true)
  502. }
  503. waitForExpectations(timeout: 3, handler: nil)
  504. }
  505. #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)
  506. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoad() {
  507. let exp = expectation(description: #function)
  508. let key = testKeys[0]
  509. let modifierCalled = LockIsolated(false)
  510. let modifier = AnyImageModifier { image in
  511. modifierCalled.setValue(true)
  512. return image.withRenderingMode(.alwaysTemplate)
  513. }
  514. cache.store(testImage, original: testImageData, forKey: key) { _ in
  515. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  516. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  517. XCTAssertFalse(modifierCalled.value)
  518. exp.fulfill()
  519. }
  520. }
  521. waitForExpectations(timeout: 3, handler: nil)
  522. }
  523. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoadAsync() async throws {
  524. let key = testKeys[0]
  525. let modifierCalled = LockIsolated(false)
  526. let modifier = AnyImageModifier { image in
  527. modifierCalled.setValue(true)
  528. return image.withRenderingMode(.alwaysTemplate)
  529. }
  530. try await cache.store(testImage, original: testImageData, forKey: key)
  531. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  532. XCTAssertFalse(modifierCalled.value)
  533. XCTAssertEqual(result.image?.renderingMode, .automatic)
  534. }
  535. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoad() {
  536. let exp = expectation(description: #function)
  537. let key = testKeys[0]
  538. let modifierCalled = LockIsolated(false)
  539. let modifier = AnyImageModifier { image in
  540. modifierCalled.setValue(true)
  541. return image.withRenderingMode(.alwaysTemplate)
  542. }
  543. cache.store(testImage, original: testImageData, forKey: key) { _ in
  544. self.cache.clearMemoryCache()
  545. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  546. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  547. XCTAssertFalse(modifierCalled.value)
  548. exp.fulfill()
  549. }
  550. }
  551. waitForExpectations(timeout: 3, handler: nil)
  552. }
  553. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoadAsync() async throws {
  554. let key = testKeys[0]
  555. let modifierCalled = LockIsolated(false)
  556. let modifier = AnyImageModifier { image in
  557. modifierCalled.setValue(true)
  558. return image.withRenderingMode(.alwaysTemplate)
  559. }
  560. try await cache.store(testImage, original: testImageData, forKey: key)
  561. cache.clearMemoryCache()
  562. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  563. XCTAssertFalse(modifierCalled.value)
  564. // The renderingMode is expected to be the default value `.automatic`. The image modifier should only apply to
  565. // the image manager result.
  566. XCTAssertEqual(result.image?.renderingMode, .automatic)
  567. }
  568. #endif
  569. func testStoreToMemoryWithExpiration() {
  570. let exp = expectation(description: #function)
  571. let key = testKeys[0]
  572. cache.store(
  573. testImage,
  574. original: testImageData,
  575. forKey: key,
  576. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.5))]),
  577. toDisk: true)
  578. {
  579. _ in
  580. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  581. delay(1) {
  582. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  583. exp.fulfill()
  584. }
  585. }
  586. waitForExpectations(timeout: 5, handler: nil)
  587. }
  588. func testStoreToMemoryWithExpirationAsync() async throws {
  589. let key = testKeys[0]
  590. try await cache.store(
  591. testImage,
  592. original: testImageData,
  593. forKey: key,
  594. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.5))]),
  595. toDisk: true
  596. )
  597. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  598. // After 1 sec, the cache only remains on disk.
  599. try await Task.sleep(nanoseconds: NSEC_PER_SEC)
  600. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  601. }
  602. func testStoreToDiskWithExpiration() {
  603. let exp = expectation(description: #function)
  604. let key = testKeys[0]
  605. cache.store(
  606. testImage,
  607. original: testImageData,
  608. forKey: key,
  609. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  610. toDisk: true)
  611. {
  612. _ in
  613. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  614. self.cache.clearMemoryCache()
  615. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  616. exp.fulfill()
  617. }
  618. waitForExpectations(timeout: 3, handler: nil)
  619. }
  620. func testStoreToDiskWithExpirationAsync() async throws {
  621. let key = testKeys[0]
  622. try await cache.store(
  623. testImage,
  624. original: testImageData,
  625. forKey: key,
  626. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  627. toDisk: true
  628. )
  629. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  630. self.cache.clearMemoryCache()
  631. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  632. }
  633. func testCalculateDiskStorageSize() {
  634. let exp = expectation(description: #function)
  635. cache.calculateDiskStorageSize { result in
  636. switch result {
  637. case .success(let size):
  638. XCTAssertEqual(size, 0)
  639. self.storeMultipleImages {
  640. self.cache.calculateDiskStorageSize { result in
  641. switch result {
  642. case .success(let size):
  643. XCTAssertEqual(size, UInt(testImagePNGData.count * testKeys.count))
  644. case .failure:
  645. XCTAssert(false)
  646. }
  647. exp.fulfill()
  648. }
  649. }
  650. case .failure:
  651. XCTAssert(false)
  652. exp.fulfill()
  653. }
  654. }
  655. waitForExpectations(timeout: 3, handler: nil)
  656. }
  657. func testDiskCacheStillWorkWhenFolderDeletedExternally() {
  658. let exp = expectation(description: #function)
  659. let key = testKeys[0]
  660. let url = URL(string: key)!
  661. let exists = cache.imageCachedType(forKey: url.cacheKey)
  662. XCTAssertEqual(exists, .none)
  663. cache.store(testImage, forKey: key, toDisk: true) { _ in
  664. self.cache.retrieveImage(forKey: key) { result in
  665. XCTAssertNotNil(result.value?.image)
  666. XCTAssertEqual(result.value?.cacheType, .memory)
  667. self.cache.clearMemoryCache()
  668. self.cache.retrieveImage(forKey: key) { result in
  669. XCTAssertNotNil(result.value?.image)
  670. XCTAssertEqual(result.value?.cacheType, .disk)
  671. self.cache.clearMemoryCache()
  672. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  673. let exists = self.cache.imageCachedType(forKey: url.cacheKey)
  674. XCTAssertEqual(exists, .none)
  675. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  676. self.cache.clearMemoryCache()
  677. let cacheType = self.cache.imageCachedType(forKey: url.cacheKey)
  678. XCTAssertEqual(cacheType, .disk)
  679. exp.fulfill()
  680. }
  681. }
  682. }
  683. }
  684. waitForExpectations(timeout: 3, handler: nil)
  685. }
  686. func testDiskCacheCalculateSizeWhenFolderDeletedExternally() {
  687. let exp = expectation(description: #function)
  688. let key = testKeys[0]
  689. cache.calculateDiskStorageSize { result in
  690. XCTAssertEqual(result.value, 0)
  691. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  692. self.cache.calculateDiskStorageSize { result in
  693. XCTAssertEqual(result.value, UInt(testImagePNGData.count))
  694. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  695. self.cache.calculateDiskStorageSize { result in
  696. XCTAssertEqual(result.value, 0)
  697. exp.fulfill()
  698. }
  699. }
  700. }
  701. }
  702. waitForExpectations(timeout: 3, handler: nil)
  703. }
  704. func testCalculateDiskStorageSizeAsync() async throws {
  705. let size = try await cache.diskStorageSize
  706. XCTAssertEqual(size, 0)
  707. await storeMultipleImages()
  708. let newSize = try await cache.diskStorageSize
  709. XCTAssertEqual(newSize, UInt(testImagePNGData.count * testKeys.count))
  710. }
  711. func testStoreFileWithForcedExtension() async throws {
  712. let key = testKeys[0]
  713. try await cache.store(testImage, forKey: key, forcedExtension: "jpg", toDisk: true)
  714. let pathWithoutExtension = cache.cachePath(forKey: key)
  715. XCTAssertFalse(FileManager.default.fileExists(atPath: pathWithoutExtension))
  716. let pathWithExtension = cache.cachePath(forKey: key, forcedExtension: "jpg")
  717. XCTAssertTrue(FileManager.default.fileExists(atPath: pathWithExtension))
  718. XCTAssertEqual(cache.imageCachedType(forKey: key), .memory)
  719. XCTAssertEqual(cache.imageCachedType(forKey: key, forcedExtension: "jpg"), .memory)
  720. cache.clearMemoryCache()
  721. XCTAssertEqual(cache.imageCachedType(forKey: key), .none)
  722. XCTAssertEqual(cache.imageCachedType(forKey: key, forcedExtension: "jpg"), .disk)
  723. }
  724. func testPossibleCacheFileURLIfOnDiskNotCached() {
  725. let url = URL(string: "https://example.com/photo")!
  726. let resource = LivePhotoResource(downloadURL: url)
  727. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  728. forKey: resource.cacheKey,
  729. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  730. referenceFileType: .heic
  731. )
  732. // Not cached
  733. XCTAssertNil(fileURL)
  734. }
  735. func testPossibleCacheFileURLIfOnDiskCachedWithWrongFileType() async throws {
  736. let url = URL(string: "https://example.com/photo")!
  737. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  738. // Cache without a file type extension
  739. try await cache.storeToDisk(
  740. testImageData,
  741. forKey: resource.cacheKey,
  742. processorIdentifier: LivePhotoImageProcessor.default.identifier
  743. )
  744. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  745. forKey: resource.cacheKey,
  746. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  747. referenceFileType: .heic
  748. )
  749. // Not cached
  750. XCTAssertNil(fileURL)
  751. }
  752. func testPossibleCacheFileURLIfOnDiskCachedWithExplicitFileType() async throws {
  753. let url = URL(string: "https://example.com/photo")!
  754. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  755. // Cache without a file type extension
  756. try await cache.storeToDisk(
  757. testImageData,
  758. forKey: resource.cacheKey,
  759. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  760. forcedExtension: "heic"
  761. )
  762. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  763. forKey: resource.cacheKey,
  764. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  765. referenceFileType: .heic
  766. )
  767. let result = try XCTUnwrap(fileURL)
  768. XCTAssertTrue(result.absoluteString.hasSuffix(".heic"))
  769. }
  770. func testPossibleCacheFileURLIfOnDiskCachedGuessingFileTypeNotHit() async throws {
  771. let url = URL(string: "https://example.com/photo")!
  772. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  773. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  774. forKey: resource.cacheKey,
  775. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  776. referenceFileType: .other("")
  777. )
  778. XCTAssertNil(fileURL)
  779. }
  780. func testPossibleCacheFileURLIfOnDiskCachedGuessingFileType() async throws {
  781. let url = URL(string: "https://example.com/photo")!
  782. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  783. // Cache without a file type extension
  784. try await cache.storeToDisk(
  785. testImageData,
  786. forKey: resource.cacheKey,
  787. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  788. forcedExtension: "heic"
  789. )
  790. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  791. forKey: resource.cacheKey,
  792. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  793. referenceFileType: .other("")
  794. )
  795. let result = try XCTUnwrap(fileURL)
  796. XCTAssertTrue(result.absoluteString.hasSuffix(".heic"))
  797. }
  798. func testPossibleCacheFileURLIfOnDiskCachedArbitraryFileType() async throws {
  799. let url = URL(string: "https://example.com/photo")!
  800. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  801. // Cache without a file type extension
  802. try await cache.storeToDisk(
  803. testImageData,
  804. forKey: resource.cacheKey,
  805. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  806. forcedExtension: "myExt"
  807. )
  808. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  809. forKey: resource.cacheKey,
  810. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  811. referenceFileType: .other("myExt")
  812. )
  813. let result = try XCTUnwrap(fileURL)
  814. XCTAssertTrue(result.absoluteString.hasSuffix(".myExt"))
  815. }
  816. #if !os(macOS) && !os(watchOS)
  817. func testKingfisherWrapperUIApplicationSharedReturnsNilInUnitTest() {
  818. // UIApplication.shared is not available in some Unit Tests contexts.
  819. // This tests that accessing it via KingfisherWrapper does not cause a crash.
  820. XCTAssertNil(KingfisherWrapper<UIApplication>.shared)
  821. }
  822. #endif
  823. // MARK: - Helper
  824. private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
  825. let group = DispatchGroup()
  826. testKeys.forEach {
  827. group.enter()
  828. cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in
  829. group.leave()
  830. }
  831. }
  832. group.notify(queue: .main, execute: completionHandler)
  833. }
  834. private func storeMultipleImages() async {
  835. await withCheckedContinuation {
  836. storeMultipleImages($0.resume)
  837. }
  838. }
  839. }
  840. @dynamicMemberLookup
  841. public final class LockIsolated<Value>: @unchecked Sendable {
  842. private var _value: Value
  843. private let lock = NSRecursiveLock()
  844. /// Initializes lock-isolated state around a value.
  845. ///
  846. /// - Parameter value: A value to isolate with a lock.
  847. public init(_ value: @autoclosure @Sendable () throws -> Value) rethrows {
  848. self._value = try value()
  849. }
  850. public subscript<Subject: Sendable>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
  851. self.lock.sync {
  852. self._value[keyPath: keyPath]
  853. }
  854. }
  855. /// Perform an operation with isolated access to the underlying value.
  856. ///
  857. /// Useful for modifying a value in a single transaction.
  858. ///
  859. /// ```swift
  860. /// // Isolate an integer for concurrent read/write access:
  861. /// var count = LockIsolated(0)
  862. ///
  863. /// func increment() {
  864. /// // Safely increment it:
  865. /// self.count.withValue { $0 += 1 }
  866. /// }
  867. /// ```
  868. ///
  869. /// - Parameter operation: An operation to be performed on the the underlying value with a lock.
  870. /// - Returns: The result of the operation.
  871. public func withValue<T: Sendable>(
  872. _ operation: @Sendable (inout Value) throws -> T
  873. ) rethrows -> T {
  874. try self.lock.sync {
  875. var value = self._value
  876. defer { self._value = value }
  877. return try operation(&value)
  878. }
  879. }
  880. /// Overwrite the isolated value with a new value.
  881. ///
  882. /// ```swift
  883. /// // Isolate an integer for concurrent read/write access:
  884. /// var count = LockIsolated(0)
  885. ///
  886. /// func reset() {
  887. /// // Reset it:
  888. /// self.count.setValue(0)
  889. /// }
  890. /// ```
  891. ///
  892. /// > Tip: Use ``withValue(_:)`` instead of ``setValue(_:)`` if the value being set is derived
  893. /// > from the current value. That is, do this:
  894. /// >
  895. /// > ```swift
  896. /// > self.count.withValue { $0 += 1 }
  897. /// > ```
  898. /// >
  899. /// > ...and not this:
  900. /// >
  901. /// > ```swift
  902. /// > self.count.setValue(self.count + 1)
  903. /// > ```
  904. /// >
  905. /// > ``withValue(_:)`` isolates the entire transaction and avoids data races between reading and
  906. /// > writing the value.
  907. ///
  908. /// - Parameter newValue: The value to replace the current isolated value with.
  909. public func setValue(_ newValue: @autoclosure @Sendable () throws -> Value) rethrows {
  910. try self.lock.sync {
  911. self._value = try newValue()
  912. }
  913. }
  914. }
  915. extension LockIsolated where Value: Sendable {
  916. /// The lock-isolated value.
  917. public var value: Value {
  918. self.lock.sync {
  919. self._value
  920. }
  921. }
  922. }
  923. extension NSRecursiveLock {
  924. @inlinable @discardableResult
  925. @_spi(Internals) public func sync<R>(work: () throws -> R) rethrows -> R {
  926. self.lock()
  927. defer { self.unlock() }
  928. return try work()
  929. }
  930. }