URLProtocolTests.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. enum 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. return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  39. }()
  40. weak var activeTask: URLSessionTask?
  41. // MARK: Class Request Methods
  42. override class func canInit(with request: URLRequest) -> Bool {
  43. if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil {
  44. return false
  45. }
  46. return true
  47. }
  48. override class func canonicalRequest(for request: URLRequest) -> URLRequest {
  49. if let headers = request.allHTTPHeaderFields {
  50. do {
  51. return try URLEncoding.default.encode(request, with: headers)
  52. } catch {
  53. return request
  54. }
  55. }
  56. return request
  57. }
  58. override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
  59. false
  60. }
  61. // MARK: Loading Methods
  62. override func startLoading() {
  63. // rdar://26849668 - URLProtocol had some API's that didn't make the value type conversion
  64. let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest
  65. URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest)
  66. activeTask = session.dataTask(with: urlRequest as URLRequest)
  67. activeTask?.resume()
  68. }
  69. override func stopLoading() {
  70. activeTask?.cancel()
  71. }
  72. }
  73. // MARK: -
  74. extension ProxyURLProtocol: URLSessionDataDelegate {
  75. // MARK: NSURLSessionDelegate
  76. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  77. client?.urlProtocol(self, didLoad: data)
  78. }
  79. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {
  80. if let response = task.response {
  81. client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  82. }
  83. client?.urlProtocolDidFinishLoading(self)
  84. }
  85. }
  86. // MARK: -
  87. class URLProtocolTestCase: BaseTestCase {
  88. var manager: Session!
  89. // MARK: Setup and Teardown
  90. override func setUp() {
  91. super.setUp()
  92. manager = {
  93. let configuration: URLSessionConfiguration = {
  94. let configuration = URLSessionConfiguration.default
  95. configuration.protocolClasses = [ProxyURLProtocol.self]
  96. configuration.headers["Session-Configuration-Header"] = "foo"
  97. return configuration
  98. }()
  99. return Session(configuration: configuration)
  100. }()
  101. }
  102. // MARK: Tests
  103. @MainActor
  104. func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
  105. // Given
  106. let endpoint = Endpoint.responseHeaders.modifying(\.headers, to: ["Request-Header": "foobar"])
  107. let expectation = expectation(description: "GET request should succeed")
  108. var response: DataResponse<Data?, AFError>?
  109. // When
  110. manager.request(endpoint)
  111. .response { resp in
  112. response = resp
  113. expectation.fulfill()
  114. }
  115. waitForExpectations(timeout: timeout)
  116. // Then
  117. XCTAssertNotNil(response?.request)
  118. XCTAssertNotNil(response?.response)
  119. XCTAssertNotNil(response?.data)
  120. XCTAssertNil(response?.error)
  121. XCTAssertEqual(response?.response?.headers["Request-Header"], "foobar")
  122. XCTAssertEqual(response?.response?.headers["Session-Configuration-Header"], "foo")
  123. }
  124. }