URLProtocolTests.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // URLProtocolTests.swift
  2. //
  3. // Copyright (c) 2014–2016 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. let mutableRequest = request.URLRequest
  56. NSURLProtocol.setProperty(true, forKey: PropertyKeys.HandledByForwarderURLProtocol, inRequest: mutableRequest)
  57. activeTask = session.dataTaskWithRequest(mutableRequest)
  58. activeTask?.resume()
  59. }
  60. override func stopLoading() {
  61. activeTask?.cancel()
  62. }
  63. }
  64. // MARK: -
  65. extension ProxyURLProtocol: NSURLSessionDelegate {
  66. // MARK: NSURLSessionDelegate
  67. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  68. client?.URLProtocol(self, didLoadData: data)
  69. }
  70. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  71. if let response = task.response {
  72. client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
  73. }
  74. client?.URLProtocolDidFinishLoading(self)
  75. }
  76. }
  77. // MARK: -
  78. class URLProtocolTestCase: BaseTestCase {
  79. // MARK: Setup and Teardown Methods
  80. override func setUp() {
  81. super.setUp()
  82. let configuration = Alamofire.Manager.sharedInstance.session.configuration
  83. configuration.protocolClasses = [ProxyURLProtocol.self]
  84. configuration.HTTPAdditionalHeaders = ["Session-Configuration-Header": "foo"]
  85. }
  86. override func tearDown() {
  87. super.tearDown()
  88. Alamofire.Manager.sharedInstance.session.configuration.protocolClasses = []
  89. }
  90. // MARK: Tests
  91. func testThatURLProtocolReceivesRequestHeadersAndNotSessionConfigurationHeaders() {
  92. // Given
  93. let URLString = "https://httpbin.org/response-headers"
  94. let URL = NSURL(string: URLString)!
  95. let parameters = ["request-header": "foobar"]
  96. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  97. mutableURLRequest.HTTPMethod = Method.GET.rawValue
  98. let URLRequest = ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
  99. let expectation = expectationWithDescription("GET request should succeed")
  100. var request: NSURLRequest?
  101. var response: NSHTTPURLResponse?
  102. var data: NSData?
  103. var error: NSError?
  104. // When
  105. Alamofire.request(URLRequest)
  106. .response { responseRequest, responseResponse, responseData, responseError in
  107. request = responseRequest
  108. response = responseResponse
  109. data = responseData
  110. error = responseError
  111. expectation.fulfill()
  112. }
  113. waitForExpectationsWithTimeout(timeout, handler: nil)
  114. // Then
  115. XCTAssertNotNil(request, "request should not be nil")
  116. XCTAssertNotNil(response, "response should not be nil")
  117. XCTAssertNotNil(data, "data should not be nil")
  118. XCTAssertNil(error, "error should be nil")
  119. if let headers = response?.allHeaderFields as? [String: String] {
  120. XCTAssertEqual(headers["request-header"] ?? "", "foobar", "urlrequest-header should be foobar")
  121. XCTAssertNil(headers["Session-Configuration-Header"], "Session-Configuration-Header should be nil")
  122. } else {
  123. XCTFail("headers should not be nil")
  124. }
  125. }
  126. }