ValidationTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 { resp in
  37. error = resp.error
  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 { resp in
  53. error = resp.error
  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 { resp in
  75. error = resp.error
  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 { resp in
  102. error = resp.error
  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 { resp in
  120. error = resp.error
  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 { resp in
  136. error = resp.error
  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 { resp in
  159. error = resp.error
  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 { resp in
  182. error = resp.error
  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: DefaultDataResponse?
  227. // When
  228. manager.request(urlString, withMethod: .delete)
  229. .validate(contentType: ["*/*"])
  230. .response { resp in
  231. response = resp
  232. expectation.fulfill()
  233. }
  234. waitForExpectations(timeout: timeout, handler: nil)
  235. // Then
  236. XCTAssertNotNil(response?.response)
  237. XCTAssertNotNil(response?.data)
  238. XCTAssertNil(response?.error)
  239. XCTAssertEqual(response?.response?.statusCode, 204)
  240. XCTAssertNil(response?.response?.mimeType)
  241. }
  242. }
  243. // MARK: -
  244. class MultipleValidationTestCase: BaseTestCase {
  245. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  246. // Given
  247. let urlString = "https://httpbin.org/ip"
  248. let expectation = self.expectation(description: "request should succeed and return ip")
  249. var error: Error?
  250. // When
  251. Alamofire.request(urlString, withMethod: .get)
  252. .validate(statusCode: 200..<300)
  253. .validate(contentType: ["application/json"])
  254. .response { resp in
  255. error = resp.error
  256. expectation.fulfill()
  257. }
  258. waitForExpectations(timeout: timeout, handler: nil)
  259. // Then
  260. XCTAssertNil(error)
  261. }
  262. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() {
  263. // Given
  264. let urlString = "https://httpbin.org/xml"
  265. let expectation = self.expectation(description: "request should succeed and return xml")
  266. var error: Error?
  267. // When
  268. Alamofire.request(urlString, withMethod: .get)
  269. .validate(statusCode: 400..<600)
  270. .validate(contentType: ["application/octet-stream"])
  271. .response { resp in
  272. error = resp.error
  273. expectation.fulfill()
  274. }
  275. waitForExpectations(timeout: timeout, handler: nil)
  276. // Then
  277. XCTAssertNotNil(error)
  278. if let error = error as? AFError {
  279. XCTAssertTrue(error.isUnacceptableStatusCode)
  280. XCTAssertEqual(error.responseCode, 200)
  281. } else {
  282. XCTFail("error should not be nil")
  283. }
  284. }
  285. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() {
  286. // Given
  287. let urlString = "https://httpbin.org/xml"
  288. let expectation = self.expectation(description: "request should succeed and return xml")
  289. var error: Error?
  290. // When
  291. Alamofire.request(urlString, withMethod: .get)
  292. .validate(contentType: ["application/octet-stream"])
  293. .validate(statusCode: 400..<600)
  294. .response { resp in
  295. error = resp.error
  296. expectation.fulfill()
  297. }
  298. waitForExpectations(timeout: timeout, handler: nil)
  299. // Then
  300. XCTAssertNotNil(error)
  301. if let error = error as? AFError {
  302. XCTAssertTrue(error.isUnacceptableContentType)
  303. XCTAssertEqual(error.responseContentType, "application/xml")
  304. XCTAssertEqual(error.acceptableContentTypes?.first, "application/octet-stream")
  305. } else {
  306. XCTFail("error should not be nil")
  307. }
  308. }
  309. }
  310. // MARK: -
  311. class AutomaticValidationTestCase: BaseTestCase {
  312. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  313. // Given
  314. let url = URL(string: "https://httpbin.org/ip")!
  315. var urlRequest = URLRequest(url: url)
  316. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  317. let expectation = self.expectation(description: "request should succeed and return ip")
  318. var error: Error?
  319. // When
  320. Alamofire.request(urlRequest)
  321. .validate()
  322. .response { resp in
  323. error = resp.error
  324. expectation.fulfill()
  325. }
  326. waitForExpectations(timeout: timeout, handler: nil)
  327. // Then
  328. XCTAssertNil(error)
  329. }
  330. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  331. // Given
  332. let urlString = "https://httpbin.org/status/404"
  333. let expectation = self.expectation(description: "request should return 404 status code")
  334. var error: Error?
  335. // When
  336. Alamofire.request(urlString, withMethod: .get)
  337. .validate()
  338. .response { resp in
  339. error = resp.error
  340. expectation.fulfill()
  341. }
  342. waitForExpectations(timeout: timeout, handler: nil)
  343. // Then
  344. XCTAssertNotNil(error)
  345. if let error = error as? AFError, let statusCode = error.responseCode {
  346. XCTAssertTrue(error.isUnacceptableStatusCode)
  347. XCTAssertEqual(statusCode, 404)
  348. } else {
  349. XCTFail("error should not be nil")
  350. }
  351. }
  352. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  353. // Given
  354. let url = URL(string: "https://httpbin.org/ip")!
  355. var urlRequest = URLRequest(url: url)
  356. urlRequest.setValue("application/*", forHTTPHeaderField: "Accept")
  357. let expectation = self.expectation(description: "request should succeed and return ip")
  358. var error: Error?
  359. // When
  360. Alamofire.request(urlRequest)
  361. .validate()
  362. .response { resp in
  363. error = resp.error
  364. expectation.fulfill()
  365. }
  366. waitForExpectations(timeout: timeout, handler: nil)
  367. // Then
  368. XCTAssertNil(error)
  369. }
  370. func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() {
  371. // Given
  372. let url = URL(string: "https://httpbin.org/xml")!
  373. var urlRequest = URLRequest(url: url)
  374. let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5"
  375. urlRequest.setValue(headerValue, forHTTPHeaderField: "Accept")
  376. let expectation = self.expectation(description: "request should succeed and return xml")
  377. var error: Error?
  378. // When
  379. Alamofire.request(urlRequest)
  380. .validate()
  381. .response { resp in
  382. error = resp.error
  383. expectation.fulfill()
  384. }
  385. waitForExpectations(timeout: timeout, handler: nil)
  386. // Then
  387. XCTAssertNil(error)
  388. }
  389. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  390. // Given
  391. let url = URL(string: "https://httpbin.org/xml")!
  392. var urlRequest = URLRequest(url: url)
  393. urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  394. let expectation = self.expectation(description: "request should succeed and return xml")
  395. var error: Error?
  396. // When
  397. Alamofire.request(urlRequest)
  398. .validate()
  399. .response { resp in
  400. error = resp.error
  401. expectation.fulfill()
  402. }
  403. waitForExpectations(timeout: timeout, handler: nil)
  404. // Then
  405. XCTAssertNotNil(error)
  406. if let error = error as? AFError {
  407. XCTAssertTrue(error.isUnacceptableContentType)
  408. XCTAssertEqual(error.responseContentType, "application/xml")
  409. XCTAssertEqual(error.acceptableContentTypes?.first, "application/json")
  410. } else {
  411. XCTFail("error should not be nil")
  412. }
  413. }
  414. }