ValidationTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //
  2. // ValidationTests.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. @testable import Alamofire
  25. import Foundation
  26. import XCTest
  27. class StatusCodeValidationTestCase: BaseTestCase {
  28. func testThatValidationForRequestWithAcceptableStatusCodeResponseSucceeds() {
  29. // Given
  30. let urlString = "https://httpbin.org/status/200"
  31. let expectation = self.expectation(description: "request should return 200 status code")
  32. var error: NSError?
  33. // When
  34. Alamofire.request(urlString, withMethod: .get)
  35. .validate(statusCode: 200..<300)
  36. .response { _, _, _, responseError in
  37. error = responseError
  38. expectation.fulfill()
  39. }
  40. waitForExpectations(timeout: timeout, handler: nil)
  41. // Then
  42. XCTAssertNil(error)
  43. }
  44. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  45. // Given
  46. let urlString = "https://httpbin.org/status/404"
  47. let expectation = self.expectation(description: "request should return 404 status code")
  48. var error: NSError?
  49. // When
  50. Alamofire.request(urlString, withMethod: .get)
  51. .validate(statusCode: [200])
  52. .response { _, _, _, responseError in
  53. error = responseError
  54. expectation.fulfill()
  55. }
  56. waitForExpectations(timeout: timeout, handler: nil)
  57. // Then
  58. XCTAssertNotNil(error)
  59. if let error = error {
  60. XCTAssertEqual(error.domain, ErrorDomain)
  61. XCTAssertEqual(error.code, ErrorCode.statusCodeValidationFailed.rawValue)
  62. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.StatusCode] as? Int, 404)
  63. } else {
  64. XCTFail("error should not be nil")
  65. }
  66. }
  67. func testThatValidationForRequestWithNoAcceptableStatusCodesFails() {
  68. // Given
  69. let urlString = "https://httpbin.org/status/201"
  70. let expectation = self.expectation(description: "request should return 201 status code")
  71. var error: NSError?
  72. // When
  73. Alamofire.request(urlString, withMethod: .get)
  74. .validate(statusCode: [])
  75. .response { _, _, _, responseError in
  76. error = responseError
  77. expectation.fulfill()
  78. }
  79. waitForExpectations(timeout: timeout, handler: nil)
  80. // Then
  81. XCTAssertNotNil(error)
  82. if let error = error {
  83. XCTAssertEqual(error.domain, ErrorDomain)
  84. XCTAssertEqual(error.code, ErrorCode.statusCodeValidationFailed.rawValue)
  85. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.StatusCode] as? Int, 201)
  86. } else {
  87. XCTFail("error should not be nil")
  88. }
  89. }
  90. }
  91. // MARK: -
  92. class ContentTypeValidationTestCase: BaseTestCase {
  93. func testThatValidationForRequestWithAcceptableContentTypeResponseSucceeds() {
  94. // Given
  95. let urlString = "https://httpbin.org/ip"
  96. let expectation = self.expectation(description: "request should succeed and return ip")
  97. var error: NSError?
  98. // When
  99. Alamofire.request(urlString, withMethod: .get)
  100. .validate(contentType: ["application/json"])
  101. .validate(contentType: ["application/json;charset=utf8"])
  102. .validate(contentType: ["application/json;q=0.8;charset=utf8"])
  103. .response { _, _, _, responseError in
  104. error = responseError
  105. expectation.fulfill()
  106. }
  107. waitForExpectations(timeout: timeout, handler: nil)
  108. // Then
  109. XCTAssertNil(error)
  110. }
  111. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  112. // Given
  113. let urlString = "https://httpbin.org/ip"
  114. let expectation = self.expectation(description: "request should succeed and return ip")
  115. var error: NSError?
  116. // When
  117. Alamofire.request(urlString, withMethod: .get)
  118. .validate(contentType: ["*/*"])
  119. .validate(contentType: ["application/*"])
  120. .validate(contentType: ["*/json"])
  121. .response { _, _, _, responseError in
  122. error = responseError
  123. expectation.fulfill()
  124. }
  125. waitForExpectations(timeout: timeout, handler: nil)
  126. // Then
  127. XCTAssertNil(error)
  128. }
  129. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  130. // Given
  131. let urlString = "https://httpbin.org/xml"
  132. let expectation = self.expectation(description: "request should succeed and return xml")
  133. var error: NSError?
  134. // When
  135. Alamofire.request(urlString, withMethod: .get)
  136. .validate(contentType: ["application/octet-stream"])
  137. .response { _, _, _, responseError in
  138. error = responseError
  139. expectation.fulfill()
  140. }
  141. waitForExpectations(timeout: timeout, handler: nil)
  142. // Then
  143. XCTAssertNotNil(error)
  144. if let error = error {
  145. XCTAssertEqual(error.domain, ErrorDomain)
  146. XCTAssertEqual(error.code, ErrorCode.contentTypeValidationFailed.rawValue)
  147. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.ContentType] as? String, "application/xml")
  148. } else {
  149. XCTFail("error should not be nil")
  150. }
  151. }
  152. func testThatValidationForRequestWithNoAcceptableContentTypeResponseFails() {
  153. // Given
  154. let urlString = "https://httpbin.org/xml"
  155. let expectation = self.expectation(description: "request should succeed and return xml")
  156. var error: NSError?
  157. // When
  158. Alamofire.request(urlString, withMethod: .get)
  159. .validate(contentType: [])
  160. .response { _, _, _, responseError in
  161. error = responseError
  162. expectation.fulfill()
  163. }
  164. waitForExpectations(timeout: timeout, handler: nil)
  165. // Then
  166. XCTAssertNotNil(error, "error should not be nil")
  167. if let error = error {
  168. XCTAssertEqual(error.domain, ErrorDomain)
  169. XCTAssertEqual(error.code, ErrorCode.contentTypeValidationFailed.rawValue)
  170. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.ContentType] as? String, "application/xml")
  171. } else {
  172. XCTFail("error should not be nil")
  173. }
  174. }
  175. func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() {
  176. // Given
  177. let urlString = "https://httpbin.org/status/204"
  178. let expectation = self.expectation(description: "request should succeed and return no data")
  179. var error: NSError?
  180. // When
  181. Alamofire.request(urlString, withMethod: .get)
  182. .validate(contentType: [])
  183. .response { _, response, data, responseError in
  184. error = responseError
  185. expectation.fulfill()
  186. }
  187. waitForExpectations(timeout: timeout, handler: nil)
  188. // Then
  189. XCTAssertNil(error)
  190. }
  191. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceedsWhenResponseIsNil() {
  192. // Given
  193. class MockManager: SessionManager {
  194. override func request(_ urlRequest: URLRequestConvertible) -> Request {
  195. var dataTask: URLSessionDataTask!
  196. queue.sync {
  197. dataTask = self.session.dataTask(with: urlRequest.urlRequest)
  198. }
  199. let request = MockRequest(session: session, task: dataTask)
  200. delegate[request.delegate.task] = request
  201. if startRequestsImmediately {
  202. request.resume()
  203. }
  204. return request
  205. }
  206. }
  207. class MockRequest: Request {
  208. override var response: HTTPURLResponse? {
  209. return MockHTTPURLResponse(
  210. url: URL(string: request!.urlString)!,
  211. statusCode: 204,
  212. httpVersion: "HTTP/1.1",
  213. headerFields: nil
  214. )
  215. }
  216. }
  217. class MockHTTPURLResponse: HTTPURLResponse {
  218. override var mimeType: String? { return nil }
  219. }
  220. let manager: SessionManager = {
  221. let configuration: URLSessionConfiguration = {
  222. let configuration = URLSessionConfiguration.ephemeral
  223. configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
  224. return configuration
  225. }()
  226. return MockManager(configuration: configuration)
  227. }()
  228. let urlString = "https://httpbin.org/delete"
  229. let expectation = self.expectation(description: "request should be stubbed and return 204 status code")
  230. var response: HTTPURLResponse?
  231. var data: Data?
  232. var error: NSError?
  233. // When
  234. manager.request(urlString, withMethod: .delete)
  235. .validate(contentType: ["*/*"])
  236. .response { _, responseResponse, responseData, responseError in
  237. response = responseResponse
  238. data = responseData
  239. error = responseError
  240. expectation.fulfill()
  241. }
  242. waitForExpectations(timeout: timeout, handler: nil)
  243. // Then
  244. XCTAssertNotNil(response)
  245. XCTAssertNotNil(data)
  246. XCTAssertNil(error)
  247. if let response = response {
  248. XCTAssertEqual(response.statusCode, 204)
  249. XCTAssertNil(response.mimeType)
  250. }
  251. }
  252. }
  253. // MARK: -
  254. class MultipleValidationTestCase: BaseTestCase {
  255. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  256. // Given
  257. let urlString = "https://httpbin.org/ip"
  258. let expectation = self.expectation(description: "request should succeed and return ip")
  259. var error: NSError?
  260. // When
  261. Alamofire.request(urlString, withMethod: .get)
  262. .validate(statusCode: 200..<300)
  263. .validate(contentType: ["application/json"])
  264. .response { _, _, _, responseError in
  265. error = responseError
  266. expectation.fulfill()
  267. }
  268. waitForExpectations(timeout: timeout, handler: nil)
  269. // Then
  270. XCTAssertNil(error)
  271. }
  272. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() {
  273. // Given
  274. let urlString = "https://httpbin.org/xml"
  275. let expectation = self.expectation(description: "request should succeed and return xml")
  276. var error: NSError?
  277. // When
  278. Alamofire.request(urlString, withMethod: .get)
  279. .validate(statusCode: 400..<600)
  280. .validate(contentType: ["application/octet-stream"])
  281. .response { _, _, _, responseError in
  282. error = responseError
  283. expectation.fulfill()
  284. }
  285. waitForExpectations(timeout: timeout, handler: nil)
  286. // Then
  287. XCTAssertNotNil(error)
  288. if let error = error {
  289. XCTAssertEqual(error.domain, ErrorDomain)
  290. XCTAssertEqual(error.code, ErrorCode.statusCodeValidationFailed.rawValue)
  291. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.StatusCode] as? Int, 200)
  292. } else {
  293. XCTFail("error should not be nil")
  294. }
  295. }
  296. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() {
  297. // Given
  298. let urlString = "https://httpbin.org/xml"
  299. let expectation = self.expectation(description: "request should succeed and return xml")
  300. var error: NSError?
  301. // When
  302. Alamofire.request(urlString, withMethod: .get)
  303. .validate(contentType: ["application/octet-stream"])
  304. .validate(statusCode: 400..<600)
  305. .response { _, _, _, responseError in
  306. error = responseError
  307. expectation.fulfill()
  308. }
  309. waitForExpectations(timeout: timeout, handler: nil)
  310. // Then
  311. XCTAssertNotNil(error)
  312. if let error = error {
  313. XCTAssertEqual(error.domain, ErrorDomain)
  314. XCTAssertEqual(error.code, ErrorCode.contentTypeValidationFailed.rawValue)
  315. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.ContentType] as? String, "application/xml")
  316. } else {
  317. XCTFail("error should not be nil")
  318. }
  319. }
  320. }
  321. // MARK: -
  322. class AutomaticValidationTestCase: BaseTestCase {
  323. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  324. // Given
  325. let url = URL(string: "https://httpbin.org/ip")!
  326. var urlRequest = URLRequest(url: url)
  327. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  328. let expectation = self.expectation(description: "request should succeed and return ip")
  329. var error: NSError?
  330. // When
  331. Alamofire.request(urlRequest)
  332. .validate()
  333. .response { _, _, _, responseError in
  334. error = responseError
  335. expectation.fulfill()
  336. }
  337. waitForExpectations(timeout: timeout, handler: nil)
  338. // Then
  339. XCTAssertNil(error)
  340. }
  341. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  342. // Given
  343. let urlString = "https://httpbin.org/status/404"
  344. let expectation = self.expectation(description: "request should return 404 status code")
  345. var error: NSError?
  346. // When
  347. Alamofire.request(urlString, withMethod: .get)
  348. .validate()
  349. .response { _, _, _, responseError in
  350. error = responseError
  351. expectation.fulfill()
  352. }
  353. waitForExpectations(timeout: timeout, handler: nil)
  354. // Then
  355. XCTAssertNotNil(error)
  356. if let error = error {
  357. XCTAssertEqual(error.domain, ErrorDomain)
  358. XCTAssertEqual(error.code, ErrorCode.statusCodeValidationFailed.rawValue)
  359. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.StatusCode] as? Int, 404)
  360. } else {
  361. XCTFail("error should not be nil")
  362. }
  363. }
  364. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  365. // Given
  366. let url = URL(string: "https://httpbin.org/ip")!
  367. var urlRequest = URLRequest(url: url)
  368. urlRequest.setValue("application/*", forHTTPHeaderField: "Accept")
  369. let expectation = self.expectation(description: "request should succeed and return ip")
  370. var error: NSError?
  371. // When
  372. Alamofire.request(urlRequest)
  373. .validate()
  374. .response { _, _, _, responseError in
  375. error = responseError
  376. expectation.fulfill()
  377. }
  378. waitForExpectations(timeout: timeout, handler: nil)
  379. // Then
  380. XCTAssertNil(error)
  381. }
  382. func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() {
  383. // Given
  384. let url = URL(string: "https://httpbin.org/xml")!
  385. var urlRequest = URLRequest(url: url)
  386. let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5"
  387. urlRequest.setValue(headerValue, forHTTPHeaderField: "Accept")
  388. let expectation = self.expectation(description: "request should succeed and return xml")
  389. var error: NSError?
  390. // When
  391. Alamofire.request(urlRequest)
  392. .validate()
  393. .response { _, _, _, responseError in
  394. error = responseError
  395. expectation.fulfill()
  396. }
  397. waitForExpectations(timeout: timeout, handler: nil)
  398. // Then
  399. XCTAssertNil(error)
  400. }
  401. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  402. // Given
  403. let url = URL(string: "https://httpbin.org/xml")!
  404. var urlRequest = URLRequest(url: url)
  405. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  406. let expectation = self.expectation(description: "request should succeed and return xml")
  407. var error: NSError?
  408. // When
  409. Alamofire.request(urlRequest)
  410. .validate()
  411. .response { _, _, _, responseError in
  412. error = responseError
  413. expectation.fulfill()
  414. }
  415. waitForExpectations(timeout: timeout, handler: nil)
  416. // Then
  417. XCTAssertNotNil(error)
  418. if let error = error {
  419. XCTAssertEqual(error.domain, ErrorDomain)
  420. XCTAssertEqual(error.code, ErrorCode.contentTypeValidationFailed.rawValue)
  421. XCTAssertEqual(error.userInfo[ErrorUserInfoKeys.ContentType] as? String, "application/xml")
  422. } else {
  423. XCTFail("error should not be nil")
  424. }
  425. }
  426. }