UploadTests.swift 30 KB

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