ImageCacheTests.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. //
  2. // ImageCacheTests.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/10.
  6. //
  7. // Copyright (c) 2015 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 UIKit
  27. import XCTest
  28. @testable import Kingfisher
  29. private let cacheName = "com.onevcat.Kingfisher.ImageCache.test"
  30. class ImageCacheTests: XCTestCase {
  31. var cache: ImageCache!
  32. var observer: NSObjectProtocol!
  33. override func setUp() {
  34. super.setUp()
  35. // Put setup code here. This method is called before the invocation of each test method in the class.
  36. cache = ImageCache(name: "test")
  37. clearCaches([cache])
  38. }
  39. override func tearDown() {
  40. // Put teardown code here. This method is called after the invocation of each test method in the class.
  41. super.tearDown()
  42. clearCaches([cache])
  43. cache = nil
  44. observer = nil
  45. }
  46. func testCustomCachePath() {
  47. let customPath = "/path/to/image/cache"
  48. let cache = ImageCache(name: "test", path: customPath)
  49. XCTAssertEqual(cache.diskCachePath, customPath + "/com.onevcat.Kingfisher.ImageCache.test", "Custom disk cache path set correctly")
  50. }
  51. func testMaxCachePeriodInSecond() {
  52. cache.maxCachePeriodInSecond = 1
  53. XCTAssert(cache.maxCachePeriodInSecond == 1, "maxCachePeriodInSecond should be able to be set.")
  54. }
  55. func testMaxMemorySize() {
  56. cache.maxMemoryCost = 1
  57. XCTAssert(cache.maxMemoryCost == 1, "maxMemoryCost should be able to be set.")
  58. }
  59. func testMaxDiskCacheSize() {
  60. cache.maxDiskCacheSize = 1
  61. XCTAssert(cache.maxDiskCacheSize == 1, "maxDiskCacheSize should be able to be set.")
  62. }
  63. func testClearDiskCache() {
  64. let expectation = expectationWithDescription("wait for clearing disk cache")
  65. let key = testKeys[0]
  66. cache.storeImage(testImage, originalData: testImageData, forKey: key, toDisk: true) { () -> () in
  67. self.cache.clearMemoryCache()
  68. let cacheResult = self.cache.isImageCachedForKey(key)
  69. XCTAssertTrue(cacheResult.cached, "Should be cached")
  70. XCTAssert(cacheResult.cacheType == .Disk, "Should be cached in disk")
  71. self.cache.clearDiskCacheWithCompletionHandler { () -> () in
  72. let cacheResult = self.cache.isImageCachedForKey(key)
  73. XCTAssertFalse(cacheResult.cached, "Should be not cached")
  74. expectation.fulfill()
  75. }
  76. }
  77. waitForExpectationsWithTimeout(10, handler:nil)
  78. }
  79. func testClearMemoryCache() {
  80. let expectation = expectationWithDescription("wait for retrieving image")
  81. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[0], toDisk: true) { () -> () in
  82. self.cache.clearMemoryCache()
  83. self.cache.retrieveImageForKey(testKeys[0], options: KingfisherManager.OptionsNone, completionHandler: { (image, type) -> () in
  84. XCTAssert(image != nil && type == .Disk, "Should be cached in disk.")
  85. expectation.fulfill()
  86. })
  87. }
  88. waitForExpectationsWithTimeout(5, handler: nil)
  89. }
  90. func testNoImageFound() {
  91. let expectation = expectationWithDescription("wait for retrieving image")
  92. cache.clearDiskCacheWithCompletionHandler { () -> () in
  93. self.cache.retrieveImageForKey(testKeys[0], options: KingfisherManager.OptionsNone, completionHandler: { (image, type) -> () in
  94. XCTAssert(image == nil, "Should not be cached in memory yet")
  95. expectation.fulfill()
  96. })
  97. return
  98. }
  99. waitForExpectationsWithTimeout(5, handler: nil)
  100. }
  101. func testStoreImageInMemory() {
  102. let expectation = expectationWithDescription("wait for retrieving image")
  103. cache.storeImage(testImage, forKey: testKeys[0], toDisk: false) { () -> () in
  104. self.cache.retrieveImageForKey(testKeys[0], options: KingfisherManager.OptionsNone, completionHandler: { (image, type) -> () in
  105. XCTAssert(image != nil && type == .Memory, "Should be cached in memory.")
  106. expectation.fulfill()
  107. })
  108. return
  109. }
  110. waitForExpectationsWithTimeout(5, handler: nil)
  111. }
  112. func testStoreMultipleImages() {
  113. let expectation = expectationWithDescription("wait for writing image")
  114. storeMultipleImages { () -> () in
  115. let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
  116. let diskCachePath = (paths.first! as NSString).stringByAppendingPathComponent(cacheName)
  117. let files: [AnyObject]?
  118. do {
  119. files = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(diskCachePath)
  120. } catch _ {
  121. files = nil
  122. }
  123. XCTAssert(files?.count == 4, "All test images should be at locaitons. Expected 4, actually \(files?.count)")
  124. expectation.fulfill()
  125. }
  126. waitForExpectationsWithTimeout(5, handler: nil)
  127. }
  128. func testIsImageCachedForKey() {
  129. let expectation = self.expectationWithDescription("wait for caching image")
  130. XCTAssert(self.cache.isImageCachedForKey(testKeys[0]).cached == false, "This image should not be cached yet.")
  131. self.cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[0], toDisk: true) { () -> () in
  132. XCTAssert(self.cache.isImageCachedForKey(testKeys[0]).cached == true, "This image should be already cached.")
  133. expectation.fulfill()
  134. }
  135. self.waitForExpectationsWithTimeout(5, handler: nil)
  136. }
  137. func testRetrievingImagePerformance() {
  138. let expectation = self.expectationWithDescription("wait for retrieving image")
  139. self.cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[0], toDisk: true) { () -> () in
  140. self.measureBlock({ () -> Void in
  141. for _ in 1 ..< 1000 {
  142. self.cache.retrieveImageInDiskCacheForKey(testKeys[0])
  143. }
  144. })
  145. expectation.fulfill()
  146. }
  147. self.waitForExpectationsWithTimeout(20, handler: nil)
  148. }
  149. func testCleanDiskCacheNotification() {
  150. let expectation = expectationWithDescription("wait for retrieving image")
  151. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[0], toDisk: true) { () -> () in
  152. self.observer = NSNotificationCenter.defaultCenter().addObserverForName(KingfisherDidCleanDiskCacheNotification, object: self.cache, queue: NSOperationQueue.mainQueue(), usingBlock: { (noti) -> Void in
  153. XCTAssert(noti.object === self.cache, "The object of notification should be the cache object.")
  154. guard let hashes = noti.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else {
  155. XCTFail("The clean disk cache notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'")
  156. expectation.fulfill()
  157. return
  158. }
  159. XCTAssertEqual(1, hashes.count, "There should be one and only one file cleaned")
  160. XCTAssertEqual(hashes.first!, self.cache.hashForKey(testKeys[0]), "The cleaned file should be the stored one.")
  161. NSNotificationCenter.defaultCenter().removeObserver(self.observer)
  162. expectation.fulfill()
  163. })
  164. self.cache.maxCachePeriodInSecond = 0
  165. self.cache.cleanExpiredDiskCache()
  166. }
  167. waitForExpectationsWithTimeout(5, handler: nil)
  168. }
  169. // MARK: - Helper
  170. func storeMultipleImages(completionHandler:()->()) {
  171. let group = dispatch_group_create()
  172. dispatch_group_enter(group)
  173. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[0], toDisk: true) { () -> () in
  174. dispatch_group_leave(group)
  175. }
  176. dispatch_group_enter(group)
  177. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[1], toDisk: true) { () -> () in
  178. dispatch_group_leave(group)
  179. }
  180. dispatch_group_enter(group)
  181. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[2], toDisk: true) { () -> () in
  182. dispatch_group_leave(group)
  183. }
  184. dispatch_group_enter(group)
  185. cache.storeImage(testImage, originalData: testImageData, forKey: testKeys[3], toDisk: true) { () -> () in
  186. dispatch_group_leave(group)
  187. }
  188. dispatch_group_notify(group, dispatch_get_main_queue()) {
  189. completionHandler()
  190. }
  191. }
  192. }