ImageCacheTests.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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 testCachedImageIsFetchedSyncronouslyFromTheMemoryCache() {
  264. cache.store(testImage, forKey: testKeys[0], toDisk: false)
  265. var foundImage: KFCrossPlatformImage?
  266. cache.retrieveImage(forKey: testKeys[0]) { result in
  267. foundImage = result.value?.image
  268. }
  269. XCTAssertEqual(testImage, foundImage)
  270. }
  271. func testCachedImageIsFetchedSyncronouslyFromTheMemoryCacheAsync() async throws {
  272. try await cache.store(testImage, forKey: testKeys[0], toDisk: false)
  273. let result = try await cache.retrieveImage(forKey: testKeys[0])
  274. XCTAssertEqual(testImage, result.image)
  275. }
  276. func testIsImageCachedForKey() {
  277. let exp = expectation(description: #function)
  278. let key = testKeys[0]
  279. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  280. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  281. XCTAssertTrue(self.cache.imageCachedType(forKey: key).cached)
  282. exp.fulfill()
  283. }
  284. waitForExpectations(timeout: 3, handler: nil)
  285. }
  286. func testIsImageCachedForKeyAsync() async throws {
  287. let key = testKeys[0]
  288. XCTAssertFalse(cache.imageCachedType(forKey: key).cached)
  289. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  290. XCTAssertTrue(cache.imageCachedType(forKey: key).cached)
  291. }
  292. func testCleanDiskCacheNotification() {
  293. let exp = expectation(description: #function)
  294. let key = testKeys[0]
  295. cache.diskStorage.config.expiration = .seconds(0.01)
  296. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  297. self.observer = NotificationCenter.default.addObserver(
  298. forName: .KingfisherDidCleanDiskCache,
  299. object: self.cache,
  300. queue: .main) {
  301. noti in
  302. let receivedCache = noti.object as? ImageCache
  303. XCTAssertNotNil(receivedCache)
  304. XCTAssertTrue(receivedCache === self.cache)
  305. guard let hashes = noti.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else {
  306. XCTFail("Notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'")
  307. exp.fulfill()
  308. return
  309. }
  310. XCTAssertEqual(hashes.count, 1)
  311. XCTAssertEqual(hashes.first!, self.cache.hash(forKey: key))
  312. guard let o = self.observer else { return }
  313. NotificationCenter.default.removeObserver(o)
  314. exp.fulfill()
  315. }
  316. delay(1) {
  317. self.cache.cleanExpiredDiskCache()
  318. }
  319. }
  320. waitForExpectations(timeout: 5, handler: nil)
  321. }
  322. func testCannotRetrieveCacheWithProcessorIdentifier() {
  323. let exp = expectation(description: #function)
  324. let key = testKeys[0]
  325. let p = RoundCornerImageProcessor(cornerRadius: 40)
  326. cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in
  327. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  328. XCTAssertNotNil(result.value)
  329. XCTAssertNil(result.value!.image)
  330. exp.fulfill()
  331. }
  332. }
  333. waitForExpectations(timeout: 3, handler: nil)
  334. }
  335. func testCannotRetrieveCacheWithProcessorIdentifierAsync() async throws {
  336. let key = testKeys[0]
  337. let p = RoundCornerImageProcessor(cornerRadius: 40)
  338. try await cache.store(testImage, original: testImageData, forKey: key, toDisk: true)
  339. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  340. XCTAssertNotNil(result)
  341. XCTAssertNil(result.image)
  342. }
  343. func testRetrieveCacheWithProcessorIdentifier() {
  344. let exp = expectation(description: #function)
  345. let key = testKeys[0]
  346. let p = RoundCornerImageProcessor(cornerRadius: 40)
  347. cache.store(
  348. testImage,
  349. original: testImageData,
  350. forKey: key,
  351. processorIdentifier: p.identifier,
  352. toDisk: true)
  353. {
  354. _ in
  355. self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in
  356. XCTAssertNotNil(result.value?.image)
  357. exp.fulfill()
  358. }
  359. }
  360. waitForExpectations(timeout: 3, handler: nil)
  361. }
  362. func testRetrieveCacheWithProcessorIdentifierAsync() async throws {
  363. let key = testKeys[0]
  364. let p = RoundCornerImageProcessor(cornerRadius: 40)
  365. try await cache.store(
  366. testImage,
  367. original: testImageData,
  368. forKey: key,
  369. processorIdentifier: p.identifier,
  370. toDisk: true
  371. )
  372. let result = try await cache.retrieveImage(forKey: key, options: [.processor(p)])
  373. XCTAssertNotNil(result.image)
  374. }
  375. func testDefaultCache() {
  376. let exp = expectation(description: #function)
  377. let key = testKeys[0]
  378. let cache = ImageCache.default
  379. cache.store(testImage, forKey: key) { _ in
  380. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  381. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  382. cleanDefaultCache()
  383. exp.fulfill()
  384. }
  385. waitForExpectations(timeout: 3, handler: nil)
  386. }
  387. func testDefaultCacheAsync() async throws {
  388. let key = testKeys[0]
  389. let cache = ImageCache.default
  390. try await cache.store(testImage, forKey: key)
  391. XCTAssertTrue(cache.memoryStorage.isCached(forKey: key))
  392. XCTAssertTrue(cache.diskStorage.isCached(forKey: key))
  393. cleanDefaultCache()
  394. }
  395. func testRetrieveDiskCacheSynchronously() {
  396. let exp = expectation(description: #function)
  397. let key = testKeys[0]
  398. cache.store(testImage, forKey: key, toDisk: true) { _ in
  399. var cacheType = self.cache.imageCachedType(forKey: key)
  400. XCTAssertEqual(cacheType, .memory)
  401. self.cache.memoryStorage.remove(forKey: key)
  402. cacheType = self.cache.imageCachedType(forKey: key)
  403. XCTAssertEqual(cacheType, .disk)
  404. var dispatched = false
  405. self.cache.retrieveImageInDiskCache(forKey: key, options: [.loadDiskFileSynchronously]) {
  406. result in
  407. XCTAssertFalse(dispatched)
  408. exp.fulfill()
  409. }
  410. // This should be called after the completion handler above.
  411. dispatched = true
  412. }
  413. waitForExpectations(timeout: 3, handler: nil)
  414. }
  415. func testRetrieveDiskCacheAsynchronously() {
  416. let exp = expectation(description: #function)
  417. let key = testKeys[0]
  418. cache.store(testImage, forKey: key, toDisk: true) { _ in
  419. var cacheType = self.cache.imageCachedType(forKey: key)
  420. XCTAssertEqual(cacheType, .memory)
  421. self.cache.memoryStorage.remove(forKey: key)
  422. cacheType = self.cache.imageCachedType(forKey: key)
  423. XCTAssertEqual(cacheType, .disk)
  424. var dispatched = false
  425. self.cache.retrieveImageInDiskCache(forKey: key, options: nil) {
  426. result in
  427. XCTAssertTrue(dispatched)
  428. exp.fulfill()
  429. }
  430. // This should be called before the completion handler above.
  431. dispatched = true
  432. }
  433. waitForExpectations(timeout: 3, handler: nil)
  434. }
  435. #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)
  436. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoad() {
  437. let exp = expectation(description: #function)
  438. let key = testKeys[0]
  439. var modifierCalled = false
  440. let modifier = AnyImageModifier { image in
  441. modifierCalled = true
  442. return image.withRenderingMode(.alwaysTemplate)
  443. }
  444. cache.store(testImage, original: testImageData, forKey: key) { _ in
  445. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  446. XCTAssertFalse(modifierCalled)
  447. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  448. exp.fulfill()
  449. }
  450. }
  451. waitForExpectations(timeout: 3, handler: nil)
  452. }
  453. func testModifierShouldOnlyApplyForFinalResultWhenMemoryLoadAsync() async throws {
  454. let key = testKeys[0]
  455. var modifierCalled = false
  456. let modifier = AnyImageModifier { image in
  457. modifierCalled = true
  458. return image.withRenderingMode(.alwaysTemplate)
  459. }
  460. try await cache.store(testImage, original: testImageData, forKey: key)
  461. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  462. XCTAssertFalse(modifierCalled)
  463. XCTAssertEqual(result.image?.renderingMode, .automatic)
  464. }
  465. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoad() {
  466. let exp = expectation(description: #function)
  467. let key = testKeys[0]
  468. var modifierCalled = false
  469. let modifier = AnyImageModifier { image in
  470. modifierCalled = true
  471. return image.withRenderingMode(.alwaysTemplate)
  472. }
  473. cache.store(testImage, original: testImageData, forKey: key) { _ in
  474. self.cache.clearMemoryCache()
  475. self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in
  476. XCTAssertFalse(modifierCalled)
  477. XCTAssertEqual(result.value?.image?.renderingMode, .automatic)
  478. exp.fulfill()
  479. }
  480. }
  481. waitForExpectations(timeout: 3, handler: nil)
  482. }
  483. func testModifierShouldOnlyApplyForFinalResultWhenDiskLoadAsync() async throws {
  484. let key = testKeys[0]
  485. var modifierCalled = false
  486. let modifier = AnyImageModifier { image in
  487. modifierCalled = true
  488. return image.withRenderingMode(.alwaysTemplate)
  489. }
  490. try await cache.store(testImage, original: testImageData, forKey: key)
  491. cache.clearMemoryCache()
  492. let result = try await cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)])
  493. XCTAssertFalse(modifierCalled)
  494. // The renderingMode is expected to be the default value `.automatic`. The image modifier should only apply to
  495. // the image manager result.
  496. XCTAssertEqual(result.image?.renderingMode, .automatic)
  497. }
  498. #endif
  499. func testStoreToMemoryWithExpiration() {
  500. let exp = expectation(description: #function)
  501. let key = testKeys[0]
  502. cache.store(
  503. testImage,
  504. original: testImageData,
  505. forKey: key,
  506. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.2))]),
  507. toDisk: true)
  508. {
  509. _ in
  510. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  511. delay(1) {
  512. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  513. exp.fulfill()
  514. }
  515. }
  516. waitForExpectations(timeout: 5, handler: nil)
  517. }
  518. func testStoreToMemoryWithExpirationAsync() async throws {
  519. let key = testKeys[0]
  520. try await cache.store(
  521. testImage,
  522. original: testImageData,
  523. forKey: key,
  524. options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.2))]),
  525. toDisk: true
  526. )
  527. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  528. // After 1 sec, the cache only remains on disk.
  529. try await Task.sleep(nanoseconds: NSEC_PER_SEC)
  530. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk)
  531. }
  532. func testStoreToDiskWithExpiration() {
  533. let exp = expectation(description: #function)
  534. let key = testKeys[0]
  535. cache.store(
  536. testImage,
  537. original: testImageData,
  538. forKey: key,
  539. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  540. toDisk: true)
  541. {
  542. _ in
  543. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  544. self.cache.clearMemoryCache()
  545. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  546. exp.fulfill()
  547. }
  548. waitForExpectations(timeout: 3, handler: nil)
  549. }
  550. func testStoreToDiskWithExpirationAsync() async throws {
  551. let key = testKeys[0]
  552. try await cache.store(
  553. testImage,
  554. original: testImageData,
  555. forKey: key,
  556. options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]),
  557. toDisk: true
  558. )
  559. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory)
  560. self.cache.clearMemoryCache()
  561. XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none)
  562. }
  563. func testCalculateDiskStorageSize() {
  564. let exp = expectation(description: #function)
  565. cache.calculateDiskStorageSize { result in
  566. switch result {
  567. case .success(let size):
  568. XCTAssertEqual(size, 0)
  569. self.storeMultipleImages {
  570. self.cache.calculateDiskStorageSize { result in
  571. switch result {
  572. case .success(let size):
  573. XCTAssertEqual(size, UInt(testImagePNGData.count * testKeys.count))
  574. case .failure:
  575. XCTAssert(false)
  576. }
  577. exp.fulfill()
  578. }
  579. }
  580. case .failure:
  581. XCTAssert(false)
  582. exp.fulfill()
  583. }
  584. }
  585. waitForExpectations(timeout: 3, handler: nil)
  586. }
  587. func testDiskCacheStillWorkWhenFolderDeletedExternally() {
  588. let exp = expectation(description: #function)
  589. let key = testKeys[0]
  590. let url = URL(string: key)!
  591. let exists = cache.imageCachedType(forKey: url.cacheKey)
  592. XCTAssertEqual(exists, .none)
  593. cache.store(testImage, forKey: key, toDisk: true) { _ in
  594. self.cache.retrieveImage(forKey: key) { result in
  595. XCTAssertNotNil(result.value?.image)
  596. XCTAssertEqual(result.value?.cacheType, .memory)
  597. self.cache.clearMemoryCache()
  598. self.cache.retrieveImage(forKey: key) { result in
  599. XCTAssertNotNil(result.value?.image)
  600. XCTAssertEqual(result.value?.cacheType, .disk)
  601. self.cache.clearMemoryCache()
  602. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  603. let exists = self.cache.imageCachedType(forKey: url.cacheKey)
  604. XCTAssertEqual(exists, .none)
  605. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  606. self.cache.clearMemoryCache()
  607. let cacheType = self.cache.imageCachedType(forKey: url.cacheKey)
  608. XCTAssertEqual(cacheType, .disk)
  609. exp.fulfill()
  610. }
  611. }
  612. }
  613. }
  614. waitForExpectations(timeout: 3, handler: nil)
  615. }
  616. func testDiskCacheCalculateSizeWhenFolderDeletedExternally() {
  617. let exp = expectation(description: #function)
  618. let key = testKeys[0]
  619. cache.calculateDiskStorageSize { result in
  620. XCTAssertEqual(result.value, 0)
  621. self.cache.store(testImage, forKey: key, toDisk: true) { _ in
  622. self.cache.calculateDiskStorageSize { result in
  623. XCTAssertEqual(result.value, UInt(testImagePNGData.count))
  624. try! FileManager.default.removeItem(at: self.cache.diskStorage.directoryURL)
  625. self.cache.calculateDiskStorageSize { result in
  626. XCTAssertEqual(result.value, 0)
  627. exp.fulfill()
  628. }
  629. }
  630. }
  631. }
  632. waitForExpectations(timeout: 3, handler: nil)
  633. }
  634. func testCalculateDiskStorageSizeAsync() async throws {
  635. let size = try await cache.diskStorageSize
  636. XCTAssertEqual(size, 0)
  637. await storeMultipleImages()
  638. let newSize = try await cache.diskStorageSize
  639. XCTAssertEqual(newSize, UInt(testImagePNGData.count * testKeys.count))
  640. }
  641. // MARK: - Helper
  642. private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
  643. let group = DispatchGroup()
  644. testKeys.forEach {
  645. group.enter()
  646. cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in
  647. group.leave()
  648. }
  649. }
  650. group.notify(queue: .main, execute: completionHandler)
  651. }
  652. private func storeMultipleImages() async {
  653. await withCheckedContinuation {
  654. storeMultipleImages($0.resume)
  655. }
  656. }
  657. }