ValidationTests.swift 18 KB

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