RequestTests.swift 46 KB

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