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) -> DataRequest {
  193. let originalRequest = urlRequest.urlRequest
  194. let adaptedRequest = originalRequest.adapt(using: adapter)
  195. var task: URLSessionDataTask!
  196. queue.sync { task = self.session.dataTask(with: adaptedRequest) }
  197. let originalTask = DataRequest.Requestable.request(originalRequest)
  198. let request = MockRequest(session: session, task: task, originalTask: originalTask)
  199. delegate[request.delegate.task] = request
  200. if startRequestsImmediately { request.resume() }
  201. return request
  202. }
  203. }
  204. class MockRequest: DataRequest {
  205. override var response: HTTPURLResponse? {
  206. return MockHTTPURLResponse(
  207. url: URL(string: request!.urlString)!,
  208. statusCode: 204,
  209. httpVersion: "HTTP/1.1",
  210. headerFields: nil
  211. )
  212. }
  213. }
  214. class MockHTTPURLResponse: HTTPURLResponse {
  215. override var mimeType: String? { return nil }
  216. }
  217. let manager: SessionManager = {
  218. let configuration: URLSessionConfiguration = {
  219. let configuration = URLSessionConfiguration.ephemeral
  220. configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
  221. return configuration
  222. }()
  223. return MockManager(configuration: configuration)
  224. }()
  225. let urlString = "https://httpbin.org/delete"
  226. let expectation = self.expectation(description: "request should be stubbed and return 204 status code")
  227. var response: HTTPURLResponse?
  228. var data: Data?
  229. var error: Error?
  230. // When
  231. manager.request(urlString, withMethod: .delete)
  232. .validate(contentType: ["*/*"])
  233. .response { _, responseResponse, responseData, responseError in
  234. response = responseResponse
  235. data = responseData
  236. error = responseError
  237. expectation.fulfill()
  238. }
  239. waitForExpectations(timeout: timeout, handler: nil)
  240. // Then
  241. XCTAssertNotNil(response)
  242. XCTAssertNotNil(data)
  243. XCTAssertNil(error)
  244. if let response = response {
  245. XCTAssertEqual(response.statusCode, 204)
  246. XCTAssertNil(response.mimeType)
  247. }
  248. }
  249. }
  250. // MARK: -
  251. class MultipleValidationTestCase: BaseTestCase {
  252. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  253. // Given
  254. let urlString = "https://httpbin.org/ip"
  255. let expectation = self.expectation(description: "request should succeed and return ip")
  256. var error: Error?
  257. // When
  258. Alamofire.request(urlString, withMethod: .get)
  259. .validate(statusCode: 200..<300)
  260. .validate(contentType: ["application/json"])
  261. .response { _, _, _, responseError in
  262. error = responseError
  263. expectation.fulfill()
  264. }
  265. waitForExpectations(timeout: timeout, handler: nil)
  266. // Then
  267. XCTAssertNil(error)
  268. }
  269. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() {
  270. // Given
  271. let urlString = "https://httpbin.org/xml"
  272. let expectation = self.expectation(description: "request should succeed and return xml")
  273. var error: Error?
  274. // When
  275. Alamofire.request(urlString, withMethod: .get)
  276. .validate(statusCode: 400..<600)
  277. .validate(contentType: ["application/octet-stream"])
  278. .response { _, _, _, responseError in
  279. error = responseError
  280. expectation.fulfill()
  281. }
  282. waitForExpectations(timeout: timeout, handler: nil)
  283. // Then
  284. XCTAssertNotNil(error)
  285. if let error = error as? AFError {
  286. XCTAssertTrue(error.isUnacceptableStatusCode)
  287. XCTAssertEqual(error.responseCode, 200)
  288. } else {
  289. XCTFail("error should not be nil")
  290. }
  291. }
  292. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() {
  293. // Given
  294. let urlString = "https://httpbin.org/xml"
  295. let expectation = self.expectation(description: "request should succeed and return xml")
  296. var error: Error?
  297. // When
  298. Alamofire.request(urlString, withMethod: .get)
  299. .validate(contentType: ["application/octet-stream"])
  300. .validate(statusCode: 400..<600)
  301. .response { _, _, _, responseError in
  302. error = responseError
  303. expectation.fulfill()
  304. }
  305. waitForExpectations(timeout: timeout, handler: nil)
  306. // Then
  307. XCTAssertNotNil(error)
  308. if let error = error as? AFError {
  309. XCTAssertTrue(error.isUnacceptableContentType)
  310. XCTAssertEqual(error.responseContentType, "application/xml")
  311. XCTAssertEqual(error.acceptableContentTypes?.first, "application/octet-stream")
  312. } else {
  313. XCTFail("error should not be nil")
  314. }
  315. }
  316. }
  317. // MARK: -
  318. class AutomaticValidationTestCase: BaseTestCase {
  319. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  320. // Given
  321. let url = URL(string: "https://httpbin.org/ip")!
  322. var urlRequest = URLRequest(url: url)
  323. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  324. let expectation = self.expectation(description: "request should succeed and return ip")
  325. var error: Error?
  326. // When
  327. Alamofire.request(urlRequest)
  328. .validate()
  329. .response { _, _, _, responseError in
  330. error = responseError
  331. expectation.fulfill()
  332. }
  333. waitForExpectations(timeout: timeout, handler: nil)
  334. // Then
  335. XCTAssertNil(error)
  336. }
  337. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  338. // Given
  339. let urlString = "https://httpbin.org/status/404"
  340. let expectation = self.expectation(description: "request should return 404 status code")
  341. var error: Error?
  342. // When
  343. Alamofire.request(urlString, withMethod: .get)
  344. .validate()
  345. .response { _, _, _, responseError in
  346. error = responseError
  347. expectation.fulfill()
  348. }
  349. waitForExpectations(timeout: timeout, handler: nil)
  350. // Then
  351. XCTAssertNotNil(error)
  352. if let error = error as? AFError, let statusCode = error.responseCode {
  353. XCTAssertTrue(error.isUnacceptableStatusCode)
  354. XCTAssertEqual(statusCode, 404)
  355. } else {
  356. XCTFail("error should not be nil")
  357. }
  358. }
  359. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  360. // Given
  361. let url = URL(string: "https://httpbin.org/ip")!
  362. var urlRequest = URLRequest(url: url)
  363. urlRequest.setValue("application/*", forHTTPHeaderField: "Accept")
  364. let expectation = self.expectation(description: "request should succeed and return ip")
  365. var error: Error?
  366. // When
  367. Alamofire.request(urlRequest)
  368. .validate()
  369. .response { _, _, _, responseError in
  370. error = responseError
  371. expectation.fulfill()
  372. }
  373. waitForExpectations(timeout: timeout, handler: nil)
  374. // Then
  375. XCTAssertNil(error)
  376. }
  377. func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() {
  378. // Given
  379. let url = URL(string: "https://httpbin.org/xml")!
  380. var urlRequest = URLRequest(url: url)
  381. let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5"
  382. urlRequest.setValue(headerValue, forHTTPHeaderField: "Accept")
  383. let expectation = self.expectation(description: "request should succeed and return xml")
  384. var error: Error?
  385. // When
  386. Alamofire.request(urlRequest)
  387. .validate()
  388. .response { _, _, _, responseError in
  389. error = responseError
  390. expectation.fulfill()
  391. }
  392. waitForExpectations(timeout: timeout, handler: nil)
  393. // Then
  394. XCTAssertNil(error)
  395. }
  396. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  397. // Given
  398. let url = URL(string: "https://httpbin.org/xml")!
  399. var urlRequest = URLRequest(url: url)
  400. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  401. let expectation = self.expectation(description: "request should succeed and return xml")
  402. var error: Error?
  403. // When
  404. Alamofire.request(urlRequest)
  405. .validate()
  406. .response { _, _, _, responseError in
  407. error = responseError
  408. expectation.fulfill()
  409. }
  410. waitForExpectations(timeout: timeout, handler: nil)
  411. // Then
  412. XCTAssertNotNil(error)
  413. if let error = error as? AFError {
  414. XCTAssertTrue(error.isUnacceptableContentType)
  415. XCTAssertEqual(error.responseContentType, "application/xml")
  416. XCTAssertEqual(error.acceptableContentTypes?.first, "application/json")
  417. } else {
  418. XCTFail("error should not be nil")
  419. }
  420. }
  421. }