ImageCacheTests.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. func testCachedImageIsFetchedSynchronouslyFromTheMemoryCache() {
  264. cache.store(testImage, forKey: testKeys[0], toDisk: false)
  265. let foundImage = ActorBox<KFCrossPlatformImage?>(nil)
  266. cache.retrieveImage(forKey: testKeys[0]) { result in
  267. Task {
  268. await foundImage.setValue(result.value?.image)
  269. }
  270. }
  271. Task {
  272. let value = await foundImage.value
  273. XCTAssertEqual(testImage, value)
  274. }
  275. }
  276. func testCachedImageIsFetchedSynchronouslyFromTheMemoryCacheAsync() async throws {
  277. try await cache.store(testImage, forKey: testKeys[0], toDisk: false)
  278. let result = try await cache.retrieveImage(forKey: testKeys[0])
  279. XCTAssertEqual(testImage, result.image)
  280. }
  281. func testIsImageCachedForKey() {
  282. let exp = expectation(description: #function)
  283. let key = testKeys[0]
  284. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  285. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  286. XCTAssertTrue(self.cache.imageCachedType(forKey: key).cached)
  287. exp.fulfill()
  288. }
  289. waitForExpectations(timeout: 3, handler: nil)
  290. }
  291. func testIsImageCachedForKeyAsync() async throws {
  292. let key = testKeys[0]
  293. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  294. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  295. XCTAssertTrue(cache.imageCachedType(forKey: key).cached)
  296. }
  297. func testCleanDiskCacheNotification() {
  298. let exp = expectation(description: #function)
  299. let key = testKeys[0]
  300. cache.diskStorage.config.expiration = .seconds(0.01)
  301. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  302. self.observer = NotificationCenter.default.addObserver(
  303. forName: .KingfisherDidCleanDiskCache,
  304. object: self.cache,
  305. queue: .main) {
  306. noti in
  307. let receivedCache = noti.object as? ImageCache
  308. XCTAssertNotNil(receivedCache)
  309. XCTAssertTrue(receivedCache === self.cache)
  310. guard let hashes = noti.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else {
  311. XCTFail("Notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'")
  312. exp.fulfill()
  313. return
  314. }
  315. XCTAssertEqual(hashes.count, 1)
  316. XCTAssertEqual(hashes.first!, self.cache.hash(forKey: key))
  317. guard let o = self.observer else { return }
  318. NotificationCenter.default.removeObserver(o)
  319. exp.fulfill()
  320. }
  321. delay(1) {
  322. self.cache.cleanExpiredDiskCache()
  323. }
  324. }
  325. waitForExpectations(timeout: 5, handler: nil)
  326. }
  327. func testCannotRetrieveCacheWithProcessorIdentifier() {
  328. let exp = expectation(description: #function)
  329. let key = testKeys[0]
  330. let p = RoundCornerImageProcessor(cornerRadius: 40)
  331. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  332. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  333. XCTAssertNotNil(result.value)
  334. XCTAssertNil(result.value!.image)
  335. exp.fulfill()
  336. }
  337. }
  338. waitForExpectations(timeout: 3, handler: nil)
  339. }
  340. func testCannotRetrieveCacheWithProcessorIdentifierAsync() async throws {
  341. let key = testKeys[0]
  342. let p = RoundCornerImageProcessor(cornerRadius: 40)
  343. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  344. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  345. XCTAssertNotNil(result)
  346. XCTAssertNil(result.image)
  347. }
  348. func testRetrieveCacheWithProcessorIdentifier() {
  349. let exp = expectation(description: #function)
  350. let key = testKeys[0]
  351. let p = RoundCornerImageProcessor(cornerRadius: 40)
  352. cache.store(
  353. testImage,
  354. original: testImageData,
  355. forKey: key,
  356. processorIdentifier: p.identifier,
  357. toDisk: true)
  358. {
  359. _ in
  360. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  361. XCTAssertNotNil(result.value?.image)
  362. exp.fulfill()
  363. }
  364. }
  365. waitForExpectations(timeout: 3, handler: nil)
  366. }
  367. func testRetrieveCacheWithProcessorIdentifierAsync() async throws {
  368. let key = testKeys[0]
  369. let p = RoundCornerImageProcessor(cornerRadius: 40)
  370. try await cache.store(
  371. testImage,
  372. original: testImageData,
  373. forKey: key,
  374. processorIdentifier: p.identifier,
  375. toDisk: true
  376. )
  377. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  378. XCTAssertNotNil(result.image)
  379. }
  380. func testDefaultCache() {
  381. let exp = expectation(description: #function)
  382. let key = testKeys[0]
  383. let cache = ImageCache.default
  384. cache.store(testImage, forKey: key) { _ in
  385. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  386. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  387. cleanDefaultCache()
  388. exp.fulfill()
  389. }
  390. waitForExpectations(timeout: 3, handler: nil)
  391. }
  392. func testDefaultCacheAsync() async throws {
  393. let key = testKeys[0]
  394. let cache = ImageCache.default
  395. try await cache.store(testImage, forKey: key)
  396. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  397. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  398. cleanDefaultCache()
  399. }
  400. func testRetrieveDiskCacheSynchronously() {
  401. let exp = expectation(description: #function)
  402. let key = testKeys[0]
  403. cache.store(testImage, forKey: key, toDisk: true) { _ in
  404. var cacheType = self.cache.imageCachedType(forKey: key)
  405. XCTAssertEqual(cacheType, .memory)
  406. self.cache.memoryStorage.remove(forKey: key)
  407. cacheType = self.cache.imageCachedType(forKey: key)
  408. XCTAssertEqual(cacheType, .disk)
  409. let dispatched = LockIsolated(false)
  410. self.cache.retrieveImageInDiskCache(forKey: key, options: [.loadDiskFileSynchronously]) {
  411. result in
  412. XCTAssertFalse(dispatched.value)
  413. exp.fulfill()
  414. }
  415. // This should be called after the completion handler above.
  416. dispatched.setValue(true)
  417. }
  418. waitForExpectations(timeout: 3, handler: nil)
  419. }
  420. func testRetrieveDiskCacheAsynchronously() {
  421. let exp = expectation(description: #function)
  422. let key = testKeys[0]
  423. cache.store(testImage, forKey: key, toDisk: true) { _ in
  424. var cacheType = self.cache.imageCachedType(forKey: key)
  425. XCTAssertEqual(cacheType, .memory)
  426. self.cache.memoryStorage.remove(forKey: key)
  427. cacheType = self.cache.imageCachedType(forKey: key)
  428. XCTAssertEqual(cacheType, .disk)
  429. let dispatched = LockIsolated(false)
  430. self.cache.retrieveImageInDiskCache(forKey: key, options: nil) {
  431. result in
  432. XCTAssertTrue(dispatched.value)
  433. exp.fulfill()
  434. }
  435. // This should be called before the completion handler above.
  436. dispatched.setValue(true)
  437. }
  438. waitForExpectations(timeout: 3, handler: nil)
  439. }
  440. #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)
  441. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoad() {
  442. let exp = expectation(description: #function)
  443. let key = testKeys[0]
  444. let modifierCalled = ActorBox(false)
  445. let modifier = AnyImageModifier { image in
  446. Task {
  447. await modifierCalled.setValue(true)
  448. }
  449. return image.withRenderingMode(.alwaysTemplate)
  450. }
  451. cache.store(testImage, original: testImageData, forKey: key) { _ in
  452. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  453. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  454. Task {
  455. let called = await modifierCalled.value
  456. XCTAssertFalse(called)
  457. exp.fulfill()
  458. }
  459. }
  460. }
  461. waitForExpectations(timeout: 3, handler: nil)
  462. }
  463. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoadAsync() async throws {
  464. let key = testKeys[0]
  465. let modifierCalled = ActorBox(false)
  466. let modifier = AnyImageModifier { image in
  467. Task {
  468. await modifierCalled.setValue(true)
  469. }
  470. return image.withRenderingMode(.alwaysTemplate)
  471. }
  472. try await cache.store(testImage, original: testImageData, forKey: key)
  473. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  474. let called = await modifierCalled.value
  475. XCTAssertFalse(called)
  476. XCTAssertEqual(result.image?.renderingMode, .automatic)
  477. }
  478. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoad() {
  479. let exp = expectation(description: #function)
  480. let key = testKeys[0]
  481. let modifierCalled = ActorBox(false)
  482. let modifier = AnyImageModifier { image in
  483. Task {
  484. await modifierCalled.setValue(true)
  485. }
  486. return image.withRenderingMode(.alwaysTemplate)
  487. }
  488. cache.store(testImage, original: testImageData, forKey: key) { _ in
  489. self.cache.clearMemoryCache()
  490. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  491. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  492. Task {
  493. let called = await modifierCalled.value
  494. XCTAssertFalse(called)
  495. exp.fulfill()
  496. }
  497. }
  498. }
  499. waitForExpectations(timeout: 3, handler: nil)
  500. }
  501. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoadAsync() async throws {
  502. let key = testKeys[0]
  503. let modifierCalled = ActorBox(false)
  504. let modifier = AnyImageModifier { image in
  505. Task {
  506. await modifierCalled.setValue(true)
  507. }
  508. return image.withRenderingMode(.alwaysTemplate)
  509. }
  510. try await cache.store(testImage, original: testImageData, forKey: key)
  511. cache.clearMemoryCache()
  512. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  513. let called = await modifierCalled.value
  514. XCTAssertFalse(called)
  515. // The renderingMode is expected to be the default value `.automatic`. The image modifier should only apply to
  516. // the image manager result.
  517. XCTAssertEqual(result.image?.renderingMode, .automatic)
  518. }
  519. #endif
  520. func testStoreToMemoryWithExpiration() {
  521. let exp = expectation(description: #function)
  522. let key = testKeys[0]
  523. cache.store(
  524. testImage,
  525. original: testImageData,
  526. forKey: key,
  527. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.2))]),
  528. toDisk: true)
  529. {
  530. _ in
  531. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  532. delay(1) {
  533. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  534. exp.fulfill()
  535. }
  536. }
  537. waitForExpectations(timeout: 5, handler: nil)
  538. }
  539. func testStoreToMemoryWithExpirationAsync() async throws {
  540. let key = testKeys[0]
  541. try await cache.store(
  542. testImage,
  543. original: testImageData,
  544. forKey: key,
  545. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.2))]),
  546. toDisk: true
  547. )
  548. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  549. // After 1 sec, the cache only remains on disk.
  550. try await Task.sleep(nanoseconds: NSEC_PER_SEC)
  551. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  552. }
  553. func testStoreToDiskWithExpiration() {
  554. let exp = expectation(description: #function)
  555. let key = testKeys[0]
  556. cache.store(
  557. testImage,
  558. original: testImageData,
  559. forKey: key,
  560. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  561. toDisk: true)
  562. {
  563. _ in
  564. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  565. self.cache.clearMemoryCache()
  566. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  567. exp.fulfill()
  568. }
  569. waitForExpectations(timeout: 3, handler: nil)
  570. }
  571. func testStoreToDiskWithExpirationAsync() async throws {
  572. let key = testKeys[0]
  573. try await cache.store(
  574. testImage,
  575. original: testImageData,
  576. forKey: key,
  577. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  578. toDisk: true
  579. )
  580. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  581. self.cache.clearMemoryCache()
  582. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  583. }
  584. func testCalculateDiskStorageSize() {
  585. let exp = expectation(description: #function)
  586. cache.calculateDiskStorageSize { result in
  587. switch result {
  588. case .success(let size):
  589. XCTAssertEqual(size, 0)
  590. self.storeMultipleImages {
  591. self.cache.calculateDiskStorageSize { result in
  592. switch result {
  593. case .success(let size):
  594. XCTAssertEqual(size, UInt(testImagePNGData.count * testKeys.count))
  595. case .failure:
  596. XCTAssert(false)
  597. }
  598. exp.fulfill()
  599. }
  600. }
  601. case .failure:
  602. XCTAssert(false)
  603. exp.fulfill()
  604. }
  605. }
  606. waitForExpectations(timeout: 3, handler: nil)
  607. }
  608. func testDiskCacheStillWorkWhenFolderDeletedExternally() {
  609. let exp = expectation(description: #function)
  610. let key = testKeys[0]
  611. let url = URL(string: key)!
  612. let exists = cache.imageCachedType(forKey: url.cacheKey)
  613. XCTAssertEqual(exists, .none)
  614. cache.store(testImage, forKey: key, toDisk: true) { _ in
  615. self.cache.retrieveImage(forKey: key) { result in
  616. XCTAssertNotNil(result.value?.image)
  617. XCTAssertEqual(result.value?.cacheType, .memory)
  618. self.cache.clearMemoryCache()
  619. self.cache.retrieveImage(forKey: key) { result in
  620. XCTAssertNotNil(result.value?.image)
  621. XCTAssertEqual(result.value?.cacheType, .disk)
  622. self.cache.clearMemoryCache()
  623. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  624. let exists = self.cache.imageCachedType(forKey: url.cacheKey)
  625. XCTAssertEqual(exists, .none)
  626. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  627. self.cache.clearMemoryCache()
  628. let cacheType = self.cache.imageCachedType(forKey: url.cacheKey)
  629. XCTAssertEqual(cacheType, .disk)
  630. exp.fulfill()
  631. }
  632. }
  633. }
  634. }
  635. waitForExpectations(timeout: 3, handler: nil)
  636. }
  637. func testDiskCacheCalculateSizeWhenFolderDeletedExternally() {
  638. let exp = expectation(description: #function)
  639. let key = testKeys[0]
  640. cache.calculateDiskStorageSize { result in
  641. XCTAssertEqual(result.value, 0)
  642. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  643. self.cache.calculateDiskStorageSize { result in
  644. XCTAssertEqual(result.value, UInt(testImagePNGData.count))
  645. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  646. self.cache.calculateDiskStorageSize { result in
  647. XCTAssertEqual(result.value, 0)
  648. exp.fulfill()
  649. }
  650. }
  651. }
  652. }
  653. waitForExpectations(timeout: 3, handler: nil)
  654. }
  655. func testCalculateDiskStorageSizeAsync() async throws {
  656. let size = try await cache.diskStorageSize
  657. XCTAssertEqual(size, 0)
  658. await storeMultipleImages()
  659. let newSize = try await cache.diskStorageSize
  660. XCTAssertEqual(newSize, UInt(testImagePNGData.count * testKeys.count))
  661. }
  662. // MARK: - Helper
  663. private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
  664. let group = DispatchGroup()
  665. testKeys.forEach {
  666. group.enter()
  667. cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in
  668. group.leave()
  669. }
  670. }
  671. group.notify(queue: .main, execute: completionHandler)
  672. }
  673. private func storeMultipleImages() async {
  674. await withCheckedContinuation {
  675. storeMultipleImages($0.resume)
  676. }
  677. }
  678. }
  679. @dynamicMemberLookup
  680. public final class LockIsolated<Value>: @unchecked Sendable {
  681. private var _value: Value
  682. private let lock = NSRecursiveLock()
  683. /// Initializes lock-isolated state around a value.
  684. ///
  685. /// - Parameter value: A value to isolate with a lock.
  686. public init(_ value: @autoclosure @Sendable () throws -> Value) rethrows {
  687. self._value = try value()
  688. }
  689. public subscript<Subject: Sendable>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
  690. self.lock.sync {
  691. self._value[keyPath: keyPath]
  692. }
  693. }
  694. /// Perform an operation with isolated access to the underlying value.
  695. ///
  696. /// Useful for modifying a value in a single transaction.
  697. ///
  698. /// ```swift
  699. /// // Isolate an integer for concurrent read/write access:
  700. /// var count = LockIsolated(0)
  701. ///
  702. /// func increment() {
  703. /// // Safely increment it:
  704. /// self.count.withValue { $0 += 1 }
  705. /// }
  706. /// ```
  707. ///
  708. /// - Parameter operation: An operation to be performed on the the underlying value with a lock.
  709. /// - Returns: The result of the operation.
  710. public func withValue<T: Sendable>(
  711. _ operation: @Sendable (inout Value) throws -> T
  712. ) rethrows -> T {
  713. try self.lock.sync {
  714. var value = self._value
  715. defer { self._value = value }
  716. return try operation(&value)
  717. }
  718. }
  719. /// Overwrite the isolated value with a new value.
  720. ///
  721. /// ```swift
  722. /// // Isolate an integer for concurrent read/write access:
  723. /// var count = LockIsolated(0)
  724. ///
  725. /// func reset() {
  726. /// // Reset it:
  727. /// self.count.setValue(0)
  728. /// }
  729. /// ```
  730. ///
  731. /// > Tip: Use ``withValue(_:)`` instead of ``setValue(_:)`` if the value being set is derived
  732. /// > from the current value. That is, do this:
  733. /// >
  734. /// > ```swift
  735. /// > self.count.withValue { $0 += 1 }
  736. /// > ```
  737. /// >
  738. /// > ...and not this:
  739. /// >
  740. /// > ```swift
  741. /// > self.count.setValue(self.count + 1)
  742. /// > ```
  743. /// >
  744. /// > ``withValue(_:)`` isolates the entire transaction and avoids data races between reading and
  745. /// > writing the value.
  746. ///
  747. /// - Parameter newValue: The value to replace the current isolated value with.
  748. public func setValue(_ newValue: @autoclosure @Sendable () throws -> Value) rethrows {
  749. try self.lock.sync {
  750. self._value = try newValue()
  751. }
  752. }
  753. }
  754. extension LockIsolated where Value: Sendable {
  755. /// The lock-isolated value.
  756. public var value: Value {
  757. self.lock.sync {
  758. self._value
  759. }
  760. }
  761. }
  762. extension NSRecursiveLock {
  763. @inlinable @discardableResult
  764. @_spi(Internals) public func sync<R>(work: () throws -> R) rethrows -> R {
  765. self.lock()
  766. defer { self.unlock() }
  767. return try work()
  768. }
  769. }