2
0

UploadTests.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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, withMethod: .post)
  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, withMethod: .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, withMethod: .post)
  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, withMethod: .post, 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, withMethod: .post)
  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, withMethod: .post, 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 request: URLRequest?
  124. var response: HTTPURLResponse?
  125. var error: NSError?
  126. // When
  127. Alamofire.upload(data, to: urlString, withMethod: .post)
  128. .response { responseRequest, responseResponse, _, responseError in
  129. request = responseRequest
  130. response = responseResponse
  131. error = responseError
  132. expectation.fulfill()
  133. }
  134. waitForExpectations(timeout: timeout, handler: nil)
  135. // Then
  136. XCTAssertNotNil(request, "request should not be nil")
  137. XCTAssertNotNil(response, "response should not be nil")
  138. XCTAssertNil(error, "error should be nil")
  139. }
  140. func testUploadDataRequestWithProgress() {
  141. // Given
  142. let urlString = "https://httpbin.org/post"
  143. let data: Data = {
  144. var text = ""
  145. for _ in 1...3_000 {
  146. text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
  147. }
  148. return text.data(using: String.Encoding.utf8, allowLossyConversion: false)!
  149. }()
  150. let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)")
  151. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  152. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  153. var responseRequest: URLRequest?
  154. var responseResponse: HTTPURLResponse?
  155. var responseData: Data?
  156. var responseError: Error?
  157. // When
  158. let upload = Alamofire.upload(data, to: urlString, withMethod: .post)
  159. upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
  160. let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
  161. byteValues.append(bytes)
  162. let progress = (
  163. completedUnitCount: upload.progress.completedUnitCount,
  164. totalUnitCount: upload.progress.totalUnitCount
  165. )
  166. progressValues.append(progress)
  167. }
  168. upload.response { request, response, data, error in
  169. responseRequest = request
  170. responseResponse = response
  171. responseData = data
  172. responseError = error
  173. expectation.fulfill()
  174. }
  175. waitForExpectations(timeout: timeout, handler: nil)
  176. // Then
  177. XCTAssertNotNil(responseRequest, "response request should not be nil")
  178. XCTAssertNotNil(responseResponse, "response response should not be nil")
  179. XCTAssertNotNil(responseData, "response data should not be nil")
  180. XCTAssertNil(responseError, "response error should be nil")
  181. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  182. if byteValues.count == progressValues.count {
  183. for index in 0..<byteValues.count {
  184. let byteValue = byteValues[index]
  185. let progressValue = progressValues[index]
  186. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  187. XCTAssertEqual(
  188. byteValue.totalBytes,
  189. progressValue.completedUnitCount,
  190. "total bytes should be equal to completed unit count"
  191. )
  192. XCTAssertEqual(
  193. byteValue.totalBytesExpected,
  194. progressValue.totalUnitCount,
  195. "total bytes expected should be equal to total unit count"
  196. )
  197. }
  198. }
  199. if let lastByteValue = byteValues.last, let lastProgressValue = progressValues.last {
  200. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  201. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  202. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  203. XCTAssertEqual(
  204. progressValueFractionalCompletion,
  205. 1.0,
  206. "progress value fractional completion should equal 1.0"
  207. )
  208. } else {
  209. XCTFail("last item in bytesValues and progressValues should not be nil")
  210. }
  211. }
  212. }
  213. // MARK: -
  214. class UploadMultipartFormDataTestCase: BaseTestCase {
  215. // MARK: Tests
  216. func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
  217. // Given
  218. let urlString = "https://httpbin.org/post"
  219. let uploadData = "upload_data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  220. let expectation = self.expectation(description: "multipart form data upload should succeed")
  221. var formData: MultipartFormData?
  222. var request: URLRequest?
  223. var response: HTTPURLResponse?
  224. var data: Data?
  225. var error: NSError?
  226. // When
  227. Alamofire.upload(
  228. multipartFormData: { multipartFormData in
  229. multipartFormData.append(uploadData, withName: "upload_data")
  230. formData = multipartFormData
  231. },
  232. to: urlString,
  233. withMethod: .post,
  234. encodingCompletion: { result in
  235. switch result {
  236. case .success(let upload, _, _):
  237. upload.response { responseRequest, responseResponse, responseData, responseError in
  238. request = responseRequest
  239. response = responseResponse
  240. data = responseData
  241. error = responseError
  242. expectation.fulfill()
  243. }
  244. case .failure:
  245. expectation.fulfill()
  246. }
  247. }
  248. )
  249. waitForExpectations(timeout: timeout, handler: nil)
  250. // Then
  251. XCTAssertNotNil(request, "request should not be nil")
  252. XCTAssertNotNil(response, "response should not be nil")
  253. XCTAssertNotNil(data, "data should not be nil")
  254. XCTAssertNil(error, "error should be nil")
  255. if
  256. let request = request,
  257. let multipartFormData = formData,
  258. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  259. {
  260. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  261. } else {
  262. XCTFail("Content-Type header value should not be nil")
  263. }
  264. }
  265. func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
  266. // Given
  267. let urlString = "https://httpbin.org/post"
  268. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  269. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  270. let expectation = self.expectation(description: "multipart form data upload should succeed")
  271. var request: URLRequest?
  272. var response: HTTPURLResponse?
  273. var data: Data?
  274. var error: NSError?
  275. // When
  276. Alamofire.upload(
  277. multipartFormData: { multipartFormData in
  278. multipartFormData.append(frenchData, withName: "french")
  279. multipartFormData.append(japaneseData, withName: "japanese")
  280. },
  281. to: urlString,
  282. withMethod: .post,
  283. encodingCompletion: { result in
  284. switch result {
  285. case .success(let upload, _, _):
  286. upload.response { responseRequest, responseResponse, responseData, responseError in
  287. request = responseRequest
  288. response = responseResponse
  289. data = responseData
  290. error = responseError
  291. expectation.fulfill()
  292. }
  293. case .failure:
  294. expectation.fulfill()
  295. }
  296. }
  297. )
  298. waitForExpectations(timeout: timeout, handler: nil)
  299. // Then
  300. XCTAssertNotNil(request, "request should not be nil")
  301. XCTAssertNotNil(response, "response should not be nil")
  302. XCTAssertNotNil(data, "data should not be nil")
  303. XCTAssertNil(error, "error should be nil")
  304. }
  305. func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
  306. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
  307. }
  308. func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
  309. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
  310. }
  311. func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
  312. // Given
  313. let urlString = "https://httpbin.org/post"
  314. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  315. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  316. let expectation = self.expectation(description: "multipart form data upload should succeed")
  317. var streamingFromDisk: Bool?
  318. var streamFileURL: URL?
  319. // When
  320. Alamofire.upload(
  321. multipartFormData: { multipartFormData in
  322. multipartFormData.append(frenchData, withName: "french")
  323. multipartFormData.append(japaneseData, withName: "japanese")
  324. },
  325. to: urlString,
  326. withMethod: .post,
  327. encodingCompletion: { result in
  328. switch result {
  329. case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  330. streamingFromDisk = uploadStreamingFromDisk
  331. streamFileURL = uploadStreamFileURL
  332. upload.response { _, _, _, _ in
  333. expectation.fulfill()
  334. }
  335. case .failure:
  336. expectation.fulfill()
  337. }
  338. }
  339. )
  340. waitForExpectations(timeout: timeout, handler: nil)
  341. // Then
  342. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  343. XCTAssertNil(streamFileURL, "stream file URL should be nil")
  344. if let streamingFromDisk = streamingFromDisk {
  345. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  346. }
  347. }
  348. func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
  349. // Given
  350. let urlString = "https://httpbin.org/post"
  351. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  352. let expectation = self.expectation(description: "multipart form data upload should succeed")
  353. var formData: MultipartFormData?
  354. var request: URLRequest?
  355. var streamingFromDisk: Bool?
  356. // When
  357. Alamofire.upload(
  358. multipartFormData: { multipartFormData in
  359. multipartFormData.append(uploadData, withName: "upload_data")
  360. formData = multipartFormData
  361. },
  362. to: urlString,
  363. withMethod: .post,
  364. encodingCompletion: { result in
  365. switch result {
  366. case let .success(upload, uploadStreamingFromDisk, _):
  367. streamingFromDisk = uploadStreamingFromDisk
  368. upload.response { responseRequest, _, _, _ in
  369. request = responseRequest
  370. expectation.fulfill()
  371. }
  372. case .failure:
  373. expectation.fulfill()
  374. }
  375. }
  376. )
  377. waitForExpectations(timeout: timeout, handler: nil)
  378. // Then
  379. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  380. if let streamingFromDisk = streamingFromDisk {
  381. XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
  382. }
  383. if
  384. let request = request,
  385. let multipartFormData = formData,
  386. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  387. {
  388. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  389. } else {
  390. XCTFail("Content-Type header value should not be nil")
  391. }
  392. }
  393. func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
  394. // Given
  395. let urlString = "https://httpbin.org/post"
  396. let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  397. let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  398. let expectation = self.expectation(description: "multipart form data upload should succeed")
  399. var streamingFromDisk: Bool?
  400. var streamFileURL: URL?
  401. // When
  402. Alamofire.upload(
  403. multipartFormData: { multipartFormData in
  404. multipartFormData.append(frenchData, withName: "french")
  405. multipartFormData.append(japaneseData, withName: "japanese")
  406. },
  407. usingThreshold: 0,
  408. to: urlString,
  409. withMethod: .post,
  410. encodingCompletion: { result in
  411. switch result {
  412. case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
  413. streamingFromDisk = uploadStreamingFromDisk
  414. streamFileURL = uploadStreamFileURL
  415. upload.response { _, _, _, _ in
  416. expectation.fulfill()
  417. }
  418. case .failure:
  419. expectation.fulfill()
  420. }
  421. }
  422. )
  423. waitForExpectations(timeout: timeout, handler: nil)
  424. // Then
  425. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  426. XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
  427. if let streamingFromDisk = streamingFromDisk, let streamFilePath = streamFileURL?.path {
  428. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  429. XCTAssertTrue(
  430. FileManager.default.fileExists(atPath: streamFilePath),
  431. "stream file path should exist"
  432. )
  433. }
  434. }
  435. func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
  436. // Given
  437. let urlString = "https://httpbin.org/post"
  438. let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  439. let expectation = self.expectation(description: "multipart form data upload should succeed")
  440. var formData: MultipartFormData?
  441. var request: URLRequest?
  442. var streamingFromDisk: Bool?
  443. // When
  444. Alamofire.upload(
  445. multipartFormData: { multipartFormData in
  446. multipartFormData.append(uploadData, withName: "upload_data")
  447. formData = multipartFormData
  448. },
  449. usingThreshold: 0,
  450. to: urlString,
  451. withMethod: .post,
  452. encodingCompletion: { result in
  453. switch result {
  454. case let .success(upload, uploadStreamingFromDisk, _):
  455. streamingFromDisk = uploadStreamingFromDisk
  456. upload.response { responseRequest, _, _, _ in
  457. request = responseRequest
  458. expectation.fulfill()
  459. }
  460. case .failure:
  461. expectation.fulfill()
  462. }
  463. }
  464. )
  465. waitForExpectations(timeout: timeout, handler: nil)
  466. // Then
  467. XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
  468. if let streamingFromDisk = streamingFromDisk {
  469. XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  470. }
  471. if
  472. let request = request,
  473. let multipartFormData = formData,
  474. let contentType = request.value(forHTTPHeaderField: "Content-Type")
  475. {
  476. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  477. } else {
  478. XCTFail("Content-Type header value should not be nil")
  479. }
  480. }
  481. // ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1
  482. // func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
  483. // // Given
  484. // let manager: Manager = {
  485. // let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
  486. // let configuration = URLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier)
  487. //
  488. // return Manager(configuration: configuration, serverTrustPolicyManager: nil)
  489. // }()
  490. //
  491. // let urlString = "https://httpbin.org/post"
  492. // let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  493. // let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
  494. //
  495. // let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
  496. //
  497. // var request: URLRequest?
  498. // var response: HTTPURLResponse?
  499. // var data: Data?
  500. // var error: NSError?
  501. // var streamingFromDisk: Bool?
  502. //
  503. // // When
  504. // manager.upload(
  505. // .post,
  506. // urlString,
  507. // multipartFormData: { multipartFormData in
  508. // multipartFormData.appendBodyPart(data: french, name: "french")
  509. // multipartFormData.appendBodyPart(data: japanese, name: "japanese")
  510. // },
  511. // encodingCompletion: { result in
  512. // switch result {
  513. // case let .success(upload, uploadStreamingFromDisk, _):
  514. // streamingFromDisk = uploadStreamingFromDisk
  515. //
  516. // upload.response { responseRequest, responseResponse, responseData, responseError in
  517. // request = responseRequest
  518. // response = responseResponse
  519. // data = responseData
  520. // error = responseError
  521. //
  522. // expectation.fulfill()
  523. // }
  524. // case .failure:
  525. // expectation.fulfill()
  526. // }
  527. // }
  528. // )
  529. //
  530. // waitForExpectations(withTimeout: timeout, handler: nil)
  531. //
  532. // // Then
  533. // XCTAssertNotNil(request, "request should not be nil")
  534. // XCTAssertNotNil(response, "response should not be nil")
  535. // XCTAssertNotNil(data, "data should not be nil")
  536. // XCTAssertNil(error, "error should be nil")
  537. //
  538. // if let streamingFromDisk = streamingFromDisk {
  539. // XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
  540. // } else {
  541. // XCTFail("streaming from disk should not be nil")
  542. // }
  543. // }
  544. // MARK: Combined Test Execution
  545. private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
  546. // Given
  547. let urlString = "https://httpbin.org/post"
  548. let loremData1: Data = {
  549. var loremValues: [String] = []
  550. for _ in 1...1_500 {
  551. loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
  552. }
  553. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  554. }()
  555. let loremData2: Data = {
  556. var loremValues: [String] = []
  557. for _ in 1...1_500 {
  558. loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
  559. }
  560. return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
  561. }()
  562. let expectation = self.expectation(description: "multipart form data upload should succeed")
  563. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  564. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  565. var request: URLRequest?
  566. var response: HTTPURLResponse?
  567. var data: Data?
  568. var error: NSError?
  569. // When
  570. Alamofire.upload(
  571. multipartFormData: { multipartFormData in
  572. multipartFormData.append(loremData1, withName: "lorem1")
  573. multipartFormData.append(loremData2, withName: "lorem2")
  574. },
  575. usingThreshold: streamFromDisk ? 0 : 100_000_000,
  576. to: urlString,
  577. withMethod: .post,
  578. encodingCompletion: { result in
  579. switch result {
  580. case .success(let upload, _, _):
  581. upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
  582. let bytes = (
  583. bytes: bytesWritten,
  584. totalBytes: totalBytesWritten,
  585. totalBytesExpected: totalBytesExpectedToWrite
  586. )
  587. byteValues.append(bytes)
  588. let progress = (
  589. completedUnitCount: upload.progress.completedUnitCount,
  590. totalUnitCount: upload.progress.totalUnitCount
  591. )
  592. progressValues.append(progress)
  593. }
  594. upload.response { responseRequest, responseResponse, responseData, responseError in
  595. request = responseRequest
  596. response = responseResponse
  597. data = responseData
  598. error = responseError
  599. expectation.fulfill()
  600. }
  601. case .failure:
  602. expectation.fulfill()
  603. }
  604. }
  605. )
  606. waitForExpectations(timeout: timeout, handler: nil)
  607. // Then
  608. XCTAssertNotNil(request, "request should not be nil")
  609. XCTAssertNotNil(response, "response should not be nil")
  610. XCTAssertNotNil(data, "data should not be nil")
  611. XCTAssertNil(error, "error should be nil")
  612. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  613. if byteValues.count == progressValues.count {
  614. for index in 0..<byteValues.count {
  615. let byteValue = byteValues[index]
  616. let progressValue = progressValues[index]
  617. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  618. XCTAssertEqual(
  619. byteValue.totalBytes,
  620. progressValue.completedUnitCount,
  621. "total bytes should be equal to completed unit count"
  622. )
  623. XCTAssertEqual(
  624. byteValue.totalBytesExpected,
  625. progressValue.totalUnitCount,
  626. "total bytes expected should be equal to total unit count"
  627. )
  628. }
  629. }
  630. if let lastByteValue = byteValues.last,
  631. let lastProgressValue = progressValues.last
  632. {
  633. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  634. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  635. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  636. XCTAssertEqual(
  637. progressValueFractionalCompletion,
  638. 1.0,
  639. "progress value fractional completion should equal 1.0"
  640. )
  641. } else {
  642. XCTFail("last item in bytesValues and progressValues should not be nil")
  643. }
  644. }
  645. }