ValidationTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // ValidationTests.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. @testable import Alamofire
  23. import Foundation
  24. import XCTest
  25. class StatusCodeValidationTestCase: BaseTestCase {
  26. func testThatValidationForRequestWithAcceptableStatusCodeResponseSucceeds() {
  27. // Given
  28. let URLString = "https://httpbin.org/status/200"
  29. let expectation = expectationWithDescription("request should return 200 status code")
  30. var error: NSError?
  31. // When
  32. Alamofire.request(.GET, URLString)
  33. .validate(statusCode: 200..<300)
  34. .response { _, _, _, responseError in
  35. error = responseError
  36. expectation.fulfill()
  37. }
  38. waitForExpectationsWithTimeout(timeout, handler: nil)
  39. // Then
  40. XCTAssertNil(error, "error should be nil")
  41. }
  42. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  43. // Given
  44. let URLString = "https://httpbin.org/status/404"
  45. let expectation = expectationWithDescription("request should return 404 status code")
  46. var error: NSError?
  47. // When
  48. Alamofire.request(.GET, URLString)
  49. .validate(statusCode: [200])
  50. .response { _, _, _, responseError in
  51. error = responseError
  52. expectation.fulfill()
  53. }
  54. waitForExpectationsWithTimeout(timeout, handler: nil)
  55. // Then
  56. XCTAssertNotNil(error, "error should not be nil")
  57. if let error = error {
  58. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  59. XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue, "code should be status code validation failure")
  60. } else {
  61. XCTFail("error should be an NSError")
  62. }
  63. }
  64. func testThatValidationForRequestWithNoAcceptableStatusCodesFails() {
  65. // Given
  66. let URLString = "https://httpbin.org/status/201"
  67. let expectation = expectationWithDescription("request should return 201 status code")
  68. var error: NSError?
  69. // When
  70. Alamofire.request(.GET, URLString)
  71. .validate(statusCode: [])
  72. .response { _, _, _, responseError in
  73. error = responseError
  74. expectation.fulfill()
  75. }
  76. waitForExpectationsWithTimeout(timeout, handler: nil)
  77. // Then
  78. XCTAssertNotNil(error, "error should not be nil")
  79. if let error = error {
  80. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  81. XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue, "code should be status code validation failure")
  82. } else {
  83. XCTFail("error should be an NSError")
  84. }
  85. }
  86. }
  87. // MARK: -
  88. class ContentTypeValidationTestCase: BaseTestCase {
  89. func testThatValidationForRequestWithAcceptableContentTypeResponseSucceeds() {
  90. // Given
  91. let URLString = "https://httpbin.org/ip"
  92. let expectation = expectationWithDescription("request should succeed and return ip")
  93. var error: NSError?
  94. // When
  95. Alamofire.request(.GET, URLString)
  96. .validate(contentType: ["application/json"])
  97. .validate(contentType: ["application/json;charset=utf8"])
  98. .validate(contentType: ["application/json;q=0.8;charset=utf8"])
  99. .response { _, _, _, responseError in
  100. error = responseError
  101. expectation.fulfill()
  102. }
  103. waitForExpectationsWithTimeout(timeout, handler: nil)
  104. // Then
  105. XCTAssertNil(error, "error should be nil")
  106. }
  107. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  108. // Given
  109. let URLString = "https://httpbin.org/ip"
  110. let expectation = expectationWithDescription("request should succeed and return ip")
  111. var error: NSError?
  112. // When
  113. Alamofire.request(.GET, URLString)
  114. .validate(contentType: ["*/*"])
  115. .validate(contentType: ["application/*"])
  116. .validate(contentType: ["*/json"])
  117. .response { _, _, _, responseError in
  118. error = responseError
  119. expectation.fulfill()
  120. }
  121. waitForExpectationsWithTimeout(timeout, handler: nil)
  122. // Then
  123. XCTAssertNil(error, "error should be nil")
  124. }
  125. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  126. // Given
  127. let URLString = "https://httpbin.org/xml"
  128. let expectation = expectationWithDescription("request should succeed and return xml")
  129. var error: NSError?
  130. // When
  131. Alamofire.request(.GET, URLString)
  132. .validate(contentType: ["application/octet-stream"])
  133. .response { _, _, _, responseError in
  134. error = responseError
  135. expectation.fulfill()
  136. }
  137. waitForExpectationsWithTimeout(timeout, handler: nil)
  138. // Then
  139. XCTAssertNotNil(error, "error should not be nil")
  140. if let error = error {
  141. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  142. XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue, "code should be content type validation failure")
  143. } else {
  144. XCTFail("error should be an NSError")
  145. }
  146. }
  147. func testThatValidationForRequestWithNoAcceptableContentTypeResponseFails() {
  148. // Given
  149. let URLString = "https://httpbin.org/xml"
  150. let expectation = expectationWithDescription("request should succeed and return xml")
  151. var error: NSError?
  152. // When
  153. Alamofire.request(.GET, URLString)
  154. .validate(contentType: [])
  155. .response { _, _, _, responseError in
  156. error = responseError
  157. expectation.fulfill()
  158. }
  159. waitForExpectationsWithTimeout(timeout, handler: nil)
  160. // Then
  161. XCTAssertNotNil(error, "error should not be nil")
  162. if let error = error {
  163. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  164. XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue, "code should be content type validation failure")
  165. } else {
  166. XCTFail("error should be an NSError")
  167. }
  168. }
  169. func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() {
  170. // Given
  171. let URLString = "https://httpbin.org/status/204"
  172. let expectation = expectationWithDescription("request should succeed and return no data")
  173. var error: NSError?
  174. // When
  175. Alamofire.request(.GET, URLString)
  176. .validate(contentType: [])
  177. .response { _, response, data, responseError in
  178. error = responseError
  179. print(response)
  180. if let data = data {
  181. print(String(data: data, encoding: NSUTF8StringEncoding)!)
  182. }
  183. expectation.fulfill()
  184. }
  185. waitForExpectationsWithTimeout(timeout, handler: nil)
  186. // Then
  187. XCTAssertNil(error, "error should be nil")
  188. }
  189. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceedsWhenResponseIsNil() {
  190. // Given
  191. class MockManager: Manager {
  192. override func request(URLRequest: URLRequestConvertible) -> Request {
  193. var dataTask: NSURLSessionDataTask!
  194. dispatch_sync(queue) {
  195. dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
  196. }
  197. let request = MockRequest(session: session, task: dataTask)
  198. delegate[request.delegate.task] = request.delegate
  199. if startRequestsImmediately {
  200. request.resume()
  201. }
  202. return request
  203. }
  204. }
  205. class MockRequest: Request {
  206. override var response: NSHTTPURLResponse? {
  207. return MockHTTPURLResponse(
  208. URL: NSURL(string: request!.URLString)!,
  209. statusCode: 204,
  210. HTTPVersion: "HTTP/1.1",
  211. headerFields: nil
  212. )
  213. }
  214. }
  215. class MockHTTPURLResponse: NSHTTPURLResponse {
  216. override var MIMEType: String? { return nil }
  217. }
  218. let manager: Manager = {
  219. let configuration: NSURLSessionConfiguration = {
  220. let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
  221. configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
  222. return configuration
  223. }()
  224. return MockManager(configuration: configuration)
  225. }()
  226. let URLString = "https://httpbin.org/delete"
  227. let expectation = expectationWithDescription("request should be stubbed and return 204 status code")
  228. var response: NSHTTPURLResponse?
  229. var data: NSData?
  230. var error: NSError?
  231. // When
  232. manager.request(.DELETE, URLString)
  233. .validate(contentType: ["*/*"])
  234. .response { _, responseResponse, responseData, responseError in
  235. response = responseResponse
  236. data = responseData
  237. error = responseError
  238. expectation.fulfill()
  239. }
  240. waitForExpectationsWithTimeout(timeout, handler: nil)
  241. // Then
  242. XCTAssertNotNil(response, "response should not be nil")
  243. XCTAssertNotNil(data, "data should not be nil")
  244. XCTAssertNil(error, "error should be nil")
  245. if let response = response {
  246. XCTAssertEqual(response.statusCode, 204, "response status code should be 204")
  247. XCTAssertNil(response.MIMEType, "response mime type should be nil")
  248. }
  249. }
  250. }
  251. // MARK: -
  252. class MultipleValidationTestCase: BaseTestCase {
  253. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  254. // Given
  255. let URLString = "https://httpbin.org/ip"
  256. let expectation = expectationWithDescription("request should succeed and return ip")
  257. var error: NSError?
  258. // When
  259. Alamofire.request(.GET, URLString)
  260. .validate(statusCode: 200..<300)
  261. .validate(contentType: ["application/json"])
  262. .response { _, _, _, responseError in
  263. error = responseError
  264. expectation.fulfill()
  265. }
  266. waitForExpectationsWithTimeout(timeout, handler: nil)
  267. // Then
  268. XCTAssertNil(error, "error should be nil")
  269. }
  270. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() {
  271. // Given
  272. let URLString = "https://httpbin.org/xml"
  273. let expectation = expectationWithDescription("request should succeed and return xml")
  274. var error: NSError?
  275. // When
  276. Alamofire.request(.GET, URLString)
  277. .validate(statusCode: 400..<600)
  278. .validate(contentType: ["application/octet-stream"])
  279. .response { _, _, _, responseError in
  280. error = responseError
  281. expectation.fulfill()
  282. }
  283. waitForExpectationsWithTimeout(timeout, handler: nil)
  284. // Then
  285. XCTAssertNotNil(error, "error should not be nil")
  286. if let error = error {
  287. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  288. XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue, "code should be status code validation failure")
  289. } else {
  290. XCTFail("error should be an NSError")
  291. }
  292. }
  293. func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() {
  294. // Given
  295. let URLString = "https://httpbin.org/xml"
  296. let expectation = expectationWithDescription("request should succeed and return xml")
  297. var error: NSError?
  298. // When
  299. Alamofire.request(.GET, URLString)
  300. .validate(contentType: ["application/octet-stream"])
  301. .validate(statusCode: 400..<600)
  302. .response { _, _, _, responseError in
  303. error = responseError
  304. expectation.fulfill()
  305. }
  306. waitForExpectationsWithTimeout(timeout, handler: nil)
  307. // Then
  308. XCTAssertNotNil(error, "error should not be nil")
  309. if let error = error {
  310. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  311. XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue, "code should be content type validation failure")
  312. } else {
  313. XCTFail("error should be an NSError")
  314. }
  315. }
  316. }
  317. // MARK: -
  318. class AutomaticValidationTestCase: BaseTestCase {
  319. func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
  320. // Given
  321. let URL = NSURL(string: "https://httpbin.org/ip")!
  322. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  323. mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  324. let expectation = expectationWithDescription("request should succeed and return ip")
  325. var error: NSError?
  326. // When
  327. Alamofire.request(mutableURLRequest)
  328. .validate()
  329. .response { _, _, _, responseError in
  330. error = responseError
  331. expectation.fulfill()
  332. }
  333. waitForExpectationsWithTimeout(timeout, handler: nil)
  334. // Then
  335. XCTAssertNil(error, "error should be nil")
  336. }
  337. func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
  338. // Given
  339. let URLString = "https://httpbin.org/status/404"
  340. let expectation = expectationWithDescription("request should return 404 status code")
  341. var error: NSError?
  342. // When
  343. Alamofire.request(.GET, URLString)
  344. .validate()
  345. .response { _, _, _, responseError in
  346. error = responseError
  347. expectation.fulfill()
  348. }
  349. waitForExpectationsWithTimeout(timeout, handler: nil)
  350. // Then
  351. XCTAssertNotNil(error, "error should not be nil")
  352. if let error = error {
  353. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  354. XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue, "code should be status code validation failure")
  355. } else {
  356. XCTFail("error should be an NSError")
  357. }
  358. }
  359. func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
  360. // Given
  361. let URL = NSURL(string: "https://httpbin.org/ip")!
  362. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  363. mutableURLRequest.setValue("application/*", forHTTPHeaderField: "Accept")
  364. let expectation = expectationWithDescription("request should succeed and return ip")
  365. var error: NSError?
  366. // When
  367. Alamofire.request(mutableURLRequest)
  368. .validate()
  369. .response { _, _, _, responseError in
  370. error = responseError
  371. expectation.fulfill()
  372. }
  373. waitForExpectationsWithTimeout(timeout, handler: nil)
  374. // Then
  375. XCTAssertNil(error, "error should be nil")
  376. }
  377. func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() {
  378. // Given
  379. let URL = NSURL(string: "https://httpbin.org/xml")!
  380. let mutableURLRequest = NSMutableURLRequest(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. mutableURLRequest.setValue(headerValue, forHTTPHeaderField: "Accept")
  383. let expectation = expectationWithDescription("request should succeed and return xml")
  384. var error: NSError?
  385. // When
  386. Alamofire.request(mutableURLRequest)
  387. .validate()
  388. .response { _, _, _, responseError in
  389. error = responseError
  390. expectation.fulfill()
  391. }
  392. waitForExpectationsWithTimeout(timeout, handler: nil)
  393. // Then
  394. XCTAssertNil(error, "error should be nil")
  395. }
  396. func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
  397. // Given
  398. let URL = NSURL(string: "https://httpbin.org/xml")!
  399. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  400. mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
  401. let expectation = expectationWithDescription("request should succeed and return xml")
  402. var error: NSError?
  403. // When
  404. Alamofire.request(mutableURLRequest)
  405. .validate()
  406. .response { _, _, _, responseError in
  407. error = responseError
  408. expectation.fulfill()
  409. }
  410. waitForExpectationsWithTimeout(timeout, handler: nil)
  411. // Then
  412. XCTAssertNotNil(error, "error should not be nil")
  413. if let error = error {
  414. XCTAssertEqual(error.domain, Error.Domain, "domain should be Alamofire error domain")
  415. XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue, "code should be content type validation failure")
  416. } else {
  417. XCTFail("error should be an NSError")
  418. }
  419. }
  420. }