ImageCacheTests.swift 37 KB

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