ImageCacheTests.swift 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 = ActorBox(false)
  510. let modifier = AnyImageModifier { image in
  511. Task {
  512. await modifierCalled.setValue(true)
  513. }
  514. return image.withRenderingMode(.alwaysTemplate)
  515. }
  516. cache.store(testImage, original: testImageData, forKey: key) { _ in
  517. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  518. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  519. Task {
  520. let called = await modifierCalled.value
  521. XCTAssertFalse(called)
  522. exp.fulfill()
  523. }
  524. }
  525. }
  526. waitForExpectations(timeout: 3, handler: nil)
  527. }
  528. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoadAsync() async throws {
  529. let key = testKeys[0]
  530. let modifierCalled = ActorBox(false)
  531. let modifier = AnyImageModifier { image in
  532. Task {
  533. await modifierCalled.setValue(true)
  534. }
  535. return image.withRenderingMode(.alwaysTemplate)
  536. }
  537. try await cache.store(testImage, original: testImageData, forKey: key)
  538. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  539. let called = await modifierCalled.value
  540. XCTAssertFalse(called)
  541. XCTAssertEqual(result.image?.renderingMode, .automatic)
  542. }
  543. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoad() {
  544. let exp = expectation(description: #function)
  545. let key = testKeys[0]
  546. let modifierCalled = ActorBox(false)
  547. let modifier = AnyImageModifier { image in
  548. Task {
  549. await modifierCalled.setValue(true)
  550. }
  551. return image.withRenderingMode(.alwaysTemplate)
  552. }
  553. cache.store(testImage, original: testImageData, forKey: key) { _ in
  554. self.cache.clearMemoryCache()
  555. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  556. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  557. Task {
  558. let called = await modifierCalled.value
  559. XCTAssertFalse(called)
  560. exp.fulfill()
  561. }
  562. }
  563. }
  564. waitForExpectations(timeout: 3, handler: nil)
  565. }
  566. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoadAsync() async throws {
  567. let key = testKeys[0]
  568. let modifierCalled = ActorBox(false)
  569. let modifier = AnyImageModifier { image in
  570. Task {
  571. await modifierCalled.setValue(true)
  572. }
  573. return image.withRenderingMode(.alwaysTemplate)
  574. }
  575. try await cache.store(testImage, original: testImageData, forKey: key)
  576. cache.clearMemoryCache()
  577. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  578. let called = await modifierCalled.value
  579. XCTAssertFalse(called)
  580. // The renderingMode is expected to be the default value `.automatic`. The image modifier should only apply to
  581. // the image manager result.
  582. XCTAssertEqual(result.image?.renderingMode, .automatic)
  583. }
  584. #endif
  585. func testStoreToMemoryWithExpiration() {
  586. let exp = expectation(description: #function)
  587. let key = testKeys[0]
  588. cache.store(
  589. testImage,
  590. original: testImageData,
  591. forKey: key,
  592. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.5))]),
  593. toDisk: true)
  594. {
  595. _ in
  596. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  597. delay(1) {
  598. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  599. exp.fulfill()
  600. }
  601. }
  602. waitForExpectations(timeout: 5, handler: nil)
  603. }
  604. func testStoreToMemoryWithExpirationAsync() async throws {
  605. let key = testKeys[0]
  606. try await cache.store(
  607. testImage,
  608. original: testImageData,
  609. forKey: key,
  610. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.5))]),
  611. toDisk: true
  612. )
  613. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  614. // After 1 sec, the cache only remains on disk.
  615. try await Task.sleep(nanoseconds: NSEC_PER_SEC)
  616. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  617. }
  618. func testStoreToDiskWithExpiration() {
  619. let exp = expectation(description: #function)
  620. let key = testKeys[0]
  621. cache.store(
  622. testImage,
  623. original: testImageData,
  624. forKey: key,
  625. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  626. toDisk: true)
  627. {
  628. _ in
  629. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  630. self.cache.clearMemoryCache()
  631. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  632. exp.fulfill()
  633. }
  634. waitForExpectations(timeout: 3, handler: nil)
  635. }
  636. func testStoreToDiskWithExpirationAsync() async throws {
  637. let key = testKeys[0]
  638. try await cache.store(
  639. testImage,
  640. original: testImageData,
  641. forKey: key,
  642. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  643. toDisk: true
  644. )
  645. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  646. self.cache.clearMemoryCache()
  647. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  648. }
  649. func testCalculateDiskStorageSize() {
  650. let exp = expectation(description: #function)
  651. cache.calculateDiskStorageSize { result in
  652. switch result {
  653. case .success(let size):
  654. XCTAssertEqual(size, 0)
  655. self.storeMultipleImages {
  656. self.cache.calculateDiskStorageSize { result in
  657. switch result {
  658. case .success(let size):
  659. XCTAssertEqual(size, UInt(testImagePNGData.count * testKeys.count))
  660. case .failure:
  661. XCTAssert(false)
  662. }
  663. exp.fulfill()
  664. }
  665. }
  666. case .failure:
  667. XCTAssert(false)
  668. exp.fulfill()
  669. }
  670. }
  671. waitForExpectations(timeout: 3, handler: nil)
  672. }
  673. func testDiskCacheStillWorkWhenFolderDeletedExternally() {
  674. let exp = expectation(description: #function)
  675. let key = testKeys[0]
  676. let url = URL(string: key)!
  677. let exists = cache.imageCachedType(forKey: url.cacheKey)
  678. XCTAssertEqual(exists, .none)
  679. cache.store(testImage, forKey: key, toDisk: true) { _ in
  680. self.cache.retrieveImage(forKey: key) { result in
  681. XCTAssertNotNil(result.value?.image)
  682. XCTAssertEqual(result.value?.cacheType, .memory)
  683. self.cache.clearMemoryCache()
  684. self.cache.retrieveImage(forKey: key) { result in
  685. XCTAssertNotNil(result.value?.image)
  686. XCTAssertEqual(result.value?.cacheType, .disk)
  687. self.cache.clearMemoryCache()
  688. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  689. let exists = self.cache.imageCachedType(forKey: url.cacheKey)
  690. XCTAssertEqual(exists, .none)
  691. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  692. self.cache.clearMemoryCache()
  693. let cacheType = self.cache.imageCachedType(forKey: url.cacheKey)
  694. XCTAssertEqual(cacheType, .disk)
  695. exp.fulfill()
  696. }
  697. }
  698. }
  699. }
  700. waitForExpectations(timeout: 3, handler: nil)
  701. }
  702. func testDiskCacheCalculateSizeWhenFolderDeletedExternally() {
  703. let exp = expectation(description: #function)
  704. let key = testKeys[0]
  705. cache.calculateDiskStorageSize { result in
  706. XCTAssertEqual(result.value, 0)
  707. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  708. self.cache.calculateDiskStorageSize { result in
  709. XCTAssertEqual(result.value, UInt(testImagePNGData.count))
  710. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  711. self.cache.calculateDiskStorageSize { result in
  712. XCTAssertEqual(result.value, 0)
  713. exp.fulfill()
  714. }
  715. }
  716. }
  717. }
  718. waitForExpectations(timeout: 3, handler: nil)
  719. }
  720. func testCalculateDiskStorageSizeAsync() async throws {
  721. let size = try await cache.diskStorageSize
  722. XCTAssertEqual(size, 0)
  723. await storeMultipleImages()
  724. let newSize = try await cache.diskStorageSize
  725. XCTAssertEqual(newSize, UInt(testImagePNGData.count * testKeys.count))
  726. }
  727. func testStoreFileWithForcedExtension() async throws {
  728. let key = testKeys[0]
  729. try await cache.store(testImage, forKey: key, forcedExtension: "jpg", toDisk: true)
  730. let pathWithoutExtension = cache.cachePath(forKey: key)
  731. XCTAssertFalse(FileManager.default.fileExists(atPath: pathWithoutExtension))
  732. let pathWithExtension = cache.cachePath(forKey: key, forcedExtension: "jpg")
  733. XCTAssertTrue(FileManager.default.fileExists(atPath: pathWithExtension))
  734. XCTAssertEqual(cache.imageCachedType(forKey: key), .memory)
  735. XCTAssertEqual(cache.imageCachedType(forKey: key, forcedExtension: "jpg"), .memory)
  736. cache.clearMemoryCache()
  737. XCTAssertEqual(cache.imageCachedType(forKey: key), .none)
  738. XCTAssertEqual(cache.imageCachedType(forKey: key, forcedExtension: "jpg"), .disk)
  739. }
  740. func testPossibleCacheFileURLIfOnDiskNotCached() {
  741. let url = URL(string: "https://example.com/photo")!
  742. let resource = LivePhotoResource(downloadURL: url)
  743. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  744. forKey: resource.cacheKey,
  745. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  746. referenceFileType: .heic
  747. )
  748. // Not cached
  749. XCTAssertNil(fileURL)
  750. }
  751. func testPossibleCacheFileURLIfOnDiskCachedWithWrongFileType() async throws {
  752. let url = URL(string: "https://example.com/photo")!
  753. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  754. // Cache without a file type extension
  755. try await cache.storeToDisk(
  756. testImageData,
  757. forKey: resource.cacheKey,
  758. processorIdentifier: LivePhotoImageProcessor.default.identifier
  759. )
  760. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  761. forKey: resource.cacheKey,
  762. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  763. referenceFileType: .heic
  764. )
  765. // Not cached
  766. XCTAssertNil(fileURL)
  767. }
  768. func testPossibleCacheFileURLIfOnDiskCachedWithExplicitFileType() async throws {
  769. let url = URL(string: "https://example.com/photo")!
  770. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  771. // Cache without a file type extension
  772. try await cache.storeToDisk(
  773. testImageData,
  774. forKey: resource.cacheKey,
  775. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  776. forcedExtension: "heic"
  777. )
  778. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  779. forKey: resource.cacheKey,
  780. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  781. referenceFileType: .heic
  782. )
  783. let result = try XCTUnwrap(fileURL)
  784. XCTAssertTrue(result.absoluteString.hasSuffix(".heic"))
  785. }
  786. func testPossibleCacheFileURLIfOnDiskCachedGuessingFileTypeNotHit() async throws {
  787. let url = URL(string: "https://example.com/photo")!
  788. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  789. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  790. forKey: resource.cacheKey,
  791. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  792. referenceFileType: .other("")
  793. )
  794. XCTAssertNil(fileURL)
  795. }
  796. func testPossibleCacheFileURLIfOnDiskCachedGuessingFileType() async throws {
  797. let url = URL(string: "https://example.com/photo")!
  798. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  799. // Cache without a file type extension
  800. try await cache.storeToDisk(
  801. testImageData,
  802. forKey: resource.cacheKey,
  803. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  804. forcedExtension: "heic"
  805. )
  806. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  807. forKey: resource.cacheKey,
  808. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  809. referenceFileType: .other("")
  810. )
  811. let result = try XCTUnwrap(fileURL)
  812. XCTAssertTrue(result.absoluteString.hasSuffix(".heic"))
  813. }
  814. func testPossibleCacheFileURLIfOnDiskCachedArbitraryFileType() async throws {
  815. let url = URL(string: "https://example.com/photo")!
  816. let resource = LivePhotoResource(downloadURL: url, fileType: .heic)
  817. // Cache without a file type extension
  818. try await cache.storeToDisk(
  819. testImageData,
  820. forKey: resource.cacheKey,
  821. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  822. forcedExtension: "myExt"
  823. )
  824. let fileURL = cache.possibleCacheFileURLIfOnDisk(
  825. forKey: resource.cacheKey,
  826. processorIdentifier: LivePhotoImageProcessor.default.identifier,
  827. referenceFileType: .other("myExt")
  828. )
  829. let result = try XCTUnwrap(fileURL)
  830. XCTAssertTrue(result.absoluteString.hasSuffix(".myExt"))
  831. }
  832. #if !os(macOS) && !os(watchOS)
  833. func testKingfisherWrapperUIApplicationSharedReturnsNilInUnitTest() {
  834. // UIApplication.shared is not available in some Unit Tests contexts.
  835. // This tests that accessing it via KingfisherWrapper does not cause a crash.
  836. XCTAssertNil(KingfisherWrapper<UIApplication>.shared)
  837. }
  838. #endif
  839. // MARK: - Helper
  840. private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
  841. let group = DispatchGroup()
  842. testKeys.forEach {
  843. group.enter()
  844. cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in
  845. group.leave()
  846. }
  847. }
  848. group.notify(queue: .main, execute: completionHandler)
  849. }
  850. private func storeMultipleImages() async {
  851. await withCheckedContinuation {
  852. storeMultipleImages($0.resume)
  853. }
  854. }
  855. }
  856. @dynamicMemberLookup
  857. public final class LockIsolated<Value>: @unchecked Sendable {
  858. private var _value: Value
  859. private let lock = NSRecursiveLock()
  860. /// Initializes lock-isolated state around a value.
  861. ///
  862. /// - Parameter value: A value to isolate with a lock.
  863. public init(_ value: @autoclosure @Sendable () throws -> Value) rethrows {
  864. self._value = try value()
  865. }
  866. public subscript<Subject: Sendable>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
  867. self.lock.sync {
  868. self._value[keyPath: keyPath]
  869. }
  870. }
  871. /// Perform an operation with isolated access to the underlying value.
  872. ///
  873. /// Useful for modifying a value in a single transaction.
  874. ///
  875. /// ```swift
  876. /// // Isolate an integer for concurrent read/write access:
  877. /// var count = LockIsolated(0)
  878. ///
  879. /// func increment() {
  880. /// // Safely increment it:
  881. /// self.count.withValue { $0 += 1 }
  882. /// }
  883. /// ```
  884. ///
  885. /// - Parameter operation: An operation to be performed on the the underlying value with a lock.
  886. /// - Returns: The result of the operation.
  887. public func withValue<T: Sendable>(
  888. _ operation: @Sendable (inout Value) throws -> T
  889. ) rethrows -> T {
  890. try self.lock.sync {
  891. var value = self._value
  892. defer { self._value = value }
  893. return try operation(&value)
  894. }
  895. }
  896. /// Overwrite the isolated value with a new value.
  897. ///
  898. /// ```swift
  899. /// // Isolate an integer for concurrent read/write access:
  900. /// var count = LockIsolated(0)
  901. ///
  902. /// func reset() {
  903. /// // Reset it:
  904. /// self.count.setValue(0)
  905. /// }
  906. /// ```
  907. ///
  908. /// > Tip: Use ``withValue(_:)`` instead of ``setValue(_:)`` if the value being set is derived
  909. /// > from the current value. That is, do this:
  910. /// >
  911. /// > ```swift
  912. /// > self.count.withValue { $0 += 1 }
  913. /// > ```
  914. /// >
  915. /// > ...and not this:
  916. /// >
  917. /// > ```swift
  918. /// > self.count.setValue(self.count + 1)
  919. /// > ```
  920. /// >
  921. /// > ``withValue(_:)`` isolates the entire transaction and avoids data races between reading and
  922. /// > writing the value.
  923. ///
  924. /// - Parameter newValue: The value to replace the current isolated value with.
  925. public func setValue(_ newValue: @autoclosure @Sendable () throws -> Value) rethrows {
  926. try self.lock.sync {
  927. self._value = try newValue()
  928. }
  929. }
  930. }
  931. extension LockIsolated where Value: Sendable {
  932. /// The lock-isolated value.
  933. public var value: Value {
  934. self.lock.sync {
  935. self._value
  936. }
  937. }
  938. }
  939. extension NSRecursiveLock {
  940. @inlinable @discardableResult
  941. @_spi(Internals) public func sync<R>(work: () throws -> R) rethrows -> R {
  942. self.lock()
  943. defer { self.unlock() }
  944. return try work()
  945. }
  946. }