UploadTests.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 = url(forResource: "rainbow", withExtension: "jpg")
  32. // When
  33. let request = Alamofire.upload(imageURL, to: urlString)
  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 headers = ["Authorization": "123456"]
  44. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  45. // When
  46. let request = Alamofire.upload(imageURL, to: urlString, method: .post, headers: headers)
  47. // Then
  48. XCTAssertNotNil(request.request, "request should not be nil")
  49. XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
  50. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  51. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  52. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  53. XCTAssertNil(request.response, "response should be nil")
  54. }
  55. }
  56. // MARK: -
  57. class UploadDataInitializationTestCase: BaseTestCase {
  58. func testUploadClassMethodWithMethodURLAndData() {
  59. // Given
  60. let urlString = "https://httpbin.org/"
  61. // When
  62. let request = Alamofire.upload(Data(), to: urlString)
  63. // Then
  64. XCTAssertNotNil(request.request, "request should not be nil")
  65. XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
  66. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  67. XCTAssertNil(request.response, "response should be nil")
  68. }
  69. func testUploadClassMethodWithMethodURLHeadersAndData() {
  70. // Given
  71. let urlString = "https://httpbin.org/"
  72. let headers = ["Authorization": "123456"]
  73. // When
  74. let request = Alamofire.upload(Data(), to: urlString, headers: headers)
  75. // Then
  76. XCTAssertNotNil(request.request, "request should not be nil")
  77. XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
  78. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  79. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  80. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  81. XCTAssertNil(request.response, "response should be nil")
  82. }
  83. }
  84. // MARK: -
  85. class UploadStreamInitializationTestCase: BaseTestCase {
  86. func testUploadClassMethodWithMethodURLAndStream() {
  87. // Given
  88. let urlString = "https://httpbin.org/"
  89. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  90. let imageStream = InputStream(url: imageURL)!
  91. // When
  92. let request = Alamofire.upload(imageStream, to: urlString)
  93. // Then
  94. XCTAssertNotNil(request.request, "request should not be nil")
  95. XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
  96. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  97. XCTAssertNil(request.response, "response should be nil")
  98. }
  99. func testUploadClassMethodWithMethodURLHeadersAndStream() {
  100. // Given
  101. let urlString = "https://httpbin.org/"
  102. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  103. let headers = ["Authorization": "123456"]
  104. let imageStream = InputStream(url: imageURL)!
  105. // When
  106. let request = Alamofire.upload(imageStream, to: urlString, headers: headers)
  107. // Then
  108. XCTAssertNotNil(request.request, "request should not be nil")
  109. XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
  110. XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
  111. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  112. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  113. XCTAssertNil(request.response, "response should be nil")
  114. }
  115. }
  116. // MARK: -
  117. class UploadDataTestCase: BaseTestCase {
  118. func testUploadDataRequest() {
  119. // Given
  120. let urlString = "https://httpbin.org/post"
  121. let data = "Lorem ipsum dolor sit amet".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  122. let expectation = self.expectation(description: "Upload request should succeed: \(urlString)")
  123. var response: DefaultDataResponse?
  124. // When
  125. Alamofire.upload(data, to: urlString)
  126. .response { resp in
  127. response = resp
  128. expectation.fulfill()
  129. }
  130. waitForExpectations(timeout: timeout, handler: nil)
  131. // Then
  132. XCTAssertNotNil(response?.request)
  133. XCTAssertNotNil(response?.response)
  134. XCTAssertNil(response?.error)
  135. }
  136. func testUploadDataRequestWithProgress() {
  137. // Given
  138. let urlString = "https://httpbin.org/post"
  139. let data: Data = {
  140. var text = ""
  141. for _ in 1...3_000 {
  142. text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
  143. }
  144. return text.data(using: String.Encoding.utf8, allowLossyConversion: false)!
  145. }()
  146. let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)")
  147. var uploadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  148. var uploadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  149. var downloadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  150. var downloadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  151. var response: DefaultDataResponse?
  152. // When
  153. Alamofire.upload(data, to: urlString)
  154. .uploadProgress { progress in
  155. uploadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  156. }
  157. .uploadProgress { bytesSent, totalBytesSent, totalBytesExpectedToSend in
  158. let bytes = (bytes: bytesSent, totalBytes: totalBytesSent, totalBytesExpected: totalBytesExpectedToSend)
  159. uploadByteValues.append(bytes)
  160. }
  161. .downloadProgress { progress in
  162. downloadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  163. }
  164. .downloadProgress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  165. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  166. downloadByteValues.append(bytes)
  167. }
  168. .response { resp in
  169. response = resp
  170. expectation.fulfill()
  171. }
  172. waitForExpectations(timeout: timeout, handler: nil)
  173. // Then
  174. XCTAssertNotNil(response?.request)
  175. XCTAssertNotNil(response?.response)
  176. XCTAssertNotNil(response?.data)
  177. XCTAssertNil(response?.error)
  178. XCTAssertEqual(uploadByteValues.count, uploadProgressValues.count)
  179. XCTAssertEqual(downloadByteValues.count, downloadProgressValues.count)
  180. if uploadByteValues.count == uploadProgressValues.count {
  181. for (byteValue, progressValue) in zip(uploadByteValues, uploadProgressValues) {
  182. XCTAssertGreaterThan(byteValue.bytes, 0)
  183. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  184. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  185. }
  186. }
  187. if let lastUploadByteValue = uploadByteValues.last, let lastUploadProgressValue = uploadProgressValues.last {
  188. let byteValueFractionalCompletion = Double(lastUploadByteValue.totalBytes) / Double(lastUploadByteValue.totalBytesExpected)
  189. let progressValueFractionalCompletion = Double(lastUploadProgressValue.0) / Double(lastUploadProgressValue.1)
  190. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  191. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  192. } else {
  193. XCTFail("last item in uploadByteValues and uploadProgressValues should not be nil")
  194. }
  195. if downloadByteValues.count == downloadProgressValues.count {
  196. for (byteValue, progressValue) in zip(downloadByteValues, downloadProgressValues) {
  197. XCTAssertGreaterThan(byteValue.bytes, 0)
  198. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  199. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  200. }
  201. }
  202. if let lastDownloadByteValue = downloadByteValues.last, let lastDownloadProgressValue = downloadProgressValues.last {
  203. let byteValueFractionalCompletion = Double(lastDownloadByteValue.totalBytes) / Double(lastDownloadByteValue.totalBytesExpected)
  204. let progressValueFractionalCompletion = Double(lastDownloadProgressValue.0) / Double(lastDownloadProgressValue.1)
  205. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  206. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  207. } else {
  208. XCTFail("last item in downloadByteValues and downloadProgressValues 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 response: DefaultDataResponse?
  222. // When
  223. Alamofire.upload(
  224. multipartFormData: { multipartFormData in
  225. multipartFormData.append(uploadData, withName: "upload_data")
  226. formData = multipartFormData
  227. },
  228. to: urlString,
  229. method: .post,
  230. encodingCompletion: { result in
  231. switch result {
  232. case .success(let upload, _, _):
  233. upload.response { resp in
  234. response = resp
  235. expectation.fulfill()
  236. }
  237. case .failure:
  238. expectation.fulfill()
  239. }
  240. }
  241. )
  242. waitForExpectations(timeout: timeout, handler: nil)
  243. // Then
  244. XCTAssertNotNil(response?.request)
  245. XCTAssertNotNil(response?.response)
  246. XCTAssertNotNil(response?.data)
  247. XCTAssertNil(response?.error)
  248. if
  249. let request = response?.request,
  250. let multipartFormData = formData,
  251. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  252. {
  253. XCTAssertEqual(contentType, multipartFormData.contentType)
  254. } else {
  255. XCTFail("Content-Type header value should not be nil")
  256. }
  257. }
  258. func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
  259. // Given
  260. let urlString = "https://httpbin.org/post"
  261. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  262. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  263. let expectation = self.expectation(description: "multipart form data upload should succeed")
  264. var response: DefaultDataResponse?
  265. // When
  266. Alamofire.upload(
  267. multipartFormData: { multipartFormData in
  268. multipartFormData.append(frenchData, withName: "french")
  269. multipartFormData.append(japaneseData, withName: "japanese")
  270. },
  271. to: urlString,
  272. encodingCompletion: { result in
  273. switch result {
  274. case .success(let upload, _, _):
  275. upload.response { resp in
  276. response = resp
  277. expectation.fulfill()
  278. }
  279. case .failure:
  280. expectation.fulfill()
  281. }
  282. }
  283. )
  284. waitForExpectations(timeout: timeout, handler: nil)
  285. // Then
  286. XCTAssertNotNil(response?.request)
  287. XCTAssertNotNil(response?.response)
  288. XCTAssertNotNil(response?.data)
  289. XCTAssertNil(response?.error)
  290. }
  291. func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
  292. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
  293. }
  294. func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
  295. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
  296. }
  297. func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
  298. // Given
  299. let urlString = "https://httpbin.org/post"
  300. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  301. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  302. let expectation = self.expectation(description: "multipart form data upload should succeed")
  303. var streamingFromDisk: Bool?
  304. var streamFileURL: URL?
  305. // When
  306. Alamofire.upload(
  307. multipartFormData: { multipartFormData in
  308. multipartFormData.append(frenchData, withName: "french")
  309. multipartFormData.append(japaneseData, withName: "japanese")
  310. },
  311. to: urlString,
  312. encodingCompletion: { result in
  313. switch result {
  314. case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  315. streamingFromDisk = uploadStreamingFromDisk
  316. streamFileURL = uploadStreamFileURL
  317. upload.response { _ in
  318. expectation.fulfill()
  319. }
  320. case .failure:
  321. expectation.fulfill()
  322. }
  323. }
  324. )
  325. waitForExpectations(timeout: timeout, handler: nil)
  326. // Then
  327. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  328. XCTAssertNil(streamFileURL, "stream file URL should be nil")
  329. if let streamingFromDisk = streamingFromDisk {
  330. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  331. }
  332. }
  333. func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
  334. // Given
  335. let urlString = "https://httpbin.org/post"
  336. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  337. let expectation = self.expectation(description: "multipart form data upload should succeed")
  338. var formData: MultipartFormData?
  339. var request: URLRequest?
  340. var streamingFromDisk: Bool?
  341. // When
  342. Alamofire.upload(
  343. multipartFormData: { multipartFormData in
  344. multipartFormData.append(uploadData, withName: "upload_data")
  345. formData = multipartFormData
  346. },
  347. to: urlString,
  348. encodingCompletion: { result in
  349. switch result {
  350. case let .success(upload, uploadStreamingFromDisk, _):
  351. streamingFromDisk = uploadStreamingFromDisk
  352. upload.response { resp in
  353. request = resp.request
  354. expectation.fulfill()
  355. }
  356. case .failure:
  357. expectation.fulfill()
  358. }
  359. }
  360. )
  361. waitForExpectations(timeout: timeout, handler: nil)
  362. // Then
  363. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  364. if let streamingFromDisk = streamingFromDisk {
  365. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  366. }
  367. if
  368. let request = request,
  369. let multipartFormData = formData,
  370. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  371. {
  372. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  373. } else {
  374. XCTFail("Content-Type header value should not be nil")
  375. }
  376. }
  377. func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
  378. // Given
  379. let urlString = "https://httpbin.org/post"
  380. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  381. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  382. let expectation = self.expectation(description: "multipart form data upload should succeed")
  383. var streamingFromDisk: Bool?
  384. var streamFileURL: URL?
  385. // When
  386. Alamofire.upload(
  387. multipartFormData: { multipartFormData in
  388. multipartFormData.append(frenchData, withName: "french")
  389. multipartFormData.append(japaneseData, withName: "japanese")
  390. },
  391. usingThreshold: 0,
  392. to: urlString,
  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. waitForExpectations(timeout: timeout, 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 streamingFromDisk = streamingFromDisk, let streamFilePath = streamFileURL?.path {
  411. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  412. XCTAssertTrue(
  413. FileManager.default.fileExists(atPath: streamFilePath),
  414. "stream file path should exist"
  415. )
  416. }
  417. }
  418. func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
  419. // Given
  420. let urlString = "https://httpbin.org/post"
  421. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  422. let expectation = self.expectation(description: "multipart form data upload should succeed")
  423. var formData: MultipartFormData?
  424. var request: URLRequest?
  425. var streamingFromDisk: Bool?
  426. // When
  427. Alamofire.upload(
  428. multipartFormData: { multipartFormData in
  429. multipartFormData.append(uploadData, withName: "upload_data")
  430. formData = multipartFormData
  431. },
  432. usingThreshold: 0,
  433. to: urlString,
  434. encodingCompletion: { result in
  435. switch result {
  436. case let .success(upload, uploadStreamingFromDisk, _):
  437. streamingFromDisk = uploadStreamingFromDisk
  438. upload.response { resp in
  439. request = resp.request
  440. expectation.fulfill()
  441. }
  442. case .failure:
  443. expectation.fulfill()
  444. }
  445. }
  446. )
  447. waitForExpectations(timeout: timeout, handler: nil)
  448. // Then
  449. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  450. if let streamingFromDisk = streamingFromDisk {
  451. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  452. }
  453. if
  454. let request = request,
  455. let multipartFormData = formData,
  456. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  457. {
  458. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  459. } else {
  460. XCTFail("Content-Type header value should not be nil")
  461. }
  462. }
  463. // ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1
  464. // func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
  465. // // Given
  466. // let manager: SessionManager = {
  467. // let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
  468. // let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
  469. //
  470. // return SessionManager(configuration: configuration, serverTrustPolicyManager: nil)
  471. // }()
  472. //
  473. // let urlString = "https://httpbin.org/post"
  474. // let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  475. // let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  476. //
  477. // let expectation = self.expectation(description: "multipart form data upload should succeed")
  478. //
  479. // var request: URLRequest?
  480. // var response: HTTPURLResponse?
  481. // var data: Data?
  482. // var error: Error?
  483. // var streamingFromDisk: Bool?
  484. //
  485. // // When
  486. // manager.upload(
  487. // multipartFormData: { multipartFormData in
  488. // multipartFormData.append(french, withName: "french")
  489. // multipartFormData.append(japanese, withName: "japanese")
  490. // },
  491. // to: urlString,
  492. // withMethod: .post,
  493. // encodingCompletion: { result in
  494. // switch result {
  495. // case let .success(upload, uploadStreamingFromDisk, _):
  496. // streamingFromDisk = uploadStreamingFromDisk
  497. //
  498. // upload.response { responseRequest, responseResponse, responseData, responseError in
  499. // request = responseRequest
  500. // response = responseResponse
  501. // data = responseData
  502. // error = responseError
  503. //
  504. // expectation.fulfill()
  505. // }
  506. // case .failure:
  507. // expectation.fulfill()
  508. // }
  509. // }
  510. // )
  511. //
  512. // waitForExpectations(timeout: timeout, handler: nil)
  513. //
  514. // // Then
  515. // XCTAssertNotNil(request, "request should not be nil")
  516. // XCTAssertNotNil(response, "response should not be nil")
  517. // XCTAssertNotNil(data, "data should not be nil")
  518. // XCTAssertNil(error, "error should be nil")
  519. //
  520. // if let streamingFromDisk = streamingFromDisk {
  521. // XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  522. // } else {
  523. // XCTFail("streaming from disk should not be nil")
  524. // }
  525. // }
  526. // MARK: Combined Test Execution
  527. private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
  528. // Given
  529. let urlString = "https://httpbin.org/post"
  530. let loremData1: Data = {
  531. var loremValues: [String] = []
  532. for _ in 1...1_500 {
  533. loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
  534. }
  535. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  536. }()
  537. let loremData2: Data = {
  538. var loremValues: [String] = []
  539. for _ in 1...1_500 {
  540. loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
  541. }
  542. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  543. }()
  544. let expectation = self.expectation(description: "multipart form data upload should succeed")
  545. var uploadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  546. var uploadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  547. var downloadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  548. var downloadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  549. var response: DefaultDataResponse?
  550. // When
  551. Alamofire.upload(
  552. multipartFormData: { multipartFormData in
  553. multipartFormData.append(loremData1, withName: "lorem1")
  554. multipartFormData.append(loremData2, withName: "lorem2")
  555. },
  556. usingThreshold: streamFromDisk ? 0 : 100_000_000,
  557. to: urlString,
  558. encodingCompletion: { result in
  559. switch result {
  560. case .success(let upload, _, _):
  561. upload
  562. .uploadProgress { progress in
  563. uploadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  564. }
  565. .uploadProgress { bytesSent, totalBytesSent, totalBytesExpectedToSend in
  566. let bytes = (bytes: bytesSent, totalBytes: totalBytesSent, totalBytesExpected: totalBytesExpectedToSend)
  567. uploadByteValues.append(bytes)
  568. }
  569. .downloadProgress { progress in
  570. downloadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  571. }
  572. .downloadProgress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  573. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  574. downloadByteValues.append(bytes)
  575. }
  576. .response { resp in
  577. response = resp
  578. expectation.fulfill()
  579. }
  580. case .failure:
  581. expectation.fulfill()
  582. }
  583. }
  584. )
  585. waitForExpectations(timeout: timeout, handler: nil)
  586. // Then
  587. XCTAssertNotNil(response?.request)
  588. XCTAssertNotNil(response?.response)
  589. XCTAssertNotNil(response?.data)
  590. XCTAssertNil(response?.error)
  591. XCTAssertEqual(uploadByteValues.count, uploadProgressValues.count)
  592. XCTAssertEqual(downloadByteValues.count, downloadProgressValues.count)
  593. if uploadByteValues.count == uploadProgressValues.count {
  594. for (byteValue, progressValue) in zip(uploadByteValues, uploadProgressValues) {
  595. XCTAssertGreaterThan(byteValue.bytes, 0)
  596. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  597. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  598. }
  599. }
  600. if let lastUploadByteValue = uploadByteValues.last, let lastUploadProgressValue = uploadProgressValues.last {
  601. let byteValueFractionalCompletion = Double(lastUploadByteValue.totalBytes) / Double(lastUploadByteValue.totalBytesExpected)
  602. let progressValueFractionalCompletion = Double(lastUploadProgressValue.0) / Double(lastUploadProgressValue.1)
  603. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  604. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  605. } else {
  606. XCTFail("last item in uploadByteValues and uploadProgressValues should not be nil")
  607. }
  608. if downloadByteValues.count == downloadProgressValues.count {
  609. for (byteValue, progressValue) in zip(downloadByteValues, downloadProgressValues) {
  610. XCTAssertGreaterThan(byteValue.bytes, 0)
  611. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  612. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  613. }
  614. }
  615. if let lastDownloadByteValue = downloadByteValues.last, let lastDownloadProgressValue = downloadProgressValues.last {
  616. let byteValueFractionalCompletion = Double(lastDownloadByteValue.totalBytes) / Double(lastDownloadByteValue.totalBytesExpected)
  617. let progressValueFractionalCompletion = Double(lastDownloadProgressValue.0) / Double(lastDownloadProgressValue.1)
  618. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  619. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  620. } else {
  621. XCTFail("last item in downloadByteValues and downloadProgressValues should not be nil")
  622. }
  623. }
  624. }