UploadTests.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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?.url?.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?.url?.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?.url?.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?.url?.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?.url?.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?.url?.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. encodingCompletion: { result in
  230. switch result {
  231. case .success(let upload, _, _):
  232. upload.response { resp in
  233. response = resp
  234. expectation.fulfill()
  235. }
  236. case .failure:
  237. expectation.fulfill()
  238. }
  239. }
  240. )
  241. waitForExpectations(timeout: timeout, handler: nil)
  242. // Then
  243. XCTAssertNotNil(response?.request)
  244. XCTAssertNotNil(response?.response)
  245. XCTAssertNotNil(response?.data)
  246. XCTAssertNil(response?.error)
  247. if
  248. let request = response?.request,
  249. let multipartFormData = formData,
  250. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  251. {
  252. XCTAssertEqual(contentType, multipartFormData.contentType)
  253. } else {
  254. XCTFail("Content-Type header value should not be nil")
  255. }
  256. }
  257. func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
  258. // Given
  259. let urlString = "https://httpbin.org/post"
  260. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  261. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  262. let expectation = self.expectation(description: "multipart form data upload should succeed")
  263. var response: DefaultDataResponse?
  264. // When
  265. Alamofire.upload(
  266. multipartFormData: { multipartFormData in
  267. multipartFormData.append(frenchData, withName: "french")
  268. multipartFormData.append(japaneseData, withName: "japanese")
  269. },
  270. to: urlString,
  271. encodingCompletion: { result in
  272. switch result {
  273. case .success(let upload, _, _):
  274. upload.response { resp in
  275. response = resp
  276. expectation.fulfill()
  277. }
  278. case .failure:
  279. expectation.fulfill()
  280. }
  281. }
  282. )
  283. waitForExpectations(timeout: timeout, handler: nil)
  284. // Then
  285. XCTAssertNotNil(response?.request)
  286. XCTAssertNotNil(response?.response)
  287. XCTAssertNotNil(response?.data)
  288. XCTAssertNil(response?.error)
  289. }
  290. func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
  291. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
  292. }
  293. func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
  294. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
  295. }
  296. func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
  297. // Given
  298. let urlString = "https://httpbin.org/post"
  299. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  300. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  301. let expectation = self.expectation(description: "multipart form data upload should succeed")
  302. var streamingFromDisk: Bool?
  303. var streamFileURL: URL?
  304. // When
  305. Alamofire.upload(
  306. multipartFormData: { multipartFormData in
  307. multipartFormData.append(frenchData, withName: "french")
  308. multipartFormData.append(japaneseData, withName: "japanese")
  309. },
  310. to: urlString,
  311. encodingCompletion: { result in
  312. switch result {
  313. case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  314. streamingFromDisk = uploadStreamingFromDisk
  315. streamFileURL = uploadStreamFileURL
  316. upload.response { _ in
  317. expectation.fulfill()
  318. }
  319. case .failure:
  320. expectation.fulfill()
  321. }
  322. }
  323. )
  324. waitForExpectations(timeout: timeout, handler: nil)
  325. // Then
  326. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  327. XCTAssertNil(streamFileURL, "stream file URL should be nil")
  328. if let streamingFromDisk = streamingFromDisk {
  329. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  330. }
  331. }
  332. func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
  333. // Given
  334. let urlString = "https://httpbin.org/post"
  335. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  336. let expectation = self.expectation(description: "multipart form data upload should succeed")
  337. var formData: MultipartFormData?
  338. var request: URLRequest?
  339. var streamingFromDisk: Bool?
  340. // When
  341. Alamofire.upload(
  342. multipartFormData: { multipartFormData in
  343. multipartFormData.append(uploadData, withName: "upload_data")
  344. formData = multipartFormData
  345. },
  346. to: urlString,
  347. encodingCompletion: { result in
  348. switch result {
  349. case let .success(upload, uploadStreamingFromDisk, _):
  350. streamingFromDisk = uploadStreamingFromDisk
  351. upload.response { resp in
  352. request = resp.request
  353. expectation.fulfill()
  354. }
  355. case .failure:
  356. expectation.fulfill()
  357. }
  358. }
  359. )
  360. waitForExpectations(timeout: timeout, 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
  367. let request = request,
  368. let multipartFormData = formData,
  369. let contentType = request.value(forHTTPHeaderField: "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 = "https://httpbin.org/post"
  379. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  380. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  381. let expectation = self.expectation(description: "multipart form data upload should succeed")
  382. var streamingFromDisk: Bool?
  383. var streamFileURL: URL?
  384. // When
  385. Alamofire.upload(
  386. multipartFormData: { multipartFormData in
  387. multipartFormData.append(frenchData, withName: "french")
  388. multipartFormData.append(japaneseData, withName: "japanese")
  389. },
  390. usingThreshold: 0,
  391. to: urlString,
  392. encodingCompletion: { result in
  393. switch result {
  394. case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  395. streamingFromDisk = uploadStreamingFromDisk
  396. streamFileURL = uploadStreamFileURL
  397. upload.response { _ in
  398. expectation.fulfill()
  399. }
  400. case .failure:
  401. expectation.fulfill()
  402. }
  403. }
  404. )
  405. waitForExpectations(timeout: timeout, handler: nil)
  406. // Then
  407. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  408. XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
  409. if let streamingFromDisk = streamingFromDisk, let streamFilePath = streamFileURL?.path {
  410. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  411. XCTAssertTrue(
  412. FileManager.default.fileExists(atPath: streamFilePath),
  413. "stream file path should exist"
  414. )
  415. }
  416. }
  417. func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
  418. // Given
  419. let urlString = "https://httpbin.org/post"
  420. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  421. let expectation = self.expectation(description: "multipart form data upload should succeed")
  422. var formData: MultipartFormData?
  423. var request: URLRequest?
  424. var streamingFromDisk: Bool?
  425. // When
  426. Alamofire.upload(
  427. multipartFormData: { multipartFormData in
  428. multipartFormData.append(uploadData, withName: "upload_data")
  429. formData = multipartFormData
  430. },
  431. usingThreshold: 0,
  432. to: urlString,
  433. encodingCompletion: { result in
  434. switch result {
  435. case let .success(upload, uploadStreamingFromDisk, _):
  436. streamingFromDisk = uploadStreamingFromDisk
  437. upload.response { resp in
  438. request = resp.request
  439. expectation.fulfill()
  440. }
  441. case .failure:
  442. expectation.fulfill()
  443. }
  444. }
  445. )
  446. waitForExpectations(timeout: timeout, handler: nil)
  447. // Then
  448. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  449. if let streamingFromDisk = streamingFromDisk {
  450. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  451. }
  452. if
  453. let request = request,
  454. let multipartFormData = formData,
  455. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  456. {
  457. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  458. } else {
  459. XCTFail("Content-Type header value should not be nil")
  460. }
  461. }
  462. // ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1
  463. // func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
  464. // // Given
  465. // let manager: SessionManager = {
  466. // let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
  467. // let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
  468. //
  469. // return SessionManager(configuration: configuration, serverTrustPolicyManager: nil)
  470. // }()
  471. //
  472. // let urlString = "https://httpbin.org/post"
  473. // let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  474. // let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  475. //
  476. // let expectation = self.expectation(description: "multipart form data upload should succeed")
  477. //
  478. // var request: URLRequest?
  479. // var response: HTTPURLResponse?
  480. // var data: Data?
  481. // var error: Error?
  482. // var streamingFromDisk: Bool?
  483. //
  484. // // When
  485. // manager.upload(
  486. // multipartFormData: { multipartFormData in
  487. // multipartFormData.append(french, withName: "french")
  488. // multipartFormData.append(japanese, withName: "japanese")
  489. // },
  490. // to: urlString,
  491. // withMethod: .post,
  492. // encodingCompletion: { result in
  493. // switch result {
  494. // case let .success(upload, uploadStreamingFromDisk, _):
  495. // streamingFromDisk = uploadStreamingFromDisk
  496. //
  497. // upload.response { responseRequest, responseResponse, responseData, responseError in
  498. // request = responseRequest
  499. // response = responseResponse
  500. // data = responseData
  501. // error = responseError
  502. //
  503. // expectation.fulfill()
  504. // }
  505. // case .failure:
  506. // expectation.fulfill()
  507. // }
  508. // }
  509. // )
  510. //
  511. // waitForExpectations(timeout: timeout, handler: nil)
  512. //
  513. // // Then
  514. // XCTAssertNotNil(request, "request should not be nil")
  515. // XCTAssertNotNil(response, "response should not be nil")
  516. // XCTAssertNotNil(data, "data should not be nil")
  517. // XCTAssertNil(error, "error should be nil")
  518. //
  519. // if let streamingFromDisk = streamingFromDisk {
  520. // XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  521. // } else {
  522. // XCTFail("streaming from disk should not be nil")
  523. // }
  524. // }
  525. // MARK: Combined Test Execution
  526. private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
  527. // Given
  528. let urlString = "https://httpbin.org/post"
  529. let loremData1: Data = {
  530. var loremValues: [String] = []
  531. for _ in 1...1_500 {
  532. loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
  533. }
  534. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  535. }()
  536. let loremData2: Data = {
  537. var loremValues: [String] = []
  538. for _ in 1...1_500 {
  539. loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
  540. }
  541. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  542. }()
  543. let expectation = self.expectation(description: "multipart form data upload should succeed")
  544. var uploadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  545. var uploadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  546. var downloadByteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  547. var downloadProgressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  548. var response: DefaultDataResponse?
  549. // When
  550. Alamofire.upload(
  551. multipartFormData: { multipartFormData in
  552. multipartFormData.append(loremData1, withName: "lorem1")
  553. multipartFormData.append(loremData2, withName: "lorem2")
  554. },
  555. usingThreshold: streamFromDisk ? 0 : 100_000_000,
  556. to: urlString,
  557. encodingCompletion: { result in
  558. switch result {
  559. case .success(let upload, _, _):
  560. upload
  561. .uploadProgress { progress in
  562. uploadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  563. }
  564. .uploadProgress { bytesSent, totalBytesSent, totalBytesExpectedToSend in
  565. let bytes = (bytes: bytesSent, totalBytes: totalBytesSent, totalBytesExpected: totalBytesExpectedToSend)
  566. uploadByteValues.append(bytes)
  567. }
  568. .downloadProgress { progress in
  569. downloadProgressValues.append((progress.completedUnitCount, progress.totalUnitCount))
  570. }
  571. .downloadProgress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  572. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  573. downloadByteValues.append(bytes)
  574. }
  575. .response { resp in
  576. response = resp
  577. expectation.fulfill()
  578. }
  579. case .failure:
  580. expectation.fulfill()
  581. }
  582. }
  583. )
  584. waitForExpectations(timeout: timeout, handler: nil)
  585. // Then
  586. XCTAssertNotNil(response?.request)
  587. XCTAssertNotNil(response?.response)
  588. XCTAssertNotNil(response?.data)
  589. XCTAssertNil(response?.error)
  590. XCTAssertEqual(uploadByteValues.count, uploadProgressValues.count)
  591. XCTAssertEqual(downloadByteValues.count, downloadProgressValues.count)
  592. if uploadByteValues.count == uploadProgressValues.count {
  593. for (byteValue, progressValue) in zip(uploadByteValues, uploadProgressValues) {
  594. XCTAssertGreaterThan(byteValue.bytes, 0)
  595. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  596. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  597. }
  598. }
  599. if let lastUploadByteValue = uploadByteValues.last, let lastUploadProgressValue = uploadProgressValues.last {
  600. let byteValueFractionalCompletion = Double(lastUploadByteValue.totalBytes) / Double(lastUploadByteValue.totalBytesExpected)
  601. let progressValueFractionalCompletion = Double(lastUploadProgressValue.0) / Double(lastUploadProgressValue.1)
  602. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  603. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  604. } else {
  605. XCTFail("last item in uploadByteValues and uploadProgressValues should not be nil")
  606. }
  607. if downloadByteValues.count == downloadProgressValues.count {
  608. for (byteValue, progressValue) in zip(downloadByteValues, downloadProgressValues) {
  609. XCTAssertGreaterThan(byteValue.bytes, 0)
  610. XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount)
  611. XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount)
  612. }
  613. }
  614. if let lastDownloadByteValue = downloadByteValues.last, let lastDownloadProgressValue = downloadProgressValues.last {
  615. let byteValueFractionalCompletion = Double(lastDownloadByteValue.totalBytes) / Double(lastDownloadByteValue.totalBytesExpected)
  616. let progressValueFractionalCompletion = Double(lastDownloadProgressValue.0) / Double(lastDownloadProgressValue.1)
  617. XCTAssertEqual(byteValueFractionalCompletion, 1.0)
  618. XCTAssertEqual(progressValueFractionalCompletion, 1.0)
  619. } else {
  620. XCTFail("last item in downloadByteValues and downloadProgressValues should not be nil")
  621. }
  622. }
  623. }