RequestTests.swift 46 KB

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