URLProtocolTests.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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: URLProtocol {
  28. // MARK: Properties
  29. struct PropertyKeys {
  30. static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol"
  31. }
  32. lazy var session: URLSession = {
  33. let configuration: URLSessionConfiguration = {
  34. let configuration = URLSessionConfiguration.ephemeral
  35. configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
  36. return configuration
  37. }()
  38. let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  39. return session
  40. }()
  41. var activeTask: URLSessionTask?
  42. // MARK: Class Request Methods
  43. override class func canInit(with request: URLRequest) -> Bool {
  44. if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil {
  45. return false
  46. }
  47. return true
  48. }
  49. override class func canonicalRequest(for request: URLRequest) -> URLRequest {
  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: URLRequest, to b: URLRequest) -> Bool {
  56. return false
  57. }
  58. // MARK: Loading Methods
  59. override func startLoading() {
  60. // rdar://26849668
  61. // Hopefully will be fixed in a future seed
  62. // URLProtocol had some API's that didnt make the value type conversion
  63. let mutableRequest = (request.urlRequest as NSURLRequest).mutableCopy() as! NSMutableURLRequest
  64. URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: mutableRequest)
  65. activeTask = session.dataTask(with: mutableRequest as URLRequest)
  66. activeTask?.resume()
  67. }
  68. override func stopLoading() {
  69. activeTask?.cancel()
  70. }
  71. }
  72. // MARK: -
  73. extension ProxyURLProtocol: URLSessionDelegate {
  74. // MARK: NSURLSessionDelegate
  75. func URLSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data) {
  76. client?.urlProtocol(self, didLoad: data)
  77. }
  78. func URLSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  79. if let response = task.response {
  80. client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  81. }
  82. client?.urlProtocolDidFinishLoading(self)
  83. }
  84. }
  85. // MARK: -
  86. class URLProtocolTestCase: BaseTestCase {
  87. var manager: SessionManager!
  88. // MARK: Setup and Teardown
  89. override func setUp() {
  90. super.setUp()
  91. manager = {
  92. let configuration: URLSessionConfiguration = {
  93. let configuration = URLSessionConfiguration.default
  94. configuration.protocolClasses = [ProxyURLProtocol.self]
  95. configuration.httpAdditionalHeaders = ["session-configuration-header": "foo"]
  96. return configuration
  97. }()
  98. return SessionManager(configuration: configuration)
  99. }()
  100. }
  101. // MARK: Tests
  102. func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
  103. // Given
  104. let urlString = "https://httpbin.org/response-headers"
  105. let url = URL(string: urlString)!
  106. var urlRequest = URLRequest(url: url)
  107. urlRequest.httpMethod = HTTPMethod.get.rawValue
  108. urlRequest.setValue("foobar", forHTTPHeaderField: "request-header")
  109. let expectation = self.expectation(description: "GET request should succeed")
  110. var request: URLRequest?
  111. var response: HTTPURLResponse?
  112. var data: Data?
  113. var error: NSError?
  114. // When
  115. manager.request(urlRequest)
  116. .response { responseRequest, responseResponse, responseData, responseError in
  117. request = responseRequest
  118. response = responseResponse
  119. data = responseData
  120. error = responseError
  121. expectation.fulfill()
  122. }
  123. waitForExpectations(timeout: timeout, handler: nil)
  124. // Then
  125. XCTAssertNotNil(request, "request should not be nil")
  126. XCTAssertNotNil(response, "response should not be nil")
  127. XCTAssertNotNil(data, "data should not be nil")
  128. XCTAssertNil(error, "error should be nil")
  129. if let headers = response?.allHeaderFields as? [String: String] {
  130. XCTAssertEqual(headers["request-header"], "foobar")
  131. XCTAssertEqual(headers["session-configuration-header"], "foo")
  132. } else {
  133. XCTFail("headers should not be nil")
  134. }
  135. }
  136. }