URLProtocolTests.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. //
  2. // URLProtocolTests.swift
  3. //
  4. // Copyright (c) 2014-2018 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.headers = HTTPHeaders.default
  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. do {
  52. return try URLEncoding.default.encode(request, with: headers)
  53. } catch {
  54. return request
  55. }
  56. }
  57. return request
  58. }
  59. override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
  60. return false
  61. }
  62. // MARK: Loading Methods
  63. override func startLoading() {
  64. // rdar://26849668 - URLProtocol had some API's that didnt make the value type conversion
  65. let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest
  66. URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest)
  67. activeTask = session.dataTask(with: urlRequest as URLRequest)
  68. activeTask?.resume()
  69. }
  70. override func stopLoading() {
  71. activeTask?.cancel()
  72. }
  73. }
  74. // MARK: -
  75. extension ProxyURLProtocol: URLSessionDataDelegate {
  76. // MARK: NSURLSessionDelegate
  77. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  78. client?.urlProtocol(self, didLoad: data)
  79. }
  80. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  81. if let response = task.response {
  82. client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  83. }
  84. client?.urlProtocolDidFinishLoading(self)
  85. }
  86. }
  87. // MARK: -
  88. class URLProtocolTestCase: BaseTestCase {
  89. var manager: Session!
  90. // MARK: Setup and Teardown
  91. override func setUp() {
  92. super.setUp()
  93. manager = {
  94. let configuration: URLSessionConfiguration = {
  95. let configuration = URLSessionConfiguration.default
  96. configuration.protocolClasses = [ProxyURLProtocol.self]
  97. configuration.httpAdditionalHeaders = ["Session-Configuration-Header": "foo"]
  98. return configuration
  99. }()
  100. return Session(configuration: configuration)
  101. }()
  102. }
  103. // MARK: Tests
  104. func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
  105. // Given
  106. let urlString = "https://httpbin.org/response-headers"
  107. let url = URL(string: urlString)!
  108. var urlRequest = URLRequest(url: url)
  109. urlRequest.httpMethod = HTTPMethod.get.rawValue
  110. urlRequest.setValue("foobar", forHTTPHeaderField: "Request-Header")
  111. let expectation = self.expectation(description: "GET request should succeed")
  112. var response: DataResponse<Data?>?
  113. // When
  114. manager.request(urlRequest)
  115. .response { resp in
  116. response = resp
  117. expectation.fulfill()
  118. }
  119. waitForExpectations(timeout: timeout, handler: nil)
  120. // Then
  121. XCTAssertNotNil(response?.request)
  122. XCTAssertNotNil(response?.response)
  123. XCTAssertNotNil(response?.data)
  124. XCTAssertNil(response?.error)
  125. if let headers = response?.response?.allHeaderFields as? [String: String] {
  126. XCTAssertEqual(headers["Request-Header"] ?? headers["request-header"], "foobar")
  127. XCTAssertEqual(headers["Session-Configuration-Header"] ?? headers["session-configuration-header"], "foo")
  128. } else {
  129. XCTFail("headers should not be nil")
  130. }
  131. }
  132. }