ImageCacheTests.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. // MARK: - Helper
  673. private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
  674. let group = DispatchGroup()
  675. testKeys.forEach {
  676. group.enter()
  677. cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in
  678. group.leave()
  679. }
  680. }
  681. group.notify(queue: .main, execute: completionHandler)
  682. }
  683. private func storeMultipleImages() async {
  684. await withCheckedContinuation {
  685. storeMultipleImages($0.resume)
  686. }
  687. }
  688. }
  689. @dynamicMemberLookup
  690. public final class LockIsolated<Value>: @unchecked Sendable {
  691. private var _value: Value
  692. private let lock = NSRecursiveLock()
  693. /// Initializes lock-isolated state around a value.
  694. ///
  695. /// - Parameter value: A value to isolate with a lock.
  696. public init(_ value: @autoclosure @Sendable () throws -> Value) rethrows {
  697. self._value = try value()
  698. }
  699. public subscript<Subject: Sendable>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
  700. self.lock.sync {
  701. self._value[keyPath: keyPath]
  702. }
  703. }
  704. /// Perform an operation with isolated access to the underlying value.
  705. ///
  706. /// Useful for modifying a value in a single transaction.
  707. ///
  708. /// ```swift
  709. /// // Isolate an integer for concurrent read/write access:
  710. /// var count = LockIsolated(0)
  711. ///
  712. /// func increment() {
  713. /// // Safely increment it:
  714. /// self.count.withValue { $0 += 1 }
  715. /// }
  716. /// ```
  717. ///
  718. /// - Parameter operation: An operation to be performed on the the underlying value with a lock.
  719. /// - Returns: The result of the operation.
  720. public func withValue<T: Sendable>(
  721. _ operation: @Sendable (inout Value) throws -> T
  722. ) rethrows -> T {
  723. try self.lock.sync {
  724. var value = self._value
  725. defer { self._value = value }
  726. return try operation(&value)
  727. }
  728. }
  729. /// Overwrite the isolated value with a new value.
  730. ///
  731. /// ```swift
  732. /// // Isolate an integer for concurrent read/write access:
  733. /// var count = LockIsolated(0)
  734. ///
  735. /// func reset() {
  736. /// // Reset it:
  737. /// self.count.setValue(0)
  738. /// }
  739. /// ```
  740. ///
  741. /// > Tip: Use ``withValue(_:)`` instead of ``setValue(_:)`` if the value being set is derived
  742. /// > from the current value. That is, do this:
  743. /// >
  744. /// > ```swift
  745. /// > self.count.withValue { $0 += 1 }
  746. /// > ```
  747. /// >
  748. /// > ...and not this:
  749. /// >
  750. /// > ```swift
  751. /// > self.count.setValue(self.count + 1)
  752. /// > ```
  753. /// >
  754. /// > ``withValue(_:)`` isolates the entire transaction and avoids data races between reading and
  755. /// > writing the value.
  756. ///
  757. /// - Parameter newValue: The value to replace the current isolated value with.
  758. public func setValue(_ newValue: @autoclosure @Sendable () throws -> Value) rethrows {
  759. try self.lock.sync {
  760. self._value = try newValue()
  761. }
  762. }
  763. }
  764. extension LockIsolated where Value: Sendable {
  765. /// The lock-isolated value.
  766. public var value: Value {
  767. self.lock.sync {
  768. self._value
  769. }
  770. }
  771. }
  772. extension NSRecursiveLock {
  773. @inlinable @discardableResult
  774. @_spi(Internals) public func sync<R>(work: () throws -> R) rethrows -> R {
  775. self.lock()
  776. defer { self.unlock() }
  777. return try work()
  778. }
  779. }