UploadTests.swift 31 KB

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