RequestTests.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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. 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?>?
  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 * 1024 * 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?>?
  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 = [
  83. "french": "français",
  84. "japanese": "日本語",
  85. "arabic": "العربية",
  86. "emoji": "😃"
  87. ]
  88. let expectation = self.expectation(description: "request should succeed")
  89. var response: DataResponse<Any>?
  90. // When
  91. AF.request(urlString, method: .post, parameters: parameters)
  92. .responseJSON { closureResponse in
  93. response = closureResponse
  94. expectation.fulfill()
  95. }
  96. waitForExpectations(timeout: timeout, handler: nil)
  97. // Then
  98. XCTAssertNotNil(response?.request)
  99. XCTAssertNotNil(response?.response)
  100. XCTAssertNotNil(response?.data)
  101. if let json = response?.result.value as? [String: Any], let form = json["form"] as? [String: String] {
  102. XCTAssertEqual(form["french"], parameters["french"])
  103. XCTAssertEqual(form["japanese"], parameters["japanese"])
  104. XCTAssertEqual(form["arabic"], parameters["arabic"])
  105. XCTAssertEqual(form["emoji"], parameters["emoji"])
  106. } else {
  107. XCTFail("form parameter in JSON should not be nil")
  108. }
  109. }
  110. func testPOSTRequestWithBase64EncodedImages() {
  111. // Given
  112. let urlString = "https://httpbin.org/post"
  113. let pngBase64EncodedString: String = {
  114. let URL = url(forResource: "unicorn", withExtension: "png")
  115. let data = try! Data(contentsOf: URL)
  116. return data.base64EncodedString(options: .lineLength64Characters)
  117. }()
  118. let jpegBase64EncodedString: String = {
  119. let URL = url(forResource: "rainbow", withExtension: "jpg")
  120. let data = try! Data(contentsOf: URL)
  121. return data.base64EncodedString(options: .lineLength64Characters)
  122. }()
  123. let parameters = [
  124. "email": "user@alamofire.org",
  125. "png_image": pngBase64EncodedString,
  126. "jpeg_image": jpegBase64EncodedString
  127. ]
  128. let expectation = self.expectation(description: "request should succeed")
  129. var response: DataResponse<Any>?
  130. // When
  131. AF.request(urlString, method: .post, parameters: parameters)
  132. .responseJSON { closureResponse in
  133. response = closureResponse
  134. expectation.fulfill()
  135. }
  136. waitForExpectations(timeout: timeout, handler: nil)
  137. // Then
  138. XCTAssertNotNil(response?.request)
  139. XCTAssertNotNil(response?.response)
  140. XCTAssertNotNil(response?.data)
  141. XCTAssertEqual(response?.result.isSuccess, true)
  142. if let json = response?.result.value as? [String: Any], let form = json["form"] as? [String: String] {
  143. XCTAssertEqual(form["email"], parameters["email"])
  144. XCTAssertEqual(form["png_image"], parameters["png_image"])
  145. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"])
  146. } else {
  147. XCTFail("form parameter in JSON should not be nil")
  148. }
  149. }
  150. // MARK: Serialization Queue
  151. func testThatResponseSerializationWorksWithSerializationQueue() {
  152. // Given
  153. let queue = DispatchQueue(label: "org.alamofire.serializationQueue")
  154. let manager = Session(serializationQueue: queue)
  155. let expectation = self.expectation(description: "request should complete")
  156. var response: DataResponse<Any>?
  157. // When
  158. manager.request("https://httpbin.org/get").responseJSON { (resp) in
  159. response = resp
  160. expectation.fulfill()
  161. }
  162. waitForExpectations(timeout: timeout, handler: nil)
  163. // Then
  164. XCTAssertEqual(response?.result.isSuccess, true)
  165. }
  166. // MARK: Encodable Parameters
  167. func testThatRequestsCanPassEncodableParametersAsJSONBodyData() {
  168. // Given
  169. let parameters = HTTPBinParameters(property: "one")
  170. let expect = expectation(description: "request should complete")
  171. var receivedResponse: DataResponse<HTTPBinResponse>?
  172. // When
  173. AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
  174. .responseDecodable { (response: DataResponse<HTTPBinResponse>) in
  175. receivedResponse = response
  176. expect.fulfill()
  177. }
  178. waitForExpectations(timeout: timeout, handler: nil)
  179. // Then
  180. XCTAssertEqual(receivedResponse?.result.value?.data, "{\"property\":\"one\"}")
  181. }
  182. func testThatRequestsCanPassEncodableParametersAsAURLQuery() {
  183. // Given
  184. let parameters = HTTPBinParameters(property: "one")
  185. let expect = expectation(description: "request should complete")
  186. var receivedResponse: DataResponse<HTTPBinResponse>?
  187. // When
  188. AF.request("https://httpbin.org/get", method: .get, parameters: parameters)
  189. .responseDecodable { (response: DataResponse<HTTPBinResponse>) in
  190. receivedResponse = response
  191. expect.fulfill()
  192. }
  193. waitForExpectations(timeout: timeout, handler: nil)
  194. // Then
  195. XCTAssertEqual(receivedResponse?.result.value?.args, ["property": "one"])
  196. }
  197. func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() {
  198. // Given
  199. let parameters = HTTPBinParameters(property: "one")
  200. let expect = expectation(description: "request should complete")
  201. var receivedResponse: DataResponse<HTTPBinResponse>?
  202. // When
  203. AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
  204. .responseDecodable { (response: DataResponse<HTTPBinResponse>) in
  205. receivedResponse = response
  206. expect.fulfill()
  207. }
  208. waitForExpectations(timeout: timeout, handler: nil)
  209. // Then
  210. XCTAssertEqual(receivedResponse?.result.value?.form, ["property": "one"])
  211. }
  212. // MARK: Lifetime Events
  213. func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() {
  214. // Given
  215. let eventMonitor = ClosureEventMonitor()
  216. let session = Session(eventMonitors: [eventMonitor])
  217. let expect = expectation(description: "request should receive appropriate lifetime events")
  218. expect.expectedFulfillmentCount = 3
  219. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  220. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  221. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  222. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  223. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  224. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  225. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  226. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  227. // When
  228. let request = session.request(URLRequest.makeHTTPBinRequest())
  229. waitForExpectations(timeout: timeout, handler: nil)
  230. // Then
  231. XCTAssertEqual(request.state, .finished)
  232. }
  233. func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  234. // Given
  235. let eventMonitor = ClosureEventMonitor()
  236. let session = Session(eventMonitors: [eventMonitor])
  237. let expect = expectation(description: "request should receive appropriate lifetime events")
  238. expect.expectedFulfillmentCount = 3
  239. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  240. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  241. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  242. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  243. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  244. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  245. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  246. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  247. // When
  248. let request = session.request(URLRequest.makeHTTPBinRequest())
  249. for _ in 0..<100 {
  250. request.resume()
  251. }
  252. waitForExpectations(timeout: timeout, handler: nil)
  253. // Then
  254. XCTAssertEqual(request.state, .finished)
  255. }
  256. func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() {
  257. // Given
  258. let eventMonitor = ClosureEventMonitor()
  259. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  260. let expect = expectation(description: "request should receive appropriate lifetime events")
  261. expect.expectedFulfillmentCount = 3
  262. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  263. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  264. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  265. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  266. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  267. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  268. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  269. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  270. // When
  271. let request = session.request(URLRequest.makeHTTPBinRequest())
  272. for _ in 0..<100 {
  273. request.resume()
  274. }
  275. waitForExpectations(timeout: timeout, handler: nil)
  276. // Then
  277. XCTAssertEqual(request.state, .finished)
  278. }
  279. func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  280. // Given
  281. let eventMonitor = ClosureEventMonitor()
  282. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  283. let expect = expectation(description: "request should receive appropriate lifetime events")
  284. expect.expectedFulfillmentCount = 3
  285. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  286. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  287. eventMonitor.requestDidFinish = { _ in expect.fulfill() }
  288. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  289. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  290. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  291. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  292. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  293. // When
  294. let request = session.request(URLRequest.makeHTTPBinRequest())
  295. for _ in 0..<100 {
  296. request.resume()
  297. }
  298. waitForExpectations(timeout: timeout, handler: nil)
  299. // Then
  300. XCTAssertEqual(request.state, .finished)
  301. }
  302. func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  303. // Given
  304. let eventMonitor = ClosureEventMonitor()
  305. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  306. let expect = expectation(description: "request should receive appropriate lifetime events")
  307. expect.expectedFulfillmentCount = 2
  308. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  309. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  310. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  311. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  312. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  313. // When
  314. let request = session.request(URLRequest.makeHTTPBinRequest())
  315. for _ in 0..<100 {
  316. request.suspend()
  317. }
  318. waitForExpectations(timeout: timeout, handler: nil)
  319. // Then
  320. XCTAssertEqual(request.state, .suspended)
  321. }
  322. func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  323. // Given
  324. let eventMonitor = ClosureEventMonitor()
  325. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  326. let expect = expectation(description: "request should receive appropriate lifetime events")
  327. expect.expectedFulfillmentCount = 2
  328. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  329. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  330. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  331. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  332. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  333. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  334. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  335. // When
  336. let request = session.request(URLRequest.makeHTTPBinRequest())
  337. for _ in 0..<100 {
  338. request.suspend()
  339. }
  340. waitForExpectations(timeout: timeout, handler: nil)
  341. // Then
  342. XCTAssertEqual(request.state, .suspended)
  343. }
  344. func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() {
  345. // Given
  346. let eventMonitor = ClosureEventMonitor()
  347. let session = Session(eventMonitors: [eventMonitor])
  348. let expect = expectation(description: "request should receive appropriate lifetime events")
  349. expect.expectedFulfillmentCount = 2
  350. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  351. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  352. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  353. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  354. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  355. // When
  356. let request = session.request(URLRequest.makeHTTPBinRequest())
  357. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  358. eventMonitor.requestDidCreateTask = { (_, _) in
  359. for _ in 0..<100 {
  360. request.cancel()
  361. }
  362. }
  363. waitForExpectations(timeout: timeout, handler: nil)
  364. // Then
  365. XCTAssertEqual(request.state, .cancelled)
  366. }
  367. func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() {
  368. // Given
  369. let eventMonitor = ClosureEventMonitor()
  370. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  371. let expect = expectation(description: "request should receive appropriate lifetime events")
  372. expect.expectedFulfillmentCount = 2
  373. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  374. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  375. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  376. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  377. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  378. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  379. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  380. // When
  381. let request = session.request(URLRequest.makeHTTPBinRequest())
  382. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  383. eventMonitor.requestDidCreateTask = { (_, _) in
  384. for _ in 0..<100 {
  385. request.cancel()
  386. }
  387. }
  388. waitForExpectations(timeout: timeout, handler: nil)
  389. // Then
  390. XCTAssertEqual(request.state, .cancelled)
  391. }
  392. func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() {
  393. // Given
  394. let eventMonitor = ClosureEventMonitor()
  395. let session = Session(eventMonitors: [eventMonitor])
  396. let expect = expectation(description: "request should receive appropriate lifetime events")
  397. expect.expectedFulfillmentCount = 5
  398. eventMonitor.requestDidCancelTask = { (_, _) in expect.fulfill() }
  399. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  400. eventMonitor.requestDidResume = { _ in expect.fulfill() }
  401. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  402. // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout.
  403. eventMonitor.requestDidSuspend = { _ in expect.fulfill() }
  404. eventMonitor.requestDidSuspendTask = { (_, _) in expect.fulfill() }
  405. // When
  406. let request = session.request(URLRequest.makeHTTPBinRequest())
  407. // Cancellation stops task creation, so don't cancel the request until the task has been created.
  408. eventMonitor.requestDidCreateTask = { (_, _) in
  409. DispatchQueue.concurrentPerform(iterations: 100) { i in
  410. request.cancel()
  411. if i == 99 { expect.fulfill() }
  412. }
  413. }
  414. waitForExpectations(timeout: timeout, handler: nil)
  415. // Then
  416. XCTAssertEqual(request.state, .cancelled)
  417. }
  418. func testThatRequestTriggersAllAppropriateLifetimeEvents() {
  419. // Given
  420. let eventMonitor = ClosureEventMonitor()
  421. let session = Session(eventMonitors: [eventMonitor])
  422. let expect = expectation(description: "request should receive appropriate lifetime events")
  423. expect.expectedFulfillmentCount = 13
  424. var dataReceived = false
  425. eventMonitor.taskDidReceiveChallenge = { (_, _, _) in expect.fulfill() }
  426. eventMonitor.taskDidFinishCollectingMetrics = { (_, _, _) in expect.fulfill() }
  427. eventMonitor.dataTaskDidReceiveData = { (_, _, _) in
  428. guard !dataReceived else { return }
  429. // Data may be received many times, fulfill only once.
  430. dataReceived = true
  431. expect.fulfill()
  432. }
  433. eventMonitor.dataTaskWillCacheResponse = { (_, _, _) in expect.fulfill() }
  434. eventMonitor.requestDidCreateURLRequest = { (_, _) in expect.fulfill() }
  435. eventMonitor.requestDidCreateTask = { (_, _) in expect.fulfill() }
  436. eventMonitor.requestDidGatherMetrics = { (_, _) in expect.fulfill() }
  437. eventMonitor.requestDidCompleteTaskWithError = { (_, _, _) in expect.fulfill() }
  438. eventMonitor.requestDidFinish = { (_) in expect.fulfill() }
  439. eventMonitor.requestDidResume = { (_) in expect.fulfill() }
  440. eventMonitor.requestDidResumeTask = { (_, _) in expect.fulfill() }
  441. eventMonitor.requestDidParseResponse = { (_, _) in expect.fulfill() }
  442. // When
  443. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in
  444. expect.fulfill()
  445. }
  446. waitForExpectations(timeout: timeout, handler: nil)
  447. // Then
  448. XCTAssertEqual(request.state, .finished)
  449. }
  450. func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() {
  451. // Given
  452. let eventMonitor = ClosureEventMonitor()
  453. let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
  454. let expect = expectation(description: "request should receive appropriate lifetime events")
  455. expect.expectedFulfillmentCount = 12
  456. eventMonitor.taskDidFinishCollectingMetrics = { (_, _, _) in expect.fulfill() }
  457. eventMonitor.requestDidCreateURLRequest = { (_, _) in expect.fulfill() }
  458. eventMonitor.requestDidCreateTask = { (_, _) in expect.fulfill() }
  459. eventMonitor.requestDidGatherMetrics = { (_, _) in expect.fulfill() }
  460. eventMonitor.requestDidCompleteTaskWithError = { (_, _, _) in expect.fulfill() }
  461. eventMonitor.requestDidFinish = { (_) in expect.fulfill() }
  462. eventMonitor.requestDidResume = { (_) in expect.fulfill() }
  463. eventMonitor.requestDidCancel = { _ in expect.fulfill() }
  464. eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() }
  465. eventMonitor.requestDidParseResponse = { (_, _) in expect.fulfill() }
  466. // When
  467. let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in
  468. expect.fulfill()
  469. }
  470. eventMonitor.requestDidResumeTask = { (_, _) in
  471. request.cancel()
  472. expect.fulfill()
  473. }
  474. request.resume()
  475. waitForExpectations(timeout: timeout, handler: nil)
  476. // Then
  477. XCTAssertEqual(request.state, .cancelled)
  478. }
  479. func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() {
  480. // Given
  481. let session = Session()
  482. var response1: DataResponse<Any>?
  483. var response2: DataResponse<Any>?
  484. let expect = expectation(description: "both response serializer completions should be called")
  485. expect.expectedFulfillmentCount = 2
  486. // When
  487. let request = session.request(URLRequest.makeHTTPBinRequest())
  488. request.responseJSON { resp in
  489. response1 = resp
  490. expect.fulfill()
  491. request.responseJSON { resp in
  492. response2 = resp
  493. expect.fulfill()
  494. }
  495. }
  496. request.cancel()
  497. waitForExpectations(timeout: timeout, handler: nil)
  498. // Then
  499. XCTAssertEqual(response1?.error?.asAFError?.isExplicitlyCancelledError, true)
  500. XCTAssertEqual(response2?.error?.asAFError?.isExplicitlyCancelledError, true)
  501. }
  502. func testThatAppendingResponseSerializerToCompletedRequestCallsCompletion() {
  503. // Given
  504. let session = Session()
  505. var response1: DataResponse<Any>?
  506. var response2: DataResponse<Any>?
  507. let expect = expectation(description: "both response serializer completions should be called")
  508. expect.expectedFulfillmentCount = 2
  509. // When
  510. let request = session.request(URLRequest.makeHTTPBinRequest())
  511. request.responseJSON { resp in
  512. response1 = resp
  513. expect.fulfill()
  514. request.responseJSON { resp in
  515. response2 = resp
  516. expect.fulfill()
  517. }
  518. }
  519. waitForExpectations(timeout: timeout, handler: nil)
  520. // Then
  521. XCTAssertNotNil(response1?.value)
  522. XCTAssertEqual(response2?.error?.asAFError?.isResponseSerializerAddedAfterRequestFinished, true)
  523. }
  524. }
  525. // MARK: -
  526. class RequestDescriptionTestCase: BaseTestCase {
  527. func testRequestDescription() {
  528. // Given
  529. let urlString = "https://httpbin.org/get"
  530. let manager = Session(startRequestsImmediately: false)
  531. let request = manager.request(urlString)
  532. let expectation = self.expectation(description: "Request description should update: \(urlString)")
  533. var response: HTTPURLResponse?
  534. // When
  535. request.response { resp in
  536. response = resp.response
  537. expectation.fulfill()
  538. }.resume()
  539. waitForExpectations(timeout: timeout, handler: nil)
  540. // Then
  541. XCTAssertEqual(request.description, "GET https://httpbin.org/get (\(response?.statusCode ?? -1))")
  542. }
  543. }
  544. // MARK: -
  545. class RequestDebugDescriptionTestCase: BaseTestCase {
  546. // MARK: Properties
  547. let manager: Session = {
  548. let manager = Session()
  549. return manager
  550. }()
  551. let managerWithAcceptLanguageHeader: Session = {
  552. var headers = HTTPHeaders.default
  553. headers["Accept-Language"] = "en-US"
  554. let configuration = URLSessionConfiguration.af.default
  555. configuration.headers = headers
  556. let manager = Session(configuration: configuration)
  557. return manager
  558. }()
  559. let managerWithContentTypeHeader: Session = {
  560. var headers = HTTPHeaders.default
  561. headers["Content-Type"] = "application/json"
  562. let configuration = URLSessionConfiguration.af.default
  563. configuration.headers = headers
  564. let manager = Session(configuration: configuration)
  565. return manager
  566. }()
  567. func managerWithCookie(_ cookie: HTTPCookie) -> Session {
  568. let configuration = URLSessionConfiguration.af.default
  569. configuration.httpCookieStorage?.setCookie(cookie)
  570. return Session(configuration: configuration)
  571. }
  572. let managerDisallowingCookies: Session = {
  573. let configuration = URLSessionConfiguration.af.default
  574. configuration.httpShouldSetCookies = false
  575. let manager = Session(configuration: configuration)
  576. return manager
  577. }()
  578. // MARK: Tests
  579. func testGETRequestDebugDescription() {
  580. // Given
  581. let urlString = "https://httpbin.org/get"
  582. let expectation = self.expectation(description: "request should complete")
  583. // When
  584. let request = manager.request(urlString).response { _ in expectation.fulfill() }
  585. waitForExpectations(timeout: timeout, handler: nil)
  586. let components = cURLCommandComponents(for: request)
  587. // Then
  588. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  589. XCTAssertTrue(components.contains("-X"))
  590. XCTAssertEqual(components.last, "\"\(urlString)\"")
  591. }
  592. func testGETRequestWithJSONHeaderDebugDescription() {
  593. // Given
  594. let urlString = "https://httpbin.org/get"
  595. let expectation = self.expectation(description: "request should complete")
  596. // When
  597. let headers: HTTPHeaders = [ "X-Custom-Header": "{\"key\": \"value\"}" ]
  598. let request = manager.request(urlString, headers: headers).response { _ in expectation.fulfill() }
  599. waitForExpectations(timeout: timeout, handler: nil)
  600. // Then
  601. XCTAssertNotNil(request.debugDescription.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\""))
  602. }
  603. func testGETRequestWithDuplicateHeadersDebugDescription() {
  604. // Given
  605. let urlString = "https://httpbin.org/get"
  606. let expectation = self.expectation(description: "request should complete")
  607. // When
  608. let headers: HTTPHeaders = [ "Accept-Language": "en-GB" ]
  609. let request = managerWithAcceptLanguageHeader.request(urlString, headers: headers).response { _ in expectation.fulfill() }
  610. waitForExpectations(timeout: timeout, handler: nil)
  611. let components = cURLCommandComponents(for: request)
  612. // Then
  613. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  614. XCTAssertTrue(components.contains("-X"))
  615. XCTAssertEqual(components.last, "\"\(urlString)\"")
  616. let tokens = request.debugDescription.components(separatedBy: "Accept-Language:")
  617. XCTAssertTrue(tokens.count == 2, "command should contain a single Accept-Language header")
  618. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Accept-Language: en-GB\""))
  619. }
  620. func testPOSTRequestDebugDescription() {
  621. // Given
  622. let urlString = "https://httpbin.org/post"
  623. let expectation = self.expectation(description: "request should complete")
  624. // When
  625. let request = manager.request(urlString, method: .post).response { _ in expectation.fulfill() }
  626. waitForExpectations(timeout: timeout, handler: nil)
  627. let components = cURLCommandComponents(for: request)
  628. // Then
  629. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  630. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  631. XCTAssertEqual(components.last, "\"\(urlString)\"")
  632. }
  633. func testPOSTRequestWithJSONParametersDebugDescription() {
  634. // Given
  635. let urlString = "https://httpbin.org/post"
  636. let expectation = self.expectation(description: "request should complete")
  637. let parameters = [
  638. "foo": "bar",
  639. "fo\"o": "b\"ar",
  640. "f'oo": "ba'r"
  641. ]
  642. // When
  643. let request = manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).response {
  644. _ in expectation.fulfill()
  645. }
  646. waitForExpectations(timeout: timeout, handler: nil)
  647. let components = cURLCommandComponents(for: request)
  648. // Then
  649. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  650. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  651. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Content-Type: application/json\""))
  652. XCTAssertNotNil(request.debugDescription.range(of: "-d \"{"))
  653. XCTAssertNotNil(request.debugDescription.range(of: "\\\"f'oo\\\":\\\"ba'r\\\""))
  654. XCTAssertNotNil(request.debugDescription.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\""))
  655. XCTAssertNotNil(request.debugDescription.range(of: "\\\"foo\\\":\\\"bar\\"))
  656. XCTAssertEqual(components.last, "\"\(urlString)\"")
  657. }
  658. func testPOSTRequestWithCookieDebugDescription() {
  659. // Given
  660. let urlString = "https://httpbin.org/post"
  661. let properties = [
  662. HTTPCookiePropertyKey.domain: "httpbin.org",
  663. HTTPCookiePropertyKey.path: "/post",
  664. HTTPCookiePropertyKey.name: "foo",
  665. HTTPCookiePropertyKey.value: "bar",
  666. ]
  667. let cookie = HTTPCookie(properties: properties)!
  668. let cookieManager = managerWithCookie(cookie)
  669. let expectation = self.expectation(description: "request should complete")
  670. // When
  671. let request = cookieManager.request(urlString, method: .post).response { _ in expectation.fulfill() }
  672. waitForExpectations(timeout: timeout, handler: nil)
  673. let components = cURLCommandComponents(for: request)
  674. // Then
  675. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  676. XCTAssertEqual(components[3..<5], ["-X", "POST"])
  677. XCTAssertEqual(components.last, "\"\(urlString)\"")
  678. XCTAssertEqual(components[5..<6], ["-b"])
  679. }
  680. func testPOSTRequestWithCookiesDisabledDebugDescription() {
  681. // Given
  682. let urlString = "https://httpbin.org/post"
  683. let properties = [
  684. HTTPCookiePropertyKey.domain: "httpbin.org",
  685. HTTPCookiePropertyKey.path: "/post",
  686. HTTPCookiePropertyKey.name: "foo",
  687. HTTPCookiePropertyKey.value: "bar",
  688. ]
  689. let cookie = HTTPCookie(properties: properties)!
  690. managerDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie)
  691. // When
  692. let request = managerDisallowingCookies.request(urlString, method: .post)
  693. let components = cURLCommandComponents(for: request)
  694. // Then
  695. let cookieComponents = components.filter { $0 == "-b" }
  696. XCTAssertTrue(cookieComponents.isEmpty)
  697. }
  698. func testMultipartFormDataRequestWithDuplicateHeadersDebugDescription() {
  699. // Given
  700. let urlString = "https://httpbin.org/post"
  701. let japaneseData = Data("日本語".utf8)
  702. let expectation = self.expectation(description: "multipart form data encoding should succeed")
  703. // When
  704. let request = managerWithContentTypeHeader.upload(multipartFormData: { (data) in
  705. data.append(japaneseData, withName: "japanese")
  706. }, to: urlString)
  707. .response { _ in
  708. expectation.fulfill()
  709. }
  710. waitForExpectations(timeout: timeout, handler: nil)
  711. let components = cURLCommandComponents(for: request)
  712. // Then
  713. XCTAssertEqual(components[0..<3], ["$", "curl", "-v"])
  714. XCTAssertTrue(components.contains("-X"))
  715. XCTAssertEqual(components.last, "\"\(urlString)\"")
  716. let tokens = request.debugDescription.components(separatedBy: "Content-Type:")
  717. XCTAssertTrue(tokens.count == 2, "command should contain a single Content-Type header")
  718. XCTAssertNotNil(request.debugDescription.range(of: "-H \"Content-Type: multipart/form-data;"))
  719. }
  720. func testThatRequestWithInvalidURLDebugDescription() {
  721. // Given
  722. let urlString = "invalid_url"
  723. let expectation = self.expectation(description: "request should complete")
  724. // When
  725. let request = manager.request(urlString).response { _ in expectation.fulfill() }
  726. waitForExpectations(timeout: timeout, handler: nil)
  727. let debugDescription = request.debugDescription
  728. // Then
  729. XCTAssertNotNil(debugDescription, "debugDescription should not crash")
  730. }
  731. // MARK: Test Helper Methods
  732. private func cURLCommandComponents(for request: Request) -> [String] {
  733. let whitespaceCharacterSet = CharacterSet.whitespacesAndNewlines
  734. return request.debugDescription
  735. .components(separatedBy: whitespaceCharacterSet)
  736. .filter { $0 != "" && $0 != "\\" }
  737. }
  738. }