ImageDownloaderTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //
  2. // ImageDownloaderTests.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 XCTest
  27. @testable import Kingfisher
  28. class ImageDownloaderTests: XCTestCase {
  29. var downloader: ImageDownloader!
  30. override class func setUp() {
  31. super.setUp()
  32. LSNocilla.sharedInstance().start()
  33. }
  34. override class func tearDown() {
  35. super.tearDown()
  36. LSNocilla.sharedInstance().stop()
  37. }
  38. override func setUp() {
  39. super.setUp()
  40. // Put setup code here. This method is called before the invocation of each test method in the class.
  41. downloader = ImageDownloader(name: "test")
  42. }
  43. override func tearDown() {
  44. // Put teardown code here. This method is called after the invocation of each test method in the class.
  45. LSNocilla.sharedInstance().clearStubs()
  46. downloader = nil
  47. super.tearDown()
  48. }
  49. func testDownloadAnImage() {
  50. let expectation = expectationWithDescription("wait for downloading image")
  51. let URLString = testKeys[0]
  52. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  53. let URL = NSURL(string: URLString)!
  54. downloader.downloadImageWithURL(URL, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
  55. return
  56. }) { (image, error, imageURL, data) -> () in
  57. expectation.fulfill()
  58. XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL)")
  59. }
  60. waitForExpectationsWithTimeout(5, handler: nil)
  61. }
  62. func testDownloadMultipleImages() {
  63. let expectation = expectationWithDescription("wait for all downloading finish")
  64. let group = dispatch_group_create()
  65. for URLString in testKeys {
  66. if let URL = NSURL(string: URLString) {
  67. dispatch_group_enter(group)
  68. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  69. downloader.downloadImageWithURL(URL, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
  70. }, completionHandler: { (image, error, imageURL, data) -> () in
  71. XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
  72. dispatch_group_leave(group)
  73. })
  74. }
  75. }
  76. dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
  77. expectation.fulfill()
  78. }
  79. waitForExpectationsWithTimeout(5, handler: nil)
  80. }
  81. func testDownloadAnImageWithMultipleCallback() {
  82. let expectation = expectationWithDescription("wait for downloading image")
  83. let group = dispatch_group_create()
  84. let URLString = testKeys[0]
  85. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  86. for _ in 0...5 {
  87. dispatch_group_enter(group)
  88. downloader.downloadImageWithURL(NSURL(string: URLString)!, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
  89. }) { (image, error, imageURL, data) -> () in
  90. XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
  91. dispatch_group_leave(group)
  92. }
  93. }
  94. dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
  95. expectation.fulfill()
  96. }
  97. waitForExpectationsWithTimeout(5, handler: nil)
  98. }
  99. func testDownloadWithModifyingRequest() {
  100. let expectation = expectationWithDescription("wait for downloading image")
  101. let URLString = testKeys[0]
  102. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  103. downloader.requestModifier = {
  104. (request: NSMutableURLRequest) in
  105. request.URL = NSURL(string: URLString)
  106. }
  107. let someURL = NSURL(string: "some_strange_url")!
  108. downloader.downloadImageWithURL(someURL, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
  109. }) { (image, error, imageURL, data) -> () in
  110. XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
  111. XCTAssertEqual(imageURL!, NSURL(string: URLString)!, "The returned imageURL should be the replaced one")
  112. expectation.fulfill()
  113. }
  114. waitForExpectationsWithTimeout(5, handler: nil)
  115. }
  116. func testServerNotModifiedResponse() {
  117. let expectation = expectationWithDescription("wait for server response 304")
  118. let URLString = testKeys[0]
  119. stubRequest("GET", URLString).andReturn(304)
  120. downloader.downloadImageWithURL(NSURL(string: URLString)!, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
  121. }) { (image, error, imageURL, data) -> () in
  122. XCTAssertNotNil(error, "There should be an error since server returning 304 and no image downloaded.")
  123. XCTAssertEqual(error!.code, KingfisherError.NotModified.rawValue, "The error should be NotModified.")
  124. expectation.fulfill()
  125. }
  126. waitForExpectationsWithTimeout(5, handler: nil)
  127. }
  128. // Since we could not receive one challage, no test for trusted hosts currently.
  129. // See http://stackoverflow.com/questions/27065372/why-is-a-https-nsurlsession-connection-only-challenged-once-per-domain for more.
  130. func testSSLCertificateValidation() {
  131. LSNocilla.sharedInstance().stop()
  132. let downloader = ImageDownloader(name: "ssl.test")
  133. let URL = NSURL(string: "https://testssl-expire.disig.sk/Expired.png")!
  134. let expectation = expectationWithDescription("wait for download from an invalid ssl site.")
  135. downloader.downloadImageWithURL(URL, progressBlock: nil, completionHandler: { (image, error, imageURL, data) -> () in
  136. XCTAssertNotNil(error, "Error should not be nil")
  137. XCTAssert(error?.code == NSURLErrorServerCertificateUntrusted || error?.code == NSURLErrorSecureConnectionFailed, "Error should be NSURLErrorServerCertificateUntrusted, but \(error)")
  138. expectation.fulfill()
  139. LSNocilla.sharedInstance().start()
  140. })
  141. waitForExpectationsWithTimeout(20) { (error) in
  142. XCTAssertNil(error, "\(error)")
  143. LSNocilla.sharedInstance().start()
  144. }
  145. }
  146. func testDownloadResultErrorAndRetry() {
  147. let expectation = expectationWithDescription("wait for downloading error")
  148. let URLString = testKeys[0]
  149. stubRequest("GET", URLString).andFailWithError(NSError(domain: "stubError", code: -1, userInfo: nil))
  150. let URL = NSURL(string: URLString)!
  151. downloader.downloadImageWithURL(URL, progressBlock: nil) { (image, error, imageURL, data) -> () in
  152. XCTAssertNotNil(error, "Should return with an error")
  153. LSNocilla.sharedInstance().clearStubs()
  154. stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
  155. // Retry the download
  156. self.downloader.downloadImageWithURL(URL, progressBlock: nil, completionHandler: { (image, error, imageURL, data) -> () in
  157. XCTAssertNil(error, "Download should be finished without error")
  158. expectation.fulfill()
  159. })
  160. }
  161. waitForExpectationsWithTimeout(5, handler: nil)
  162. }
  163. func testDownloadEmptyURL() {
  164. let expectation = expectationWithDescription("wait for downloading error")
  165. downloader.downloadImageWithURL(NSURL(string: "")!, progressBlock: { (receivedSize, totalSize) -> () in
  166. XCTFail("The progress block should not be called.")
  167. }) { (image, error, imageURL, originalData) -> () in
  168. XCTAssertNotNil(error, "An error should happen for empty URL")
  169. XCTAssertEqual(error!.code, KingfisherError.InvalidURL.rawValue)
  170. expectation.fulfill()
  171. }
  172. waitForExpectationsWithTimeout(5, handler: nil)
  173. }
  174. func testDownloadTaskProperty() {
  175. let task = downloader.downloadImageWithURL(NSURL(string: "1234")!, progressBlock: { (receivedSize, totalSize) -> () in
  176. }) { (image, error, imageURL, originalData) -> () in
  177. }
  178. XCTAssertNotNil(task, "The task should exist.")
  179. XCTAssertEqual(task!.ownerDownloader, downloader, "The owner downloader should be correct")
  180. XCTAssertEqual(task!.URL, NSURL(string: "1234"), "The request URL should equal.")
  181. }
  182. func testCancelDownloadTask() {
  183. let expectation = expectationWithDescription("wait for downloading")
  184. let URLString = testKeys[0]
  185. let stub = stubRequest("GET", URLString).andReturn(200).withBody(testImageData).delay()
  186. let URL = NSURL(string: URLString)!
  187. var progressBlockIsCalled = false
  188. var completionBlockIsCalled = false
  189. let downloadTask = downloader.downloadImageWithURL(URL, progressBlock: { (receivedSize, totalSize) -> () in
  190. progressBlockIsCalled = true
  191. }) { (image, error, imageURL, originalData) -> () in
  192. XCTAssertNotNil(error)
  193. XCTAssertEqual(error!.code, NSURLErrorCancelled)
  194. completionBlockIsCalled = true
  195. }
  196. XCTAssertNotNil(downloadTask)
  197. downloadTask!.cancel()
  198. stub.go()
  199. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.09)), dispatch_get_main_queue()) { () -> Void in
  200. expectation.fulfill()
  201. XCTAssert(progressBlockIsCalled == false, "ProgressBlock should not be called since it is canceled.")
  202. XCTAssert(completionBlockIsCalled == true, "CompletionBlock should be called with error.")
  203. }
  204. waitForExpectationsWithTimeout(5, handler: nil)
  205. }
  206. func testDownloadTaskNil() {
  207. let downloadTask = downloader.downloadImageWithURL(NSURL(string: "")!, progressBlock: nil, completionHandler: nil)
  208. XCTAssertNil(downloadTask)
  209. }
  210. }