URLProtocolTests.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // URLProtocolTests.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. import Alamofire
  23. import Foundation
  24. import XCTest
  25. class ProxyURLProtocol: NSURLProtocol {
  26. // MARK: Properties
  27. struct PropertyKeys {
  28. static let HandledByForwarderURLProtocol = "HandledByProxyURLProtocol"
  29. }
  30. lazy var session: NSURLSession = {
  31. let configuration: NSURLSessionConfiguration = {
  32. let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
  33. configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
  34. return configuration
  35. }()
  36. let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  37. return session
  38. }()
  39. var activeTask: NSURLSessionTask?
  40. // MARK: Class Request Methods
  41. override class func canInitWithRequest(request: NSURLRequest) -> Bool {
  42. if NSURLProtocol.propertyForKey(PropertyKeys.HandledByForwarderURLProtocol, inRequest: request) != nil {
  43. return false
  44. }
  45. return true
  46. }
  47. override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
  48. return request
  49. }
  50. override class func requestIsCacheEquivalent(a: NSURLRequest, toRequest b: NSURLRequest) -> Bool {
  51. return false
  52. }
  53. // MARK: Loading Methods
  54. override func startLoading() {
  55. var mutableRequest = self.request.mutableCopy() as! NSMutableURLRequest
  56. NSURLProtocol.setProperty(true, forKey: PropertyKeys.HandledByForwarderURLProtocol, inRequest: mutableRequest)
  57. self.activeTask = self.session.dataTaskWithRequest(mutableRequest)
  58. self.activeTask?.resume()
  59. }
  60. override func stopLoading() {
  61. self.activeTask?.cancel()
  62. }
  63. }
  64. // MARK: -
  65. extension ProxyURLProtocol: NSURLSessionDelegate {
  66. // MARK: NSURLSessionDelegate
  67. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  68. self.client?.URLProtocol(self, didLoadData: data)
  69. }
  70. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  71. if let response = task.response {
  72. let cachePolicy = task.originalRequest.cachePolicy
  73. self.client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
  74. }
  75. self.client?.URLProtocolDidFinishLoading(self)
  76. }
  77. }
  78. // MARK: -
  79. class URLProtocolTestCase: BaseTestCase {
  80. // MARK: Setup and Teardown Methods
  81. override func setUp() {
  82. super.setUp()
  83. let protocolClasses: [AnyObject] = [ProxyURLProtocol.self]
  84. Alamofire.Manager.sharedInstance.session.configuration.protocolClasses = protocolClasses
  85. Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Session-Configuration-Header": "foo"]
  86. }
  87. override func tearDown() {
  88. super.tearDown()
  89. Alamofire.Manager.sharedInstance.session.configuration.protocolClasses = []
  90. }
  91. // MARK: Tests
  92. func testThatURLProtocolReceivesRequestHeadersAndNotSessionConfigurationHeaders() {
  93. // Given
  94. let URLString = "http://httpbin.org/response-headers"
  95. let URL = NSURL(string: URLString)!
  96. let parameters = ["URLRequest-Header": "foobar"]
  97. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  98. mutableURLRequest.HTTPMethod = Method.GET.rawValue
  99. let URLRequest = ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
  100. let expectation = expectationWithDescription("GET request should succeed")
  101. var request: NSURLRequest?
  102. var response: NSHTTPURLResponse?
  103. var string: AnyObject?
  104. var error: NSError?
  105. // When
  106. Alamofire.request(URLRequest)
  107. .response { responseRequest, responseResponse, responseString, responseError in
  108. request = responseRequest
  109. response = responseResponse
  110. string = responseString
  111. error = responseError
  112. expectation.fulfill()
  113. }
  114. waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
  115. // Then
  116. XCTAssertNotNil(request, "request should not be nil")
  117. XCTAssertNotNil(response, "response should not be nil")
  118. XCTAssertNotNil(string, "string should not be nil")
  119. XCTAssertNil(error, "error should be nil")
  120. if let headers = response?.allHeaderFields as? [String: String] {
  121. XCTAssertEqual(headers["URLRequest-Header"] ?? "", "foobar", "URLRequest-Header should be foobar")
  122. XCTAssertNil(headers["Session-Configuration-Header"], "Session-Configuration-Header should be nil")
  123. } else {
  124. XCTFail("headers should not be nil")
  125. }
  126. }
  127. }