URLProtocolTests.swift 5.7 KB

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