RequestTests.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. //
  2. // RequestTests.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Alamofire
  25. import Foundation
  26. import XCTest
  27. class RequestInitializationTestCase: BaseTestCase {
  28. func testRequestClassMethodWithMethodAndURL() {
  29. // Given
  30. let URLString = "https://httpbin.org/"
  31. // When
  32. let request = Alamofire.request(.GET, URLString)
  33. // Then
  34. XCTAssertNotNil(request.request, "request URL request should not be nil")
  35. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
  36. XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  37. XCTAssertNil(request.response, "request response should be nil")
  38. }
  39. func testRequestClassMethodWithMethodAndURLAndParameters() {
  40. // Given
  41. let URLString = "https://httpbin.org/get"
  42. // When
  43. let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
  44. // Then
  45. XCTAssertNotNil(request.request, "request URL request should not be nil")
  46. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
  47. XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  48. XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect")
  49. XCTAssertNil(request.response, "request response should be nil")
  50. }
  51. func testRequestClassMethodWithMethodURLParametersAndHeaders() {
  52. // Given
  53. let URLString = "https://httpbin.org/get"
  54. let headers = ["Authorization": "123456"]
  55. // When
  56. let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"], headers: headers)
  57. // Then
  58. XCTAssertNotNil(request.request, "request should not be nil")
  59. XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
  60. XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
  61. XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect")
  62. let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
  63. XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
  64. XCTAssertNil(request.response, "response should be nil")
  65. }
  66. }
  67. // MARK: -
  68. class RequestResponseTestCase: BaseTestCase {
  69. func testRequestResponse() {
  70. // Given
  71. let URLString = "https://httpbin.org/get"
  72. let expectation = expectationWithDescription("GET request should succeed: \(URLString)")
  73. var request: NSURLRequest?
  74. var response: NSHTTPURLResponse?
  75. var data: NSData?
  76. var error: NSError?
  77. // When
  78. Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
  79. .response { responseRequest, responseResponse, responseData, responseError in
  80. request = responseRequest
  81. response = responseResponse
  82. data = responseData
  83. error = responseError
  84. expectation.fulfill()
  85. }
  86. waitForExpectationsWithTimeout(timeout, handler: nil)
  87. // Then
  88. XCTAssertNotNil(request, "request should not be nil")
  89. XCTAssertNotNil(response, "response should not be nil")
  90. XCTAssertNotNil(data, "data should not be nil")
  91. XCTAssertNil(error, "error should be nil")
  92. }
  93. func testRequestResponseWithProgress() {
  94. // Given
  95. let randomBytes = 4 * 1024 * 1024
  96. let URLString = "https://httpbin.org/bytes/\(randomBytes)"
  97. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  98. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  99. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  100. var responseRequest: NSURLRequest?
  101. var responseResponse: NSHTTPURLResponse?
  102. var responseData: NSData?
  103. var responseError: ErrorType?
  104. // When
  105. let request = Alamofire.request(.GET, URLString)
  106. request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  107. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  108. byteValues.append(bytes)
  109. let progress = (
  110. completedUnitCount: request.progress.completedUnitCount,
  111. totalUnitCount: request.progress.totalUnitCount
  112. )
  113. progressValues.append(progress)
  114. }
  115. request.response { request, response, data, error in
  116. responseRequest = request
  117. responseResponse = response
  118. responseData = data
  119. responseError = error
  120. expectation.fulfill()
  121. }
  122. waitForExpectationsWithTimeout(timeout, handler: nil)
  123. // Then
  124. XCTAssertNotNil(responseRequest, "response request should not be nil")
  125. XCTAssertNotNil(responseResponse, "response response should not be nil")
  126. XCTAssertNotNil(responseData, "response data should not be nil")
  127. XCTAssertNil(responseError, "response error should be nil")
  128. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  129. if byteValues.count == progressValues.count {
  130. for index in 0..<byteValues.count {
  131. let byteValue = byteValues[index]
  132. let progressValue = progressValues[index]
  133. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  134. XCTAssertEqual(
  135. byteValue.totalBytes,
  136. progressValue.completedUnitCount,
  137. "total bytes should be equal to completed unit count"
  138. )
  139. XCTAssertEqual(
  140. byteValue.totalBytesExpected,
  141. progressValue.totalUnitCount,
  142. "total bytes expected should be equal to total unit count"
  143. )
  144. }
  145. }
  146. if let
  147. lastByteValue = byteValues.last,
  148. lastProgressValue = progressValues.last
  149. {
  150. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  151. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  152. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  153. XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
  154. } else {
  155. XCTFail("last item in bytesValues and progressValues should not be nil")
  156. }
  157. }
  158. func testRequestResponseWithStream() {
  159. // Given
  160. let randomBytes = 4 * 1024 * 1024
  161. let URLString = "https://httpbin.org/bytes/\(randomBytes)"
  162. let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
  163. var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
  164. var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
  165. var accumulatedData = [NSData]()
  166. var responseRequest: NSURLRequest?
  167. var responseResponse: NSHTTPURLResponse?
  168. var responseData: NSData?
  169. var responseError: ErrorType?
  170. // When
  171. let request = Alamofire.request(.GET, URLString)
  172. request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
  173. let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
  174. byteValues.append(bytes)
  175. let progress = (
  176. completedUnitCount: request.progress.completedUnitCount,
  177. totalUnitCount: request.progress.totalUnitCount
  178. )
  179. progressValues.append(progress)
  180. }
  181. request.stream { accumulatedData.append($0) }
  182. request.response { request, response, data, error in
  183. responseRequest = request
  184. responseResponse = response
  185. responseData = data
  186. responseError = error
  187. expectation.fulfill()
  188. }
  189. waitForExpectationsWithTimeout(timeout, handler: nil)
  190. // Then
  191. XCTAssertNotNil(responseRequest, "response request should not be nil")
  192. XCTAssertNotNil(responseResponse, "response response should not be nil")
  193. XCTAssertNil(responseData, "response data should be nil")
  194. XCTAssertNil(responseError, "response error should be nil")
  195. XCTAssertGreaterThanOrEqual(accumulatedData.count, 1, "accumulated data should have one or more parts")
  196. XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
  197. if byteValues.count == progressValues.count {
  198. for index in 0..<byteValues.count {
  199. let byteValue = byteValues[index]
  200. let progressValue = progressValues[index]
  201. XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
  202. XCTAssertEqual(
  203. byteValue.totalBytes,
  204. progressValue.completedUnitCount,
  205. "total bytes should be equal to completed unit count"
  206. )
  207. XCTAssertEqual(
  208. byteValue.totalBytesExpected,
  209. progressValue.totalUnitCount,
  210. "total bytes expected should be equal to total unit count"
  211. )
  212. }
  213. }
  214. if let
  215. lastByteValue = byteValues.last,
  216. lastProgressValue = progressValues.last
  217. {
  218. let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
  219. let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
  220. XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
  221. XCTAssertEqual(
  222. progressValueFractionalCompletion,
  223. 1.0,
  224. "progress value fractional completion should equal 1.0"
  225. )
  226. XCTAssertEqual(
  227. accumulatedData.reduce(Int64(0)) { $0 + $1.length },
  228. lastByteValue.totalBytes,
  229. "accumulated data length should match byte count"
  230. )
  231. } else {
  232. XCTFail("last item in bytesValues and progressValues should not be nil")
  233. }
  234. }
  235. func testPOSTRequestWithUnicodeParameters() {
  236. // Given
  237. let URLString = "https://httpbin.org/post"
  238. let parameters = [
  239. "french": "français",
  240. "japanese": "日本語",
  241. "arabic": "العربية",
  242. "emoji": "😃"
  243. ]
  244. let expectation = expectationWithDescription("request should succeed")
  245. var response: Response<AnyObject, NSError>?
  246. // When
  247. Alamofire.request(.POST, URLString, parameters: parameters)
  248. .responseJSON { closureResponse in
  249. response = closureResponse
  250. expectation.fulfill()
  251. }
  252. waitForExpectationsWithTimeout(timeout, handler: nil)
  253. // Then
  254. if let response = response {
  255. XCTAssertNotNil(response.request, "request should not be nil")
  256. XCTAssertNotNil(response.response, "response should not be nil")
  257. XCTAssertNotNil(response.data, "data should not be nil")
  258. if let
  259. JSON = response.result.value as? [String: AnyObject],
  260. form = JSON["form"] as? [String: String]
  261. {
  262. XCTAssertEqual(form["french"], parameters["french"], "french parameter value should match form value")
  263. XCTAssertEqual(form["japanese"], parameters["japanese"], "japanese parameter value should match form value")
  264. XCTAssertEqual(form["arabic"], parameters["arabic"], "arabic parameter value should match form value")
  265. XCTAssertEqual(form["emoji"], parameters["emoji"], "emoji parameter value should match form value")
  266. } else {
  267. XCTFail("form parameter in JSON should not be nil")
  268. }
  269. } else {
  270. XCTFail("response should not be nil")
  271. }
  272. }
  273. func testPOSTRequestWithBase64EncodedImages() {
  274. // Given
  275. let URLString = "https://httpbin.org/post"
  276. let pngBase64EncodedString: String = {
  277. let URL = URLForResource("unicorn", withExtension: "png")
  278. let data = NSData(contentsOfURL: URL)!
  279. return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  280. }()
  281. let jpegBase64EncodedString: String = {
  282. let URL = URLForResource("rainbow", withExtension: "jpg")
  283. let data = NSData(contentsOfURL: URL)!
  284. return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  285. }()
  286. let parameters = [
  287. "email": "user@alamofire.org",
  288. "png_image": pngBase64EncodedString,
  289. "jpeg_image": jpegBase64EncodedString
  290. ]
  291. let expectation = expectationWithDescription("request should succeed")
  292. var response: Response<AnyObject, NSError>?
  293. // When
  294. Alamofire.request(.POST, URLString, parameters: parameters)
  295. .responseJSON { closureResponse in
  296. response = closureResponse
  297. expectation.fulfill()
  298. }
  299. waitForExpectationsWithTimeout(timeout, handler: nil)
  300. // Then
  301. if let response = response {
  302. XCTAssertNotNil(response.request, "request should not be nil")
  303. XCTAssertNotNil(response.response, "response should not be nil")
  304. XCTAssertNotNil(response.data, "data should not be nil")
  305. XCTAssertTrue(response.result.isSuccess, "result should be success")
  306. if let
  307. JSON = response.result.value as? [String: AnyObject],
  308. form = JSON["form"] as? [String: String]
  309. {
  310. XCTAssertEqual(form["email"], parameters["email"], "email parameter value should match form value")
  311. XCTAssertEqual(form["png_image"], parameters["png_image"], "png_image parameter value should match form value")
  312. XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"], "jpeg_image parameter value should match form value")
  313. } else {
  314. XCTFail("form parameter in JSON should not be nil")
  315. }
  316. } else {
  317. XCTFail("response should not be nil")
  318. }
  319. }
  320. }
  321. // MARK: -
  322. extension Request {
  323. private func preValidate(operation: Void -> Void) -> Self {
  324. delegate.queue.addOperationWithBlock {
  325. operation()
  326. }
  327. return self
  328. }
  329. private func postValidate(operation: Void -> Void) -> Self {
  330. delegate.queue.addOperationWithBlock {
  331. operation()
  332. }
  333. return self
  334. }
  335. }
  336. // MARK: -
  337. class RequestExtensionTestCase: BaseTestCase {
  338. func testThatRequestExtensionHasAccessToTaskDelegateQueue() {
  339. // Given
  340. let URLString = "https://httpbin.org/get"
  341. let expectation = expectationWithDescription("GET request should succeed: \(URLString)")
  342. var responses: [String] = []
  343. // When
  344. Alamofire.request(.GET, URLString)
  345. .preValidate {
  346. responses.append("preValidate")
  347. }
  348. .validate()
  349. .postValidate {
  350. responses.append("postValidate")
  351. }
  352. .response { _, _, _, _ in
  353. responses.append("response")
  354. expectation.fulfill()
  355. }
  356. waitForExpectationsWithTimeout(timeout, handler: nil)
  357. // Then
  358. if responses.count == 3 {
  359. XCTAssertEqual(responses[0], "preValidate", "response at index 0 should be preValidate")
  360. XCTAssertEqual(responses[1], "postValidate", "response at index 1 should be postValidate")
  361. XCTAssertEqual(responses[2], "response", "response at index 2 should be response")
  362. } else {
  363. XCTFail("responses count should be equal to 3")
  364. }
  365. }
  366. }
  367. // MARK: -
  368. class RequestDescriptionTestCase: BaseTestCase {
  369. func testRequestDescription() {
  370. // Given
  371. let URLString = "https://httpbin.org/get"
  372. let request = Alamofire.request(.GET, URLString)
  373. let initialRequestDescription = request.description
  374. let expectation = expectationWithDescription("Request description should update: \(URLString)")
  375. var finalRequestDescription: String?
  376. var response: NSHTTPURLResponse?
  377. // When
  378. request.response { _, responseResponse, _, _ in
  379. finalRequestDescription = request.description
  380. response = responseResponse
  381. expectation.fulfill()
  382. }
  383. waitForExpectationsWithTimeout(timeout, handler: nil)
  384. // Then
  385. XCTAssertEqual(initialRequestDescription, "GET https://httpbin.org/get", "incorrect request description")
  386. XCTAssertEqual(
  387. finalRequestDescription ?? "",
  388. "GET https://httpbin.org/get (\(response?.statusCode ?? -1))",
  389. "incorrect request description"
  390. )
  391. }
  392. }
  393. // MARK: -
  394. class RequestDebugDescriptionTestCase: BaseTestCase {
  395. // MARK: Properties
  396. let manager: Manager = {
  397. let manager = Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
  398. manager.startRequestsImmediately = false
  399. return manager
  400. }()
  401. let managerWithAcceptLanguageHeader: Manager = {
  402. var headers = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
  403. headers["Accept-Language"] = "en-US"
  404. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  405. configuration.HTTPAdditionalHeaders = headers
  406. let manager = Manager(configuration: configuration)
  407. manager.startRequestsImmediately = false
  408. return manager
  409. }()
  410. let managerDisallowingCookies: Manager = {
  411. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  412. configuration.HTTPShouldSetCookies = false
  413. let manager = Manager(configuration: configuration)
  414. manager.startRequestsImmediately = false
  415. return manager
  416. }()
  417. // MARK: Tests
  418. func testGETRequestDebugDescription() {
  419. // Given
  420. let URLString = "https://httpbin.org/get"
  421. // When
  422. let request = manager.request(.GET, URLString)
  423. let components = cURLCommandComponents(request)
  424. // Then
  425. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  426. XCTAssertFalse(components.contains("-X"), "command should not contain explicit -X flag")
  427. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  428. }
  429. func testGETRequestWithDuplicateHeadersDebugDescription() {
  430. // Given
  431. let URLString = "https://httpbin.org/get"
  432. // When
  433. let headers = [ "Accept-Language": "en-GB" ]
  434. let request = managerWithAcceptLanguageHeader.request(.GET, URLString, headers: headers)
  435. let components = cURLCommandComponents(request)
  436. // Then
  437. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  438. XCTAssertFalse(components.contains("-X"), "command should not contain explicit -X flag")
  439. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  440. let tokens = request.debugDescription.componentsSeparatedByString("Accept-Language:")
  441. XCTAssertTrue(tokens.count == 2, "command should contain a single Accept-Language header")
  442. XCTAssertTrue(
  443. request.debugDescription.rangeOfString("-H \"Accept-Language: en-GB\"") != nil,
  444. "command should Accept-Language set to 'en-GB'"
  445. )
  446. }
  447. func testPOSTRequestDebugDescription() {
  448. // Given
  449. let URLString = "https://httpbin.org/post"
  450. // When
  451. let request = manager.request(.POST, URLString)
  452. let components = cURLCommandComponents(request)
  453. // Then
  454. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  455. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  456. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  457. }
  458. func testPOSTRequestWithJSONParametersDebugDescription() {
  459. // Given
  460. let URLString = "https://httpbin.org/post"
  461. let parameters = [
  462. "foo": "bar",
  463. "fo\"o": "b\"ar",
  464. "f'oo": "ba'r"
  465. ]
  466. // When
  467. let request = manager.request(.POST, URLString, parameters: parameters, encoding: .JSON)
  468. let components = cURLCommandComponents(request)
  469. // Then
  470. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  471. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  472. XCTAssertTrue(
  473. request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil,
  474. "command should contain 'application/json' Content-Type"
  475. )
  476. let expectedBody = "-d \"{\\\"f'oo\\\":\\\"ba'r\\\",\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\",\\\"foo\\\":\\\"bar\\\"}\""
  477. XCTAssertTrue(
  478. request.debugDescription.rangeOfString(expectedBody) != nil,
  479. "command data should contain JSON encoded parameters"
  480. )
  481. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  482. }
  483. func testPOSTRequestWithCookieDebugDescription() {
  484. // Given
  485. let URLString = "https://httpbin.org/post"
  486. let properties = [
  487. NSHTTPCookieDomain: "httpbin.org",
  488. NSHTTPCookiePath: "/post",
  489. NSHTTPCookieName: "foo",
  490. NSHTTPCookieValue: "bar",
  491. ]
  492. let cookie = NSHTTPCookie(properties: properties)!
  493. manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
  494. // When
  495. let request = manager.request(.POST, URLString)
  496. let components = cURLCommandComponents(request)
  497. // Then
  498. XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
  499. XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
  500. XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
  501. XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag")
  502. }
  503. func testPOSTRequestWithCookiesDisabledDebugDescription() {
  504. // Given
  505. let URLString = "https://httpbin.org/post"
  506. let properties = [
  507. NSHTTPCookieDomain: "httpbin.org",
  508. NSHTTPCookiePath: "/post",
  509. NSHTTPCookieName: "foo",
  510. NSHTTPCookieValue: "bar",
  511. ]
  512. let cookie = NSHTTPCookie(properties: properties)!
  513. managerDisallowingCookies.session.configuration.HTTPCookieStorage?.setCookie(cookie)
  514. // When
  515. let request = managerDisallowingCookies.request(.POST, URLString)
  516. let components = cURLCommandComponents(request)
  517. // Then
  518. let cookieComponents = components.filter { $0 == "-b" }
  519. XCTAssertTrue(cookieComponents.isEmpty, "command should not contain -b flag")
  520. }
  521. func testThatRequestWithInvalidURLDebugDescription() {
  522. // Given
  523. let URLString = "invalid_url"
  524. // When
  525. let request = manager.request(.GET, URLString)
  526. let debugDescription = request.debugDescription
  527. // Then
  528. XCTAssertNotNil(debugDescription, "debugDescription should not crash")
  529. }
  530. // MARK: Test Helper Methods
  531. private func cURLCommandComponents(request: Request) -> [String] {
  532. let whitespaceCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
  533. return request.debugDescription.componentsSeparatedByCharactersInSet(whitespaceCharacterSet)
  534. .filter { $0 != "" && $0 != "\\" }
  535. }
  536. }