ValidationTests.swift 18 KB

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