RequestTests.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. //
  2. // RequestTests.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. final class RequestResponseTestCase: BaseTestCase {
  28. func testRequestResponse() {
  29. // Given
  30. let urlString = "https://httpbin.org/get"
  31. let expectation = self.expectation(description: "GET request should succeed: \(urlString)")
  32. var response: DataResponse<Data?, AFError>?
  33. // When
  34. AF.request(urlString, parameters: ["foo": "bar"])
  35. .response { resp in
  36. response = resp
  37. expectation.fulfill()
  38. }
  39. waitForExpectations(timeout: timeout, handler: nil)
  40. // Then
  41. XCTAssertNotNil(response?.request)
  42. XCTAssertNotNil(response?.response)
  43. XCTAssertNotNil(response?.data)
  44. XCTAssertNil(response?.error)
  45. }
  46. func testRequestResponseWithProgress() {
  47. // Given
  48. let randomBytes = 1 * 25 * 1024
  49. let urlString = "https://httpbin.org/bytes/\(randomBytes)"
  50. let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)")
  51. var progressValues: [Double] = []
  52. var response: DataResponse<Data?, AFError>?
  53. // When
  54. AF.request(urlString)
  55. .downloadProgress { progress in
  56. progressValues.append(progress.fractionCompleted)
  57. }
  58. .response { resp in
  59. response = resp
  60. expectation.fulfill()
  61. }
  62. waitForExpectations(timeout: timeout, handler: nil)
  63. // Then
  64. XCTAssertNotNil(response?.request)
  65. XCTAssertNotNil(response?.response)
  66. XCTAssertNotNil(response?.data)
  67. XCTAssertNil(response?.error)
  68. var previousProgress: Double = progressValues.first ?? 0.0
  69. for progress in progressValues {
  70. XCTAssertGreaterThanOrEqual(progress, previousProgress)
  71. previousProgress = progress
  72. }
  73. if let lastProgressValue = progressValues.last {
  74. XCTAssertEqual(lastProgressValue, 1.0)
  75. } else {
  76. XCTFail("last item in progressValues should not be nil")
  77. }
  78. }
  79. func testPOSTRequestWithUnicodeParameters() {
  80. // Given
  81. let urlString = "https://httpbin.org/post"
  82. let parameters = ["french": "français",
  83. "japanese": "日本語",
  84. "arabic": "العربية",
  85. "emoji": "😃"]
  86. let expectation = self.expectation(description: "request should succeed")
  87. var response: DataResponse<Any, AFError>?
  88. // When
  89. AF.request(urlString, method: .post, parameters: parameters)
  90. .responseJSON { closureResponse in
  91. response = closureResponse
  92. expectation.fulfill()
  93. }
  94. waitForExpectations(timeout: timeout, handler: nil)
  95. // Then
  96. XCTAssertNotNil(response?.request)
  97. XCTAssertNotNil(response?.response)
  98. XCTAssertNotNil(response?.data)
  99. if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] {
  100. XCTAssertEqual(form["french"], parameters["french"])
  101. XCTAssertEqual(form["japanese"], parameters["japanese"])
  102. XCTAssertEqual(form["arabic"], parameters["arabic"])
  103. XCTAssertEqual(form["emoji"], parameters["emoji"])
  104. } else {
  105. XCTFail("form parameter in JSON should not be nil")
  106. }
  107. }
  108. #if !SWIFT_PACKAGE
  109. func testPOSTRequestWithBase64EncodedImages() {
  110. // Given
  111. let urlString = "https://httpbin.org/post"
  112. let pngBase64EncodedString: String = {
  113. let URL = url(forResource: "unicorn", withExtension: "png")
  114. let data = try! Data(contentsOf: URL)
  115. return data.base64EncodedString(options: .lineLength64Characters)
  116. }()
  117. let jpegBase64EncodedString: String = {
  118. let URL = url(forResource: "rainbow", withExtension: "jpg")
  119. let data = try! Data(contentsOf: URL)
  120. return data.base64EncodedString(options: .lineLength64Characters)
  121. }()
  122. let parameters = ["email": "user@alamofire.org",
  123. "png_image": pngBase64EncodedString,
  124. "jpeg_image": jpegBase64EncodedString]
  125. let expectation = self.expectation(description: "request should succeed")
  126. var response: DataResponse<Any, AFError>?
  127. // When
  128. AF.request(urlString, method: .post, parameters: parameters)
  129. .responseJSON { closureResponse in
  130. response = closureResponse
  131. expectation.fulfill()
  132. }
  133. waitForExpectations(timeout: timeout, handler: nil)
  134. // Then
  135. XCTAssertNotNil(response?.request)
  136. XCTAssertNotNil(response?.response)
  137. XCTAssertNotNil(response?.data)
  138. XCTAssertEqual(response?.result.isSuccess, true)
  139. if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] {
  140. XCTAssertEqual(form["email"], parameters["email"])
  141. XCTAssertEqual(form["png_image"], parameters["png_image"])
  142. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
  143. } else {
  144. XCTFail("form parameter in JSON should not be nil")
  145. }
  146. }
  147. #endif
  148. // MARK: Queues
  149. func testThatResponseSerializationWorksWithSerializationQueue() {
  150. // Given
  151. let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  152. let manager = Session(serializationQueue: queue)
  153. let expectation = self.expectation(description: "request should complete")
  154. var response: DataResponse<Any, AFError>?
  155. // When
  156. manager.request("https://httpbin.org/get").responseJSON { resp in
  157. response = resp
  158. expectation.fulfill()
  159. }
  160. waitForExpectations(timeout: timeout, handler: nil)
  161. // Then
  162. XCTAssertEqual(response?.result.isSuccess, true)
  163. }
  164. func testThatRequestsWorksWithRequestAndSerializationQueue() {
  165. // Given
  166. let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue")
  167. let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue")
  168. let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue)
  169. let expectation = self.expectation(description: "request should complete")
  170. var response: DataResponse<Any, AFError>?
  171. // When
  172. manager.request("https://httpbin.org/get").responseJSON { resp in
  173. response = resp
  174. expectation.fulfill()
  175. }
  176. waitForExpectations(timeout: timeout, handler: nil)
  177. // Then
  178. XCTAssertEqual(response?.result.isSuccess, true)
  179. }
  180. // MARK: Encodable Parameters
  181. func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
  182. // Given
  183. let parameters = HTTPBinParameters(property: "one")
  184. let expect = expectation(description: "request should complete")
  185. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  186. // When
  187. AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
  188. .responseDecodable(of: HTTPBinResponse.self) { response in
  189. receivedResponse = response
  190. expect.fulfill()
  191. }
  192. waitForExpectations(timeout: timeout, handler: nil)
  193. // Then
  194. XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}")
  195. }
  196. func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
  197. // Given
  198. let parameters = HTTPBinParameters(property: "one")
  199. let expect = expectation(description: "request should complete")
  200. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  201. // When
  202. AF.request("https://httpbin.org/get", method: .get, parameters: parameters)
  203. .responseDecodable(of: HTTPBinResponse.self) { response in
  204. receivedResponse = response
  205. expect.fulfill()
  206. }
  207. waitForExpectations(timeout: timeout, handler: nil)
  208. // Then
  209. XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"])
  210. }
  211. func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
  212. // Given
  213. let parameters = HTTPBinParameters(property: "one")
  214. let expect = expectation(description: "request should complete")
  215. var receivedResponse: DataResponse<HTTPBinResponse, AFError>?
  216. // When
  217. AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
  218. .responseDecodable(of: HTTPBinResponse.self) { response in
  219. receivedResponse = response
  220. expect.fulfill()
  221. }
  222. waitForExpectations(timeout: timeout, handler: nil)
  223. // Then
  224. XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"])
  225. }
  226. // MARK: Lifetime Events
  227. func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
  228. // Given
  229. let eventMonitor = ClosureEventMonitor()
  230. let session = Session(eventMonitors: [eventMonitor])
  231. let expect = expectation(description: "request should receive appropriate lifetime events")
  232. expect.expectedFulfillmentCount = 4
  233. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  234. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  235. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  236. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  237. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  238. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  239. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  240. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  241. // When
  242. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  243. waitForExpectations(timeout: timeout, handler: nil)
  244. // Then
  245. XCTAssertEqual(request.state, .finished)
  246. }
  247. func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  248. // Given
  249. let eventMonitor = ClosureEventMonitor()
  250. let session = Session(eventMonitors: [eventMonitor])
  251. let expect = expectation(description: "request should receive appropriate lifetime events")
  252. expect.expectedFulfillmentCount = 4
  253. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  254. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  255. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  256. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  257. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  258. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  259. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  260. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  261. // When
  262. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  263. for _ in 0..<100 {
  264. request.resume()
  265. }
  266. waitForExpectations(timeout: timeout, handler: nil)
  267. // Then
  268. XCTAssertEqual(request.state, .finished)
  269. }
  270. func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  271. // Given
  272. let eventMonitor = ClosureEventMonitor()
  273. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  274. let expect = expectation(description: "request should receive appropriate lifetime events")
  275. expect.expectedFulfillmentCount = 3
  276. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  277. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  278. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  279. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  280. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  281. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  282. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  283. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  284. // When
  285. let request = session.request(URLRequest.makeHTTPBinRequest())
  286. for _ in 0..<100 {
  287. request.resume()
  288. }
  289. waitForExpectations(timeout: timeout, handler: nil)
  290. // Then
  291. XCTAssertEqual(request.state, .finished)
  292. }
  293. func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  294. // Given
  295. let eventMonitor = ClosureEventMonitor()
  296. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  297. let expect = expectation(description: "request should receive appropriate lifetime events")
  298. expect.expectedFulfillmentCount = 4
  299. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  300. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  301. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  302. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  303. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  304. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  305. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  306. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  307. // When
  308. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() }
  309. for _ in 0..<100 {
  310. request.resume()
  311. }
  312. waitForExpectations(timeout: timeout, handler: nil)
  313. // Then
  314. XCTAssertEqual(request.state, .finished)
  315. }
  316. func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  317. // Given
  318. let eventMonitor = ClosureEventMonitor()
  319. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  320. let expect = expectation(description: "request should receive appropriate lifetime events")
  321. expect.expectedFulfillmentCount = 2
  322. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  323. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  324. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  325. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  326. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  327. // When
  328. let request = session.request(URLRequest.makeHTTPBinRequest())
  329. for _ in 0..<100 {
  330. request.suspend()
  331. }
  332. waitForExpectations(timeout: timeout, handler: nil)
  333. // Then
  334. XCTAssertEqual(request.state, .suspended)
  335. }
  336. func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  337. // Given
  338. let eventMonitor = ClosureEventMonitor()
  339. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  340. let expect = expectation(description: "request should receive appropriate lifetime events")
  341. expect.expectedFulfillmentCount = 2
  342. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  343. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  344. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  345. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  346. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  347. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  348. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  349. // When
  350. let request = session.request(URLRequest.makeHTTPBinRequest())
  351. for _ in 0..<100 {
  352. request.suspend()
  353. }
  354. waitForExpectations(timeout: timeout, handler: nil)
  355. // Then
  356. XCTAssertEqual(request.state, .suspended)
  357. }
  358. func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  359. // Given
  360. let eventMonitor = ClosureEventMonitor()
  361. let session = Session(eventMonitors: [eventMonitor])
  362. let expect = expectation(description: "request should receive appropriate lifetime events")
  363. expect.expectedFulfillmentCount = 2
  364. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  365. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  366. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  367. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  368. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  369. // When
  370. let request = session.request(URLRequest.makeHTTPBinRequest())
  371. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  372. eventMonitor.requestDidCreateTask = { _, _ in
  373. for _ in 0..<100 {
  374. request.cancel()
  375. }
  376. }
  377. waitForExpectations(timeout: timeout, handler: nil)
  378. // Then
  379. XCTAssertEqual(request.state, .cancelled)
  380. }
  381. func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  382. // Given
  383. let eventMonitor = ClosureEventMonitor()
  384. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  385. let expect = expectation(description: "request should receive appropriate lifetime events")
  386. expect.expectedFulfillmentCount = 2
  387. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  388. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  389. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  390. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  391. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  392. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  393. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  394. // When
  395. let request = session.request(URLRequest.makeHTTPBinRequest())
  396. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  397. eventMonitor.requestDidCreateTask = { _, _ in
  398. for _ in 0..<100 {
  399. request.cancel()
  400. }
  401. }
  402. waitForExpectations(timeout: timeout, handler: nil)
  403. // Then
  404. XCTAssertEqual(request.state, .cancelled)
  405. }
  406. func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
  407. // Given
  408. let eventMonitor = ClosureEventMonitor()
  409. let session = Session(eventMonitors: [eventMonitor])
  410. let expect = expectation(description: "request should receive appropriate lifetime events")
  411. expect.expectedFulfillmentCount = 6
  412. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  413. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  414. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  415. eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() }
  416. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  417. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  418. eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() }
  419. // When
  420. let request = session.request(URLRequest.makeHTTPBinRequest(path: "delay/5")).response { _ in expect.fulfill() }
  421. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  422. eventMonitor.requestDidCreateTask = { _, _ in
  423. DispatchQueue.concurrentPerform(iterations: 100) { i in
  424. request.cancel()
  425. if i == 99 { expect.fulfill() }
  426. }
  427. }
  428. waitForExpectations(timeout: timeout, handler: nil)
  429. // Then
  430. XCTAssertEqual(request.state, .cancelled)
  431. }
  432. func testThatRequestTriggersAllAppropriateLifetimeEvents() {
  433. // Given
  434. let eventMonitor = ClosureEventMonitor()
  435. let session = Session(eventMonitors: [eventMonitor])
  436. let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire")
  437. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  438. let didReceiveData = expectation(description: "didReceiveData should fire")
  439. let willCacheResponse = expectation(description: "willCacheResponse should fire")
  440. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  441. let didCreateTask = expectation(description: "didCreateTask should fire")
  442. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  443. let didComplete = expectation(description: "didComplete should fire")
  444. let didFinish = expectation(description: "didFinish should fire")
  445. let didResume = expectation(description: "didResume should fire")
  446. let didResumeTask = expectation(description: "didResumeTask should fire")
  447. let didParseResponse = expectation(description: "didParseResponse should fire")
  448. let responseHandler = expectation(description: "responseHandler should fire")
  449. var dataReceived = false
  450. eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() }
  451. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  452. eventMonitor.dataTaskDidReceiveData = { _, _, _ in
  453. guard !dataReceived else { return }
  454. // Data may be received many times, fulfill only once.
  455. dataReceived = true
  456. didReceiveData.fulfill()
  457. }
  458. eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() }
  459. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  460. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  461. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  462. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  463. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  464. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  465. eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
  466. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  467. // When
  468. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in
  469. responseHandler.fulfill()
  470. }
  471. waitForExpectations(timeout: timeout, handler: nil)
  472. // Then
  473. XCTAssertEqual(request.state, .finished)
  474. }
  475. func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
  476. // Given
  477. let eventMonitor = ClosureEventMonitor()
  478. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  479. let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
  480. let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
  481. let didCreateTask = expectation(description: "didCreateTask should fire")
  482. let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
  483. let didComplete = expectation(description: "didComplete should fire")
  484. let didFinish = expectation(description: "didFinish should fire")
  485. let didResume = expectation(description: "didResume should fire")
  486. let didResumeTask = expectation(description: "didResumeTask should fire")
  487. let didParseResponse = expectation(description: "didParseResponse should fire")
  488. let didCancel = expectation(description: "didCancel should fire")
  489. let didCancelTask = expectation(description: "didCancelTask should fire")
  490. let responseHandler = expectation(description: "responseHandler should fire")
  491. eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
  492. eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() }
  493. eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
  494. eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
  495. eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
  496. eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
  497. eventMonitor.requestDidResume = { _ in didResume.fulfill() }
  498. eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
  499. eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
  500. eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
  501. // When
  502. let request = session.request(URLRequest.makeHTTPBinRequest(path: "delay/5")).response { _ in
  503. responseHandler.fulfill()
  504. }
  505. eventMonitor.requestDidResumeTask = { _, _ in
  506. request.cancel()
  507. didResumeTask.fulfill()
  508. }
  509. request.resume()
  510. waitForExpectations(timeout: timeout, handler: nil)
  511. // Then
  512. XCTAssertEqual(request.state, .cancelled)
  513. }
  514. func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
  515. // Given
  516. let session = Session()
  517. var response1: DataResponse<Any, AFError>?
  518. var response2: DataResponse<Any, AFError>?
  519. let expect = expectation(description: "both response serializer completions should be called")
  520. expect.expectedFulfillmentCount = 2
  521. // When
  522. let request = session.request(URLRequest.makeHTTPBinRequest())
  523. request.responseJSON { resp in
  524. response1 = resp
  525. expect.fulfill()
  526. request.responseJSON { resp in
  527. response2 = resp
  528. expect.fulfill()
  529. }
  530. }
  531. request.cancel()
  532. waitForExpectations(timeout: timeout, handler: nil)
  533. // Then
  534. XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true)
  535. XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true)
  536. }
  537. func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() {
  538. // Given
  539. let session = Session()
  540. var response1: DataResponse<Any, AFError>?
  541. var response2: DataResponse<Any, AFError>?
  542. var response3: DataResponse<Any, AFError>?
  543. let expect = expectation(description: "all response serializer completions should be called")
  544. expect.expectedFulfillmentCount = 3
  545. // When
  546. let request = session.request(URLRequest.makeHTTPBinRequest())
  547. request.responseJSON { resp in
  548. response1 = resp
  549. expect.fulfill()
  550. request.responseJSON { resp in
  551. response2 = resp
  552. expect.fulfill()
  553. request.responseJSON { resp in
  554. response3 = resp
  555. expect.fulfill()
  556. }
  557. }
  558. }
  559. waitForExpectations(timeout: timeout, handler: nil)
  560. // Then
  561. XCTAssertNotNil(response1?.value)
  562. XCTAssertNotNil(response2?.value)
  563. XCTAssertNotNil(response3?.value)
  564. }
  565. func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() {
  566. // Given
  567. let session = Session()
  568. let request = session.request(URLRequest.makeHTTPBinRequest())
  569. var response1: DataResponse<Any, AFError>?
  570. var response2: DataResponse<Any, AFError>?
  571. var response3: DataResponse<Any, AFError>?
  572. // When
  573. let expect1 = expectation(description: "response serializer 1 completion should be called")
  574. request.responseJSON { response1 = $0; expect1.fulfill() }
  575. waitForExpectations(timeout: timeout, handler: nil)
  576. let expect2 = expectation(description: "response serializer 2 completion should be called")
  577. request.responseJSON { response2 = $0; expect2.fulfill() }
  578. waitForExpectations(timeout: timeout, handler: nil)
  579. let expect3 = expectation(description: "response serializer 3 completion should be called")
  580. request.responseJSON { response3 = $0; expect3.fulfill() }
  581. waitForExpectations(timeout: timeout, handler: nil)
  582. // Then
  583. XCTAssertNotNil(response1?.value)
  584. XCTAssertNotNil(response2?.value)
  585. XCTAssertNotNil(response3?.value)
  586. }
  587. }
  588. // MARK: -
  589. class RequestDescriptionTestCase: BaseTestCase {
  590. func testRequestDescription() {
  591. // Given
  592. let urlString = "https://httpbin.org/get"
  593. let manager = Session(startRequestsImmediately: false)
  594. let request = manager.request(urlString)
  595. let expectation = self.expectation(description: "Request description should update: \(urlString)")
  596. var response: HTTPURLResponse?
  597. // When
  598. request.response { resp in
  599. response = resp.response
  600. expectation.fulfill()
  601. }.resume()
  602. waitForExpectations(timeout: timeout, handler: nil)
  603. // Then
  604. XCTAssertEqual(request.description, "GET https://httpbin.org/get (\(response?.statusCode ?? -1))")
  605. }
  606. }
  607. // MARK: -
  608. final class RequestCURLDescriptionTestCase: BaseTestCase {
  609. // MARK: Properties
  610. let manager: Session = {
  611. let manager = Session()
  612. return manager
  613. }()
  614. let managerWithAcceptLanguageHeader: Session = {
  615. var headers = HTTPHeaders.default
  616. headers["Accept-Language"] = "en-US"
  617. let configuration = URLSessionConfiguration.af.default
  618. configuration.headers = headers
  619. let manager = Session(configuration: configuration)
  620. return manager
  621. }()
  622. let managerWithContentTypeHeader: Session = {
  623. var headers = HTTPHeaders.default
  624. headers["Content-Type"] = "application/json"
  625. let configuration = URLSessionConfiguration.af.default
  626. configuration.headers = headers
  627. let manager = Session(configuration: configuration)
  628. return manager
  629. }()
  630. func managerWithCookie(_ cookie: HTTPCookie) -> Session {
  631. let configuration = URLSessionConfiguration.af.default
  632. configuration.httpCookieStorage?.setCookie(cookie)
  633. return Session(configuration: configuration)
  634. }
  635. let managerDisallowingCookies: Session = {
  636. let configuration = URLSessionConfiguration.af.default
  637. configuration.httpShouldSetCookies = false
  638. let manager = Session(configuration: configuration)
  639. return manager
  640. }()
  641. // MARK: Tests
  642. func testGETRequestCURLDescription() {
  643. // Given
  644. let urlString = "https://httpbin.org/get"
  645. let expectation = self.expectation(description: "request should complete")
  646. var components: [String]?
  647. // When
  648. manager.request(urlString).cURLDescription {
  649. components = self.cURLCommandComponents(from: $0)
  650. expectation.fulfill()
  651. }
  652. waitForExpectations(timeout: timeout, handler: nil)
  653. // Then
  654. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  655. XCTAssertTrue(components?.contains("-X") == true)
  656. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  657. }
  658. func testGETRequestCURLDescriptionSynchronous() {
  659. // Given
  660. let urlString = "https://httpbin.org/get"
  661. let expectation = self.expectation(description: "request should complete")
  662. var components: [String]?
  663. var syncComponents: [String]?
  664. // When
  665. let request = manager.request(urlString)
  666. request.cURLDescription {
  667. components = self.cURLCommandComponents(from: $0)
  668. syncComponents = self.cURLCommandComponents(from: request.cURLDescription())
  669. expectation.fulfill()
  670. }
  671. waitForExpectations(timeout: timeout, handler: nil)
  672. // Then
  673. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  674. XCTAssertTrue(components?.contains("-X") == true)
  675. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  676. XCTAssertEqual(components?.sorted(), syncComponents?.sorted())
  677. }
  678. func testGETRequestCURLDescriptionCanBeRequestedManyTimes() {
  679. // Given
  680. let urlString = "https://httpbin.org/get"
  681. let expectation = self.expectation(description: "request should complete")
  682. var components: [String]?
  683. var secondComponents: [String]?
  684. // When
  685. let request = manager.request(urlString)
  686. request.cURLDescription {
  687. components = self.cURLCommandComponents(from: $0)
  688. request.cURLDescription {
  689. secondComponents = self.cURLCommandComponents(from: $0)
  690. expectation.fulfill()
  691. }
  692. }
  693. // Trigger the overwrite behavior.
  694. request.cURLDescription {
  695. components = self.cURLCommandComponents(from: $0)
  696. request.cURLDescription {
  697. secondComponents = self.cURLCommandComponents(from: $0)
  698. expectation.fulfill()
  699. }
  700. }
  701. waitForExpectations(timeout: timeout, handler: nil)
  702. // Then
  703. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  704. XCTAssertTrue(components?.contains("-X") == true)
  705. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  706. XCTAssertEqual(components?.sorted(), secondComponents?.sorted())
  707. }
  708. func testGETRequestWithCustomHeaderCURLDescription() {
  709. // Given
  710. let urlString = "https://httpbin.org/get"
  711. let expectation = self.expectation(description: "request should complete")
  712. var cURLDescription: String?
  713. // When
  714. let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"]
  715. manager.request(urlString, headers: headers).cURLDescription {
  716. cURLDescription = $0
  717. expectation.fulfill()
  718. }
  719. waitForExpectations(timeout: timeout, handler: nil)
  720. // Then
  721. XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
  722. }
  723. func testGETRequestWithDuplicateHeadersDebugDescription() {
  724. // Given
  725. let urlString = "https://httpbin.org/get"
  726. let expectation = self.expectation(description: "request should complete")
  727. var cURLDescription: String?
  728. var components: [String]?
  729. // When
  730. let headers: HTTPHeaders = ["Accept-Language": "en-GB"]
  731. managerWithAcceptLanguageHeader.request(urlString, headers: headers).cURLDescription {
  732. components = self.cURLCommandComponents(from: $0)
  733. cURLDescription = $0
  734. expectation.fulfill()
  735. }
  736. waitForExpectations(timeout: timeout, handler: nil)
  737. // Then
  738. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  739. XCTAssertTrue(components?.contains("-X") == true)
  740. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  741. let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count
  742. XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header")
  743. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\""))
  744. }
  745. func testPOSTRequestCURLDescription() {
  746. // Given
  747. let urlString = "https://httpbin.org/post"
  748. let expectation = self.expectation(description: "request should complete")
  749. var components: [String]?
  750. // When
  751. manager.request(urlString, method: .post).cURLDescription {
  752. components = self.cURLCommandComponents(from: $0)
  753. expectation.fulfill()
  754. }
  755. waitForExpectations(timeout: timeout, handler: nil)
  756. // Then
  757. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  758. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  759. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  760. }
  761. func testPOSTRequestWithJSONParametersCURLDescription() {
  762. // Given
  763. let urlString = "https://httpbin.org/post"
  764. let expectation = self.expectation(description: "request should complete")
  765. var cURLDescription: String?
  766. var components: [String]?
  767. let parameters = ["foo": "bar",
  768. "fo\"o": "b\"ar",
  769. "f'oo": "ba'r"]
  770. // When
  771. manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).cURLDescription {
  772. components = self.cURLCommandComponents(from: $0)
  773. cURLDescription = $0
  774. expectation.fulfill()
  775. }
  776. waitForExpectations(timeout: timeout, handler: nil)
  777. // Then
  778. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  779. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  780. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: application/json\""))
  781. XCTAssertNotNil(cURLDescription?.range(of: "-d \"{"))
  782. XCTAssertNotNil(cURLDescription?.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
  783. XCTAssertNotNil(cURLDescription?.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
  784. XCTAssertNotNil(cURLDescription?.range(of: "\\\"foo\\\":\\\"bar\\"))
  785. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  786. }
  787. func testPOSTRequestWithCookieCURLDescription() {
  788. // Given
  789. let urlString = "https://httpbin.org/post"
  790. let properties = [HTTPCookiePropertyKey.domain: "httpbin.org",
  791. HTTPCookiePropertyKey.path: "/post",
  792. HTTPCookiePropertyKey.name: "foo",
  793. HTTPCookiePropertyKey.value: "bar"]
  794. let cookie = HTTPCookie(properties: properties)!
  795. let cookieManager = managerWithCookie(cookie)
  796. let expectation = self.expectation(description: "request should complete")
  797. var components: [String]?
  798. // When
  799. cookieManager.request(urlString, method: .post).cURLDescription {
  800. components = self.cURLCommandComponents(from: $0)
  801. expectation.fulfill()
  802. }
  803. waitForExpectations(timeout: timeout, handler: nil)
  804. // Then
  805. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  806. XCTAssertEqual(components?[3..<5], ["-X", "POST"])
  807. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  808. XCTAssertEqual(components?[5..<6], ["-b"])
  809. }
  810. func testPOSTRequestWithCookiesDisabledCURLDescriptionHasNoCookies() {
  811. // Given
  812. let urlString = "https://httpbin.org/post"
  813. let properties = [HTTPCookiePropertyKey.domain: "httpbin.org",
  814. HTTPCookiePropertyKey.path: "/post",
  815. HTTPCookiePropertyKey.name: "foo",
  816. HTTPCookiePropertyKey.value: "bar"]
  817. let cookie = HTTPCookie(properties: properties)!
  818. managerDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
  819. let expectation = self.expectation(description: "request should complete")
  820. var components: [String]?
  821. // When
  822. managerDisallowingCookies.request(urlString, method: .post).cURLDescription {
  823. components = self.cURLCommandComponents(from: $0)
  824. expectation.fulfill()
  825. }
  826. waitForExpectations(timeout: timeout, handler: nil)
  827. // Then
  828. let cookieComponents = components?.filter { $0 == "-b" }
  829. XCTAssertTrue(cookieComponents?.isEmpty == true)
  830. }
  831. func testMultipartFormDataRequestWithDuplicateHeadersCURLDescriptionHasOneContentTypeHeader() {
  832. // Given
  833. let urlString = "https://httpbin.org/post"
  834. let japaneseData = Data("日本語".utf8)
  835. let expectation = self.expectation(description: "multipart form data encoding should succeed")
  836. var cURLDescription: String?
  837. var components: [String]?
  838. // When
  839. managerWithContentTypeHeader.upload(multipartFormData: { data in
  840. data.append(japaneseData, withName: "japanese")
  841. }, to: urlString).cURLDescription {
  842. components = self.cURLCommandComponents(from: $0)
  843. cURLDescription = $0
  844. expectation.fulfill()
  845. }
  846. waitForExpectations(timeout: timeout, handler: nil)
  847. // Then
  848. XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"])
  849. XCTAssertTrue(components?.contains("-X") == true)
  850. XCTAssertEqual(components?.last, "\"\(urlString)\"")
  851. let contentTypeCount = components?.filter { $0.contains("Content-Type") }.count
  852. XCTAssertEqual(contentTypeCount, 1, "command should contain a single Content-Type header")
  853. XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: multipart/form-data;"))
  854. }
  855. func testThatRequestWithInvalidURLDebugDescription() {
  856. // Given
  857. let urlString = "invalid_url"
  858. let expectation = self.expectation(description: "request should complete")
  859. var cURLDescription: String?
  860. // When
  861. manager.request(urlString).cURLDescription {
  862. cURLDescription = $0
  863. expectation.fulfill()
  864. }
  865. waitForExpectations(timeout: timeout, handler: nil)
  866. // Then
  867. XCTAssertNotNil(cURLDescription, "debugDescription should not crash")
  868. }
  869. // MARK: Test Helper Methods
  870. private func cURLCommandComponents(from cURLString: String) -> [String] {
  871. return cURLString.components(separatedBy: .whitespacesAndNewlines)
  872. .filter { $0 != "" && $0 != "\\" }
  873. }
  874. }