ImageCacheTests.swift 37 KB

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