URLProtocolTests.swift 5.9 KB

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