UploadTests.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. //
  2. // UploadTests.swift
  3. //
  4. // Copyright (c) 2014-2018 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/post"
  31. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  32. let expectation = self.expectation(description: "upload should complete")
  33. // When
  34. let request = AF.upload(imageURL, to: urlString).response { _ in
  35. expectation.fulfill()
  36. }
  37. waitForExpectations(timeout: timeout, handler: nil)
  38. // Then
  39. XCTAssertNotNil(request.request, "request should not be nil")
  40. XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
  41. XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
  42. XCTAssertNotNil(request.response, "response should not be nil")
  43. }
  44. func testUploadClassMethodWithMethodURLHeadersAndFile() {
  45. // Given
  46. let urlString = "https://httpbin.org/post"
  47. let headers: HTTPHeaders = ["Authorization": "123456"]
  48. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  49. let expectation = self.expectation(description: "upload should complete")
  50. // When
  51. let request = AF.upload(imageURL, to: urlString, method: .post, headers: headers).response { _ in
  52. expectation.fulfill()
  53. }
  54. waitForExpectations(timeout: timeout, handler: nil)
  55. // Then
  56. XCTAssertNotNil(request.request, "request should not be nil")
  57. XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
  58. XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
  59. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  60. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  61. XCTAssertNotNil(request.response, "response should not be nil")
  62. }
  63. }
  64. // MARK: -
  65. class UploadDataInitializationTestCase: BaseTestCase {
  66. func testUploadClassMethodWithMethodURLAndData() {
  67. // Given
  68. let urlString = "https://httpbin.org/post"
  69. let expectation = self.expectation(description: "upload should complete")
  70. // When
  71. let request = AF.upload(Data(), to: urlString).response { _ in
  72. expectation.fulfill()
  73. }
  74. waitForExpectations(timeout: timeout, handler: nil)
  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?.absoluteString, urlString, "request URL string should be equal")
  79. XCTAssertNotNil(request.response, "response should not be nil")
  80. }
  81. func testUploadClassMethodWithMethodURLHeadersAndData() {
  82. // Given
  83. let urlString = "https://httpbin.org/post"
  84. let headers: HTTPHeaders = ["Authorization": "123456"]
  85. let expectation = self.expectation(description: "upload should complete")
  86. // When
  87. let request = AF.upload(Data(), to: urlString, headers: headers).response { _ in
  88. expectation.fulfill()
  89. }
  90. waitForExpectations(timeout: timeout, handler: nil)
  91. // Then
  92. XCTAssertNotNil(request.request, "request should not be nil")
  93. XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
  94. XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
  95. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  96. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  97. XCTAssertNotNil(request.response, "response should not be nil")
  98. }
  99. }
  100. // MARK: -
  101. class UploadStreamInitializationTestCase: BaseTestCase {
  102. func testUploadClassMethodWithMethodURLAndStream() {
  103. // Given
  104. let urlString = "https://httpbin.org/post"
  105. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  106. let imageStream = InputStream(url: imageURL)!
  107. let expectation = self.expectation(description: "upload should complete")
  108. // When
  109. let request = AF.upload(imageStream, to: urlString).response { _ in
  110. expectation.fulfill()
  111. }
  112. waitForExpectations(timeout: timeout, handler: nil)
  113. // Then
  114. XCTAssertNotNil(request.request, "request should not be nil")
  115. XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
  116. XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
  117. XCTAssertNotNil(request.response, "response should not be nil")
  118. }
  119. func testUploadClassMethodWithMethodURLHeadersAndStream() {
  120. // Given
  121. let urlString = "https://httpbin.org/post"
  122. let imageURL = url(forResource: "rainbow", withExtension: "jpg")
  123. let headers: HTTPHeaders = ["Authorization": "123456"]
  124. let imageStream = InputStream(url: imageURL)!
  125. let expectation = self.expectation(description: "upload should complete")
  126. // When
  127. let request = AF.upload(imageStream, to: urlString, headers: headers).response { _ in
  128. expectation.fulfill()
  129. }
  130. waitForExpectations(timeout: timeout, handler: nil)
  131. // Then
  132. XCTAssertNotNil(request.request, "request should not be nil")
  133. XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
  134. XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
  135. let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
  136. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  137. XCTAssertNotNil(request.response, "response should not be nil, tasks: \(request.tasks)")
  138. }
  139. }
  140. // MARK: -
  141. class UploadDataTestCase: BaseTestCase {
  142. func testUploadDataRequest() {
  143. // Given
  144. let urlString = "https://httpbin.org/post"
  145. let data = Data("Lorem ipsum dolor sit amet".utf8)
  146. let expectation = self.expectation(description: "Upload request should succeed: \(urlString)")
  147. var response: DataResponse<Data?, AFError>?
  148. // When
  149. AF.upload(data, to: urlString)
  150. .response { resp in
  151. response = resp
  152. expectation.fulfill()
  153. }
  154. waitForExpectations(timeout: timeout, handler: nil)
  155. // Then
  156. XCTAssertNotNil(response?.request)
  157. XCTAssertNotNil(response?.response)
  158. XCTAssertNil(response?.error)
  159. }
  160. func testUploadDataRequestWithProgress() {
  161. // Given
  162. let urlString = "https://httpbin.org/post"
  163. let string = String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", count: 300)
  164. let data = Data(string.utf8)
  165. let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)")
  166. var uploadProgressValues: [Double] = []
  167. var downloadProgressValues: [Double] = []
  168. var response: DataResponse<Data?, AFError>?
  169. // When
  170. AF.upload(data, to: urlString)
  171. .uploadProgress { progress in
  172. uploadProgressValues.append(progress.fractionCompleted)
  173. }
  174. .downloadProgress { progress in
  175. downloadProgressValues.append(progress.fractionCompleted)
  176. }
  177. .response { resp in
  178. response = resp
  179. expectation.fulfill()
  180. }
  181. waitForExpectations(timeout: timeout, handler: nil)
  182. // Then
  183. XCTAssertNotNil(response?.request)
  184. XCTAssertNotNil(response?.response)
  185. XCTAssertNotNil(response?.data)
  186. XCTAssertNil(response?.error)
  187. var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
  188. for progress in uploadProgressValues {
  189. XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
  190. previousUploadProgress = progress
  191. }
  192. if let lastProgressValue = uploadProgressValues.last {
  193. XCTAssertEqual(lastProgressValue, 1.0)
  194. } else {
  195. XCTFail("last item in uploadProgressValues should not be nil")
  196. }
  197. var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
  198. for progress in downloadProgressValues {
  199. XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
  200. previousDownloadProgress = progress
  201. }
  202. if let lastProgressValue = downloadProgressValues.last {
  203. XCTAssertEqual(lastProgressValue, 1.0)
  204. } else {
  205. XCTFail("last item in downloadProgressValues should not be nil")
  206. }
  207. }
  208. }
  209. // MARK: -
  210. class UploadMultipartFormDataTestCase: BaseTestCase {
  211. // MARK: Tests
  212. func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
  213. // Given
  214. let urlString = "https://httpbin.org/post"
  215. let uploadData = Data("upload_data".utf8)
  216. let expectation = self.expectation(description: "multipart form data upload should succeed")
  217. var formData: MultipartFormData?
  218. var response: DataResponse<Data?, AFError>?
  219. // When
  220. AF.upload(multipartFormData: { multipartFormData in
  221. multipartFormData.append(uploadData, withName: "upload_data")
  222. formData = multipartFormData
  223. },
  224. to: urlString)
  225. .response { resp in
  226. response = resp
  227. expectation.fulfill()
  228. }
  229. waitForExpectations(timeout: timeout, handler: nil)
  230. // Then
  231. XCTAssertNotNil(response?.request)
  232. XCTAssertNotNil(response?.response)
  233. XCTAssertNotNil(response?.data)
  234. XCTAssertNil(response?.error)
  235. if
  236. let request = response?.request,
  237. let multipartFormData = formData,
  238. let contentType = request.value(forHTTPHeaderField: "Content-Type") {
  239. XCTAssertEqual(contentType, multipartFormData.contentType)
  240. } else {
  241. XCTFail("Content-Type header value should not be nil")
  242. }
  243. }
  244. func testThatCustomBoundaryCanBeSetWhenUploadingMultipartFormData() throws {
  245. // Given
  246. let urlRequest = try URLRequest(url: "https://httpbin.org/post", method: .post)
  247. let uploadData = Data("upload_data".utf8)
  248. let formData = MultipartFormData(fileManager: .default, boundary: "custom-test-boundary")
  249. formData.append(uploadData, withName: "upload_data")
  250. let expectation = self.expectation(description: "multipart form data upload should succeed")
  251. var response: DataResponse<Data?, AFError>?
  252. // When
  253. AF.upload(multipartFormData: formData, with: urlRequest).response { resp in
  254. response = resp
  255. expectation.fulfill()
  256. }
  257. waitForExpectations(timeout: timeout, handler: nil)
  258. // Then
  259. XCTAssertNotNil(response?.request)
  260. XCTAssertNotNil(response?.response)
  261. XCTAssertNotNil(response?.data)
  262. XCTAssertNil(response?.error)
  263. if let request = response?.request, let contentType = request.value(forHTTPHeaderField: "Content-Type") {
  264. XCTAssertEqual(contentType, formData.contentType)
  265. XCTAssertTrue(contentType.contains("boundary=custom-test-boundary"))
  266. } else {
  267. XCTFail("Content-Type header value should not be nil")
  268. }
  269. }
  270. func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
  271. // Given
  272. let urlString = "https://httpbin.org/post"
  273. let frenchData = Data("français".utf8)
  274. let japaneseData = Data("日本語".utf8)
  275. let expectation = self.expectation(description: "multipart form data upload should succeed")
  276. var response: DataResponse<Data?, AFError>?
  277. // When
  278. AF.upload(multipartFormData: { multipartFormData in
  279. multipartFormData.append(frenchData, withName: "french")
  280. multipartFormData.append(japaneseData, withName: "japanese")
  281. },
  282. to: urlString)
  283. .response { resp in
  284. response = resp
  285. expectation.fulfill()
  286. }
  287. waitForExpectations(timeout: timeout, handler: nil)
  288. // Then
  289. XCTAssertNotNil(response?.request)
  290. XCTAssertNotNil(response?.response)
  291. XCTAssertNotNil(response?.data)
  292. XCTAssertNil(response?.error)
  293. }
  294. func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
  295. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
  296. }
  297. func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
  298. executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
  299. }
  300. func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
  301. // Given
  302. let urlString = "https://httpbin.org/post"
  303. let frenchData = Data("français".utf8)
  304. let japaneseData = Data("日本語".utf8)
  305. let expectation = self.expectation(description: "multipart form data upload should succeed")
  306. var response: DataResponse<Data?, AFError>?
  307. // When
  308. let request = AF.upload(multipartFormData: { multipartFormData in
  309. multipartFormData.append(frenchData, withName: "french")
  310. multipartFormData.append(japaneseData, withName: "japanese")
  311. },
  312. to: urlString)
  313. .response { resp in
  314. response = resp
  315. expectation.fulfill()
  316. }
  317. waitForExpectations(timeout: timeout, handler: nil)
  318. // Then
  319. guard let uploadable = request.uploadable, case .data = uploadable else {
  320. XCTFail("Uploadable is not .data")
  321. return
  322. }
  323. XCTAssertTrue(response?.result.isSuccess == true)
  324. }
  325. func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
  326. // Given
  327. let urlString = "https://httpbin.org/post"
  328. let uploadData = Data("upload_data".utf8)
  329. let expectation = self.expectation(description: "multipart form data upload should succeed")
  330. var formData: MultipartFormData?
  331. var response: DataResponse<Data?, AFError>?
  332. // When
  333. let request = AF.upload(multipartFormData: { multipartFormData in
  334. multipartFormData.append(uploadData, withName: "upload_data")
  335. formData = multipartFormData
  336. },
  337. to: urlString)
  338. .response { resp in
  339. response = resp
  340. expectation.fulfill()
  341. }
  342. waitForExpectations(timeout: timeout, handler: nil)
  343. // Then
  344. guard let uploadable = request.uploadable, case .data = uploadable else {
  345. XCTFail("Uploadable is not .data")
  346. return
  347. }
  348. if
  349. let request = response?.request,
  350. let multipartFormData = formData,
  351. let contentType = request.value(forHTTPHeaderField: "Content-Type") {
  352. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  353. } else {
  354. XCTFail("Content-Type header value should not be nil")
  355. }
  356. }
  357. func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
  358. // Given
  359. let urlString = "https://httpbin.org/post"
  360. let frenchData = Data("français".utf8)
  361. let japaneseData = Data("日本語".utf8)
  362. let expectation = self.expectation(description: "multipart form data upload should succeed")
  363. var response: DataResponse<Data?, AFError>?
  364. // When
  365. let request = AF.upload(multipartFormData: { multipartFormData in
  366. multipartFormData.append(frenchData, withName: "french")
  367. multipartFormData.append(japaneseData, withName: "japanese")
  368. },
  369. to: urlString,
  370. usingThreshold: 0).response { resp in
  371. response = resp
  372. expectation.fulfill()
  373. }
  374. waitForExpectations(timeout: timeout, handler: nil)
  375. // Then
  376. guard let uploadable = request.uploadable, case let .file(url, _) = uploadable else {
  377. XCTFail("Uploadable is not .file")
  378. return
  379. }
  380. XCTAssertTrue(response?.result.isSuccess == true)
  381. XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
  382. }
  383. func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
  384. // Given
  385. let urlString = "https://httpbin.org/post"
  386. let uploadData = Data("upload_data".utf8)
  387. let expectation = self.expectation(description: "multipart form data upload should succeed")
  388. var response: DataResponse<Data?, AFError>?
  389. var formData: MultipartFormData?
  390. // When
  391. let request = AF.upload(multipartFormData: { multipartFormData in
  392. multipartFormData.append(uploadData, withName: "upload_data")
  393. formData = multipartFormData
  394. },
  395. to: urlString,
  396. usingThreshold: 0).response { resp in
  397. response = resp
  398. expectation.fulfill()
  399. }
  400. waitForExpectations(timeout: timeout, handler: nil)
  401. // Then
  402. guard let uploadable = request.uploadable, case .file = uploadable else {
  403. XCTFail("Uploadable is not .file")
  404. return
  405. }
  406. XCTAssertTrue(response?.result.isSuccess == true)
  407. if
  408. let request = response?.request,
  409. let multipartFormData = formData,
  410. let contentType = request.value(forHTTPHeaderField: "Content-Type") {
  411. XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
  412. } else {
  413. XCTFail("Content-Type header value should not be nil")
  414. }
  415. }
  416. #if os(macOS)
  417. func disabled_testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
  418. // Given
  419. let manager: Session = {
  420. let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
  421. let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
  422. return Session(configuration: configuration)
  423. }()
  424. let urlString = "https://httpbin.org/post"
  425. let french = Data("français".utf8)
  426. let japanese = Data("日本語".utf8)
  427. let expectation = self.expectation(description: "multipart form data upload should succeed")
  428. var request: URLRequest?
  429. var response: HTTPURLResponse?
  430. var data: Data?
  431. var error: AFError?
  432. // When
  433. let upload = manager.upload(multipartFormData: { multipartFormData in
  434. multipartFormData.append(french, withName: "french")
  435. multipartFormData.append(japanese, withName: "japanese")
  436. },
  437. to: urlString)
  438. .response { defaultResponse in
  439. request = defaultResponse.request
  440. response = defaultResponse.response
  441. data = defaultResponse.data
  442. error = defaultResponse.error
  443. expectation.fulfill()
  444. }
  445. waitForExpectations(timeout: timeout, handler: nil)
  446. // Then
  447. XCTAssertNotNil(request, "request should not be nil")
  448. XCTAssertNotNil(response, "response should not be nil")
  449. XCTAssertNotNil(data, "data should not be nil")
  450. XCTAssertNil(error, "error should be nil")
  451. guard let uploadable = upload.uploadable, case .file = uploadable else {
  452. XCTFail("Uploadable is not .file")
  453. return
  454. }
  455. }
  456. #endif
  457. // MARK: Combined Test Execution
  458. private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
  459. // Given
  460. let urlString = "https://httpbin.org/post"
  461. let loremData1 = Data(String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  462. count: 100).utf8)
  463. let loremData2 = Data(String(repeating: "Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.",
  464. count: 100).utf8)
  465. let expectation = self.expectation(description: "multipart form data upload should succeed")
  466. var uploadProgressValues: [Double] = []
  467. var downloadProgressValues: [Double] = []
  468. var response: DataResponse<Data?, AFError>?
  469. // When
  470. AF.upload(multipartFormData: { multipartFormData in
  471. multipartFormData.append(loremData1, withName: "lorem1")
  472. multipartFormData.append(loremData2, withName: "lorem2")
  473. },
  474. to: urlString,
  475. usingThreshold: streamFromDisk ? 0 : 100_000_000)
  476. .uploadProgress { progress in
  477. uploadProgressValues.append(progress.fractionCompleted)
  478. }
  479. .downloadProgress { progress in
  480. downloadProgressValues.append(progress.fractionCompleted)
  481. }
  482. .response { resp in
  483. response = resp
  484. expectation.fulfill()
  485. }
  486. waitForExpectations(timeout: timeout, handler: nil)
  487. // Then
  488. XCTAssertNotNil(response?.request)
  489. XCTAssertNotNil(response?.response)
  490. XCTAssertNotNil(response?.data)
  491. XCTAssertNil(response?.error)
  492. var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
  493. for progress in uploadProgressValues {
  494. XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
  495. previousUploadProgress = progress
  496. }
  497. if let lastProgressValue = uploadProgressValues.last {
  498. XCTAssertEqual(lastProgressValue, 1.0)
  499. } else {
  500. XCTFail("last item in uploadProgressValues should not be nil")
  501. }
  502. var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
  503. for progress in downloadProgressValues {
  504. XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
  505. previousDownloadProgress = progress
  506. }
  507. if let lastProgressValue = downloadProgressValues.last {
  508. XCTAssertEqual(lastProgressValue, 1.0)
  509. } else {
  510. XCTFail("last item in downloadProgressValues should not be nil")
  511. }
  512. }
  513. }
  514. final class UploadRequestEventsTestCase: BaseTestCase {
  515. func testThatUploadRequestTriggersAllAppropriateLifetimeEvents() {
  516. // Given
  517. let eventMonitor = ClosureEventMonitor()
  518. let session = Session(eventMonitors: [eventMonitor])
  519. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  520. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  521. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  522. let didCreateTask = expectation(description: "didCreateTask should fire")
  523. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  524. let didComplete = expectation(description: "didComplete should fire")
  525. let didFinish = expectation(description: "didFinish should fire")
  526. let didResume = expectation(description: "didResume should fire")
  527. let didResumeTask = expectation(description: "didResumeTask should fire")
  528. let didCreateUploadable = expectation(description: "didCreateUploadable should fire")
  529. let didParseResponse = expectation(description: "didParseResponse should fire")
  530. let responseHandler = expectation(description: "responseHandler should fire")
  531. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  532. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  533. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  534. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  535. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  536. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  537. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  538. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  539. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  540. eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() }
  541. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  542. // When
  543. let request = session.upload(Data("PAYLOAD".utf8),
  544. with: URLRequest.makeHTTPBinRequest(path: "post", method: .post)).response { _ in
  545. responseHandler.fulfill()
  546. }
  547. waitForExpectations(timeout: timeout, handler: nil)
  548. // Then
  549. XCTAssertEqual(request.state, .finished)
  550. }
  551. func testThatCancelledUploadRequestTriggersAllAppropriateLifetimeEvents() {
  552. // Given
  553. let eventMonitor = ClosureEventMonitor()
  554. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  555. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  556. let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  557. let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
  558. let didCreateTask = expectation(description: "didCreateTask should fire")
  559. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  560. let didComplete = expectation(description: "didComplete should fire")
  561. let didFinish = expectation(description: "didFinish should fire")
  562. let didResume = expectation(description: "didResume should fire")
  563. let didResumeTask = expectation(description: "didResumeTask should fire")
  564. let didCreateUploadable = expectation(description: "didCreateUploadable should fire")
  565. let didParseResponse = expectation(description: "didParseResponse should fire")
  566. let didCancel = expectation(description: "didCancel should fire")
  567. let didCancelTask = expectation(description: "didCancelTask should fire")
  568. let responseHandler = expectation(description: "responseHandler should fire")
  569. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  570. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
  571. eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  572. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  573. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  574. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  575. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  576. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  577. eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() }
  578. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  579. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  580. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  581. // When
  582. let request = session.upload(Data("PAYLOAD".utf8),
  583. with: URLRequest.makeHTTPBinRequest(path: "delay/5", method: .post)).response { _ in
  584. responseHandler.fulfill()
  585. }
  586. eventMonitor.requestDidResumeTask = { _, _ in
  587. request.cancel()
  588. didResumeTask.fulfill()
  589. }
  590. request.resume()
  591. waitForExpectations(timeout: timeout, handler: nil)
  592. // Then
  593. XCTAssertEqual(request.state, .cancelled)
  594. }
  595. }