| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422 |
- //
- // ImageCacheTests.swift
- // Kingfisher
- //
- // Created by Wei Wang on 15/4/10.
- //
- // Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- import XCTest
- @testable import Kingfisher
- class ImageCacheTests: XCTestCase {
- var cache: ImageCache!
- var observer: NSObjectProtocol!
- private var cacheName = "com.onevcat.Kingfisher.ImageCache.test"
-
- override func setUp() {
- super.setUp()
- // Put setup code here. This method is called before the invocation of each test method in the class.
- let uuid = UUID().uuidString
- cacheName = "test-\(uuid)"
- cache = ImageCache(name: cacheName)
- }
-
- override func tearDown() {
- // Put teardown code here. This method is called after the invocation of each test method in the class.
- super.tearDown()
-
- clearCaches([cache])
- cache = nil
- observer = nil
- }
-
- func testCustomCachePath() {
- let customPath = "/path/to/image/cache"
- let cache = ImageCache(name: "test", path: customPath)
- XCTAssertEqual(cache.diskCachePath, customPath + "/com.onevcat.Kingfisher.ImageCache.test", "Custom disk cache path set correctly")
- }
-
- func testMaxCachePeriodInSecond() {
- cache.maxCachePeriodInSecond = 1
- XCTAssert(cache.maxCachePeriodInSecond == 1, "maxCachePeriodInSecond should be able to be set.")
- }
-
- func testMaxMemorySize() {
- cache.maxMemoryCost = 1
- XCTAssert(cache.maxMemoryCost == 1, "maxMemoryCost should be able to be set.")
- }
-
- func testMaxDiskCacheSize() {
- cache.maxDiskCacheSize = 1
- XCTAssert(cache.maxDiskCacheSize == 1, "maxDiskCacheSize should be able to be set.")
- }
-
- func testClearDiskCache() {
-
- let expectation = self.expectation(description: "wait for clearing disk cache")
- let key = testKeys[0]
-
- cache.store(testImage, original: testImageData as Data, forKey: key, toDisk: true) {
- self.cache.clearMemoryCache()
- let cacheResult = self.cache.imageCachedType(forKey: key)
- XCTAssertTrue(cacheResult.cached, "Should be cached")
- XCTAssert(cacheResult == .disk, "Should be cached in disk")
-
- self.cache.clearDiskCache {
- let cacheResult = self.cache.imageCachedType(forKey: key)
- XCTAssertFalse(cacheResult.cached, "Should be not cached")
- expectation.fulfill()
- }
- }
- waitForExpectations(timeout: 10, handler:nil)
- }
-
- func testClearMemoryCache() {
- let expectation = self.expectation(description: "wait for retrieving image")
-
- cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in
- self.cache.clearMemoryCache()
- self.cache.retrieveImage(forKey: testKeys[0], options: nil, completionHandler: { (image, type) -> Void in
- XCTAssert(image != nil && type == .disk, "Should be cached in disk. But \(type)")
- expectation.fulfill()
- })
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testNoImageFound() {
- let expectation = self.expectation(description: "wait for retrieving image")
-
- cache.clearDiskCache {
- self.cache.retrieveImage(forKey: testKeys[0], options: nil, completionHandler: { (image, type) -> Void in
- XCTAssert(image == nil, "Should not be cached in memory yet")
- expectation.fulfill()
- })
- return
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testStoreImageInMemory() {
- let expectation = self.expectation(description: "wait for retrieving image")
-
- cache.store(testImage, forKey: testKeys[0], toDisk: false) { () -> Void in
- self.cache.retrieveImage(forKey: testKeys[0], options: nil, completionHandler: { (image, type) -> Void in
- XCTAssert(image != nil && type == .memory, "Should be cached in memory.")
- expectation.fulfill()
- })
- return
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testStoreMultipleImages() {
- let expectation = self.expectation(description: "wait for writing image")
-
- storeMultipleImages { () -> Void in
- let diskCachePath = self.cache.diskCachePath
- let files: [String]?
- do {
- files = try FileManager.default.contentsOfDirectory(atPath: diskCachePath)
- } catch _ {
- files = nil
- }
- XCTAssert(files?.count == 4, "All test images should be at locaitons. Expected 4, actually \(String(describing: files?.count))")
-
- expectation.fulfill()
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testCachedFileExists() {
- let expectation = self.expectation(description: "cache does contain image")
-
- let URLString = testKeys[0]
- let url = URL(string: URLString)!
-
- let exists = cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertFalse(exists)
-
- cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNil(image, "Should not be cached yet")
-
- XCTAssertEqual(type, .none)
- self.cache.store(testImage, forKey: URLString, toDisk: true) { () -> Void in
- self.cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNotNil(image, "Should be cached (memory or disk)")
- XCTAssertEqual(type, .memory)
- let exists = self.cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertTrue(exists, "Image should exist in the cache (memory or disk)")
- self.cache.clearMemoryCache()
- self.cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNotNil(image, "Should be cached (disk)")
- XCTAssertEqual(type, CacheType.disk)
-
- let exists = self.cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertTrue(exists, "Image should exist in the cache (disk)")
-
- expectation.fulfill()
- })
- })
- }
- })
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testCachedFileDoesNotExist() {
- let URLString = testKeys[0]
- let url = URL(string: URLString)!
-
- let exists = cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertFalse(exists)
- }
- func testCachedFileWithCustomPathExtensionExists() {
- cache.pathExtension = "jpg"
- let expectation = self.expectation(description: "cache with custom path extension does contain image")
-
- let URLString = testKeys[0]
- let url = URL(string: URLString)!
-
- let exists = cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertFalse(exists)
-
- cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNil(image, "Should not be cached yet")
-
- XCTAssertEqual(type, .none)
-
- self.cache.store(testImage, forKey: URLString, toDisk: true) { () -> Void in
- self.cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNotNil(image, "Should be cached (memory or disk)")
- XCTAssertEqual(type, .memory)
-
- let exists = self.cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertTrue(exists, "Image should exist in the cache (memory or disk)")
-
- self.cache.clearMemoryCache()
- self.cache.retrieveImage(forKey: URLString, options: nil, completionHandler: { (image, type) -> Void in
- XCTAssertNotNil(image, "Should be cached (disk)")
- XCTAssertEqual(type, CacheType.disk)
-
- let exists = self.cache.imageCachedType(forKey: url.cacheKey).cached
- XCTAssertTrue(exists, "Image should exist in the cache (disk)")
-
- let cachePath = self.cache.cachePath(forKey: url.cacheKey)
- let hasExtension = cachePath.hasSuffix(".jpg")
- XCTAssert(hasExtension, "Should have .jpg file extension")
-
- expectation.fulfill()
- })
- })
- }
- })
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testCachedImageIsFetchedSyncronouslyFromTheMemoryCache() {
- cache.store(testImage, forKey: testKeys[0], toDisk: false) { () -> Void in
- // do nothing
- }
- var foundImage: Image?
- cache.retrieveImage(forKey: testKeys[0], options: [.backgroundDecode]) { (image, type) -> Void in
- foundImage = image
- }
- XCTAssertEqual(testImage, foundImage, "should have found the image immediately")
- }
- func testIsImageCachedForKey() {
- let expectation = self.expectation(description: "wait for caching image")
-
- XCTAssert(self.cache.imageCachedType(forKey: testKeys[0]).cached == false, "This image should not be cached yet.")
- self.cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in
- XCTAssert(self.cache.imageCachedType(forKey: testKeys[0]).cached == true, "This image should be already cached.")
- expectation.fulfill()
- }
- self.waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testRetrievingImagePerformance() {
- let expectation = self.expectation(description: "wait for retrieving image")
- self.cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in
- self.measure({ () -> Void in
- for _ in 1 ..< 200 {
- _ = self.cache.retrieveImageInDiskCache(forKey: testKeys[0])
- }
- })
- expectation.fulfill()
- }
-
- self.waitForExpectations(timeout: 20, handler: nil)
- }
-
- func testCleanDiskCacheNotification() {
- let expectation = self.expectation(description: "wait for retrieving image")
-
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in
- self.observer = NotificationCenter.default.addObserver(forName: .KingfisherDidCleanDiskCache, object: self.cache, queue: OperationQueue.main, using: { (noti) -> Void in
- let receivedCache = noti.object as? ImageCache
- XCTAssertNotNil(receivedCache)
- XCTAssert(receivedCache === self.cache, "The object of notification should be the cache object.")
-
- guard let hashes = (noti as NSNotification).userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else {
- XCTFail("The clean disk cache notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'")
- expectation.fulfill()
- return
- }
-
- XCTAssertEqual(1, hashes.count, "There should be one and only one file cleaned")
- XCTAssertEqual(hashes.first!, self.cache.hash(forKey: testKeys[0]), "The cleaned file should be the stored one.")
-
- NotificationCenter.default.removeObserver(self.observer)
- expectation.fulfill()
- })
-
- self.cache.maxCachePeriodInSecond = 0
- self.cache.cleanExpiredDiskCache()
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
-
- func testCannotRetrieveCacheWithProcessorIdentifier() {
- let expectation = self.expectation(description: "wait for retrieving image")
- let p = RoundCornerImageProcessor(cornerRadius: 40)
-
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in
-
- self.cache.retrieveImage(forKey: testKeys[0], options: [.processor(p)], completionHandler: { (image, type) -> Void in
-
- XCTAssert(image == nil, "The image with prosossor should not be cached yet.")
-
- expectation.fulfill()
- })
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
- func testRetrieveCacheWithProcessorIdentifier() {
- let expectation = self.expectation(description: "wait for retrieving image")
- let p = RoundCornerImageProcessor(cornerRadius: 40)
-
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], processorIdentifier: p.identifier,toDisk: true) { () -> Void in
-
- self.cache.retrieveImage(forKey: testKeys[0], options: [.processor(p)], completionHandler: { (image, type) -> Void in
-
- XCTAssert(image != nil, "The image with prosossor should already be cached.")
-
- expectation.fulfill()
- })
- }
-
- waitForExpectations(timeout: 5, handler: nil)
- }
- #if os(iOS) || os(tvOS) || os(watchOS)
- func testGettingMemoryCachedImageCouldBeModified() {
- let expectation = self.expectation(description: "wait for retrieving image")
- var modifierCalled = false
- let modifier = AnyImageModifier { image in
- modifierCalled = true
- return image.withRenderingMode(.alwaysTemplate)
- }
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0]) {
- self.cache.retrieveImage(forKey: testKeys[0], options: [.imageModifier(modifier)]) {
- image, _ in
- XCTAssertTrue(modifierCalled)
- XCTAssertEqual(image?.renderingMode, .alwaysTemplate)
- expectation.fulfill()
- }
- }
- waitForExpectations(timeout: 5, handler: nil)
- }
- func testGettingDiskCachedImageCouldBeModified() {
- let expectation = self.expectation(description: "wait for retrieving image")
- var modifierCalled = false
- let modifier = AnyImageModifier { image in
- modifierCalled = true
- return image.withRenderingMode(.alwaysTemplate)
- }
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0]) {
- self.cache.clearMemoryCache()
- self.cache.retrieveImage(forKey: testKeys[0], options: [.imageModifier(modifier)]) {
- image, _ in
- XCTAssertTrue(modifierCalled)
- XCTAssertEqual(image?.renderingMode, .alwaysTemplate)
- expectation.fulfill()
- }
- }
- waitForExpectations(timeout: 5, handler: nil)
- }
- #endif
- // MARK: - Helper
- func storeMultipleImages(_ completionHandler:@escaping ()->()) {
-
- let group = DispatchGroup()
-
- group.enter()
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in
- group.leave()
- }
- group.enter()
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[1], toDisk: true) { () -> Void in
- group.leave()
- }
- group.enter()
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[2], toDisk: true) { () -> Void in
- group.leave()
- }
- group.enter()
- cache.store(testImage, original: testImageData as Data?, forKey: testKeys[3], toDisk: true) { () -> Void in
- group.leave()
- }
-
- group.notify(queue: .main, execute: completionHandler)
- }
- }
|