UploadTests.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. // UploadTests.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Alamofire
  23. import Foundation
  24. import XCTest
  25. class UploadFileInitializationTestCase: BaseTestCase {
  26. func testUploadClassMethodWithMethodURLAndFile() {
  27. // Given
  28. let URLString = "http://httpbin.org/"
  29. let imageURL = URLForResource("rainbow", withExtension: "jpg")
  30. // When
  31. let request = Alamofire.upload(.POST, URLString, file: imageURL)
  32. // Then
  33. XCTAssertNotNil(request.request, "request should not be nil")
  34. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  35. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  36. XCTAssertNil(request.response, "response should be nil")
  37. }
  38. func testUploadClassMethodWithMethodURLHeadersAndFile() {
  39. // Given
  40. let URLString = "http://httpbin.org/"
  41. let imageURL = URLForResource("rainbow", withExtension: "jpg")
  42. // When
  43. let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], file: imageURL)
  44. // Then
  45. XCTAssertNotNil(request.request, "request should not be nil")
  46. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  47. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  48. let authorizationHeader = request.request.valueForHTTPHeaderField("Authorization") ?? ""
  49. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  50. XCTAssertNil(request.response, "response should be nil")
  51. }
  52. }
  53. // MARK: -
  54. class UploadDataInitializationTestCase: BaseTestCase {
  55. func testUploadClassMethodWithMethodURLAndData() {
  56. // Given
  57. let URLString = "http://httpbin.org/"
  58. // When
  59. let request = Alamofire.upload(.POST, URLString, data: NSData())
  60. // Then
  61. XCTAssertNotNil(request.request, "request should not be nil")
  62. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  63. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  64. XCTAssertNil(request.response, "response should be nil")
  65. }
  66. func testUploadClassMethodWithMethodURLHeadersAndData() {
  67. // Given
  68. let URLString = "http://httpbin.org/"
  69. // When
  70. let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], data: NSData())
  71. // Then
  72. XCTAssertNotNil(request.request, "request should not be nil")
  73. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  74. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  75. let authorizationHeader = request.request.valueForHTTPHeaderField("Authorization") ?? ""
  76. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  77. XCTAssertNil(request.response, "response should be nil")
  78. }
  79. }
  80. // MARK: -
  81. class UploadStreamInitializationTestCase: BaseTestCase {
  82. func testUploadClassMethodWithMethodURLAndStream() {
  83. // Given
  84. let URLString = "http://httpbin.org/"
  85. let imageURL = URLForResource("rainbow", withExtension: "jpg")
  86. let imageStream = NSInputStream(URL: imageURL)!
  87. // When
  88. let request = Alamofire.upload(.POST, URLString, stream: imageStream)
  89. // Then
  90. XCTAssertNotNil(request.request, "request should not be nil")
  91. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  92. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  93. XCTAssertNil(request.response, "response should be nil")
  94. }
  95. func testUploadClassMethodWithMethodURLHeadersAndStream() {
  96. // Given
  97. let URLString = "http://httpbin.org/"
  98. let imageURL = URLForResource("rainbow", withExtension: "jpg")
  99. let imageStream = NSInputStream(URL: imageURL)!
  100. // When
  101. let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], stream: imageStream)
  102. // Then
  103. XCTAssertNotNil(request.request, "request should not be nil")
  104. XCTAssertEqual(request.request.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
  105. XCTAssertEqual(request.request.URL!, NSURL(string: URLString)!, "request URL should be equal")
  106. let authorizationHeader = request.request.valueForHTTPHeaderField("Authorization") ?? ""
  107. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  108. XCTAssertNil(request.response, "response should be nil")
  109. }
  110. }
  111. // MARK: -
  112. class UploadDataTestCase: BaseTestCase {
  113. func testUploadDataRequest() {
  114. // Given
  115. let URLString = "http://httpbin.org/post"
  116. let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  117. let expectation = expectationWithDescription("Upload request should succeed: \(URLString)")
  118. var request: NSURLRequest?
  119. var response: NSHTTPURLResponse?
  120. var error: NSError?
  121. // When
  122. Alamofire.upload(.POST, URLString, data: data)
  123. .response { responseRequest, responseResponse, _, responseError in
  124. request = responseRequest
  125. response = responseResponse
  126. error = responseError
  127. expectation.fulfill()
  128. }
  129. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  130. // Then
  131. XCTAssertNotNil(request, "request should not be nil")
  132. XCTAssertNotNil(response, "response should not be nil")
  133. XCTAssertNil(error, "error should be nil")
  134. }
  135. func testUploadDataRequestWithProgress() {
  136. // Given
  137. let URLString = "http://httpbin.org/post"
  138. let data: NSData = {
  139. var text = ""
  140. for _ in 1...3_000 {
  141. text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
  142. }
  143. return text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  144. }()
  145. let expectation = expectationWithDescription("Bytes upload progress should be reported: \(URLString)")
  146. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  147. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  148. var responseRequest: NSURLRequest?
  149. var responseResponse: NSHTTPURLResponse?
  150. var responseData: AnyObject?
  151. var responseError: NSError?
  152. // When
  153. let upload = Alamofire.upload(.POST, URLString, data: data)
  154. upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
  155. let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
  156. byteValues.append(bytes)
  157. let progress = (completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount)
  158. progressValues.append(progress)
  159. }
  160. upload.response { request, response, data, error in
  161. responseRequest = request
  162. responseResponse = response
  163. responseData = data
  164. responseError = error
  165. expectation.fulfill()
  166. }
  167. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  168. // Then
  169. XCTAssertNotNil(responseRequest, "response request should not be nil")
  170. XCTAssertNotNil(responseResponse, "response response should not be nil")
  171. XCTAssertNotNil(responseData, "response data should not be nil")
  172. XCTAssertNil(responseError, "response error should be nil")
  173. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  174. if byteValues.count == progressValues.count {
  175. for index in 0..<byteValues.count {
  176. let byteValue = byteValues[index]
  177. let progressValue = progressValues[index]
  178. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  179. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  180. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  181. }
  182. }
  183. if let
  184. lastByteValue = byteValues.last,
  185. lastProgressValue = progressValues.last
  186. {
  187. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  188. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  189. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  190. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  191. } else {
  192. XCTFail("last item in bytesValues and progressValues should not be nil")
  193. }
  194. }
  195. }
  196. // MARK: -
  197. class UploadMultipartFormDataTestCase: BaseTestCase {
  198. // MARK: Tests
  199. func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
  200. // Given
  201. let URLString = "http://httpbin.org/post"
  202. let uploadData = "upload_data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  203. let expectation = expectationWithDescription("multipart form data upload should succeed")
  204. var formData: MultipartFormData?
  205. var request: NSURLRequest?
  206. var response: NSHTTPURLResponse?
  207. var data: AnyObject?
  208. var error: NSError?
  209. // When
  210. Alamofire.upload(
  211. .POST,
  212. URLString: URLString,
  213. multipartFormData: { multipartFormData in
  214. multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
  215. formData = multipartFormData
  216. },
  217. encodingCompletion: { result in
  218. switch result {
  219. case .Success(let upload, _, _):
  220. upload.response { responseRequest, responseResponse, responseData, responseError in
  221. request = responseRequest
  222. response = responseResponse
  223. data = responseData
  224. error = responseError
  225. expectation.fulfill()
  226. }
  227. case .Failure:
  228. expectation.fulfill()
  229. }
  230. }
  231. )
  232. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  233. // Then
  234. XCTAssertNotNil(request, "request should not be nil")
  235. XCTAssertNotNil(response, "response should not be nil")
  236. XCTAssertNotNil(data, "data should not be nil")
  237. XCTAssertNil(error, "error should be nil")
  238. if let
  239. request = request,
  240. multipartFormData = formData,
  241. contentType = request.valueForHTTPHeaderField("Content-Type")
  242. {
  243. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  244. } else {
  245. XCTFail("Content-Type header value should not be nil")
  246. }
  247. }
  248. func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
  249. // Given
  250. let URLString = "http://httpbin.org/post"
  251. let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  252. let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  253. let expectation = expectationWithDescription("multipart form data upload should succeed")
  254. var request: NSURLRequest?
  255. var response: NSHTTPURLResponse?
  256. var data: AnyObject?
  257. var error: NSError?
  258. // When
  259. Alamofire.upload(
  260. .POST,
  261. URLString: URLString,
  262. multipartFormData: { multipartFormData in
  263. multipartFormData.appendBodyPart(data: french, name: "french")
  264. multipartFormData.appendBodyPart(data: japanese, name: "japanese")
  265. },
  266. encodingCompletion: { result in
  267. switch result {
  268. case .Success(let upload, _, _):
  269. upload.response { responseRequest, responseResponse, responseData, responseError in
  270. request = responseRequest
  271. response = responseResponse
  272. data = responseData
  273. error = responseError
  274. expectation.fulfill()
  275. }
  276. case .Failure:
  277. expectation.fulfill()
  278. }
  279. }
  280. )
  281. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  282. // Then
  283. XCTAssertNotNil(request, "request should not be nil")
  284. XCTAssertNotNil(response, "response should not be nil")
  285. XCTAssertNotNil(data, "data should not be nil")
  286. XCTAssertNil(error, "error should be nil")
  287. }
  288. func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
  289. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
  290. }
  291. func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
  292. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
  293. }
  294. func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
  295. // Given
  296. let URLString = "http://httpbin.org/post"
  297. let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  298. let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  299. let expectation = expectationWithDescription("multipart form data upload should succeed")
  300. var streamingFromDisk: Bool?
  301. var streamFileURL: NSURL?
  302. // When
  303. Alamofire.upload(
  304. .POST,
  305. URLString: URLString,
  306. multipartFormData: { multipartFormData in
  307. multipartFormData.appendBodyPart(data: french, name: "french")
  308. multipartFormData.appendBodyPart(data: japanese, name: "japanese")
  309. },
  310. encodingCompletion: { result in
  311. switch result {
  312. case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  313. streamingFromDisk = uploadStreamingFromDisk
  314. streamFileURL = uploadStreamFileURL
  315. upload.response { _, _, _, _ in
  316. expectation.fulfill()
  317. }
  318. case .Failure:
  319. expectation.fulfill()
  320. }
  321. }
  322. )
  323. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  324. // Then
  325. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  326. XCTAssertNil(streamFileURL, "stream file URL should be nil")
  327. if let streamingFromDisk = streamingFromDisk {
  328. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  329. }
  330. }
  331. func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
  332. // Given
  333. let URLString = "http://httpbin.org/post"
  334. let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  335. let expectation = expectationWithDescription("multipart form data upload should succeed")
  336. var formData: MultipartFormData?
  337. var request: NSURLRequest?
  338. var streamingFromDisk: Bool?
  339. // When
  340. Alamofire.upload(
  341. .POST,
  342. URLString: URLString,
  343. multipartFormData: { multipartFormData in
  344. multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
  345. formData = multipartFormData
  346. },
  347. encodingCompletion: { result in
  348. switch result {
  349. case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  350. streamingFromDisk = uploadStreamingFromDisk
  351. upload.response { responseRequest, _, _, _ in
  352. request = responseRequest
  353. expectation.fulfill()
  354. }
  355. case .Failure:
  356. expectation.fulfill()
  357. }
  358. }
  359. )
  360. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  361. // Then
  362. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  363. if let streamingFromDisk = streamingFromDisk {
  364. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  365. }
  366. if let
  367. request = request,
  368. multipartFormData = formData,
  369. contentType = request.valueForHTTPHeaderField("Content-Type")
  370. {
  371. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  372. } else {
  373. XCTFail("Content-Type header value should not be nil")
  374. }
  375. }
  376. func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
  377. // Given
  378. let URLString = "http://httpbin.org/post"
  379. let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  380. let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  381. let expectation = expectationWithDescription("multipart form data upload should succeed")
  382. var streamingFromDisk: Bool?
  383. var streamFileURL: NSURL?
  384. // When
  385. Alamofire.upload(
  386. .POST,
  387. URLString: URLString,
  388. multipartFormData: { multipartFormData in
  389. multipartFormData.appendBodyPart(data: french, name: "french")
  390. multipartFormData.appendBodyPart(data: japanese, name: "japanese")
  391. },
  392. encodingMemoryThreshold: 0,
  393. encodingCompletion: { result in
  394. switch result {
  395. case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  396. streamingFromDisk = uploadStreamingFromDisk
  397. streamFileURL = uploadStreamFileURL
  398. upload.response { _, _, _, _ in
  399. expectation.fulfill()
  400. }
  401. case .Failure:
  402. expectation.fulfill()
  403. }
  404. }
  405. )
  406. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  407. // Then
  408. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  409. XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
  410. if let
  411. streamingFromDisk = streamingFromDisk,
  412. streamFilePath = streamFileURL?.path
  413. {
  414. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  415. XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(streamFilePath), "stream file path should exist")
  416. }
  417. }
  418. func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
  419. // Given
  420. let URLString = "http://httpbin.org/post"
  421. let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  422. let expectation = expectationWithDescription("multipart form data upload should succeed")
  423. var formData: MultipartFormData?
  424. var request: NSURLRequest?
  425. var streamingFromDisk: Bool?
  426. // When
  427. Alamofire.upload(
  428. .POST,
  429. URLString: URLString,
  430. multipartFormData: { multipartFormData in
  431. multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
  432. formData = multipartFormData
  433. },
  434. encodingMemoryThreshold: 0,
  435. encodingCompletion: { result in
  436. switch result {
  437. case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  438. streamingFromDisk = uploadStreamingFromDisk
  439. upload.response { responseRequest, _, _, _ in
  440. request = responseRequest
  441. expectation.fulfill()
  442. }
  443. case .Failure:
  444. expectation.fulfill()
  445. }
  446. }
  447. )
  448. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  449. // Then
  450. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  451. if let streamingFromDisk = streamingFromDisk {
  452. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  453. }
  454. if let
  455. request = request,
  456. multipartFormData = formData,
  457. contentType = request.valueForHTTPHeaderField("Content-Type")
  458. {
  459. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  460. } else {
  461. XCTFail("Content-Type header value should not be nil")
  462. }
  463. }
  464. // MARK: Combined Test Execution
  465. private func executeMultipartFormDataUploadRequestWithProgress(#streamFromDisk: Bool) {
  466. // Given
  467. let URLString = "http://httpbin.org/post"
  468. let loremData1: NSData = {
  469. var loremValues: [String] = []
  470. for _ in 1...1_500 {
  471. loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
  472. }
  473. return join(" ", loremValues).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  474. }()
  475. let loremData2: NSData = {
  476. var loremValues: [String] = []
  477. for _ in 1...1_500 {
  478. loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
  479. }
  480. return join(" ", loremValues).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  481. }()
  482. let expectation = expectationWithDescription("multipart form data upload should succeed")
  483. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  484. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  485. var request: NSURLRequest?
  486. var response: NSHTTPURLResponse?
  487. var data: AnyObject?
  488. var error: NSError?
  489. // When
  490. Alamofire.upload(
  491. .POST,
  492. URLString: URLString,
  493. multipartFormData: { multipartFormData in
  494. multipartFormData.appendBodyPart(data: loremData1, name: "lorem1")
  495. multipartFormData.appendBodyPart(data: loremData2, name: "lorem2")
  496. },
  497. encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000,
  498. encodingCompletion: { result in
  499. switch result {
  500. case .Success(let upload, let streamingFromDisk, _):
  501. upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
  502. let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
  503. byteValues.append(bytes)
  504. let progress = (completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount)
  505. progressValues.append(progress)
  506. }
  507. upload.response { responseRequest, responseResponse, responseData, responseError in
  508. request = responseRequest
  509. response = responseResponse
  510. data = responseData
  511. error = responseError
  512. expectation.fulfill()
  513. }
  514. case .Failure:
  515. expectation.fulfill()
  516. }
  517. }
  518. )
  519. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  520. // Then
  521. XCTAssertNotNil(request, "request should not be nil")
  522. XCTAssertNotNil(response, "response should not be nil")
  523. XCTAssertNotNil(data, "data should not be nil")
  524. XCTAssertNil(error, "error should be nil")
  525. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  526. if byteValues.count == progressValues.count {
  527. for index in 0..<byteValues.count {
  528. let byteValue = byteValues[index]
  529. let progressValue = progressValues[index]
  530. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  531. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
  532. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
  533. }
  534. }
  535. if let
  536. lastByteValue = byteValues.last,
  537. lastProgressValue = progressValues.last
  538. {
  539. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  540. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  541. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  542. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  543. } else {
  544. XCTFail("last item in bytesValues and progressValues should not be nil")
  545. }
  546. }
  547. }