URLProtocolTests.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  39. return session
  40. }()
  41. weak 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. false
  61. }
  62. // MARK: Loading Methods
  63. override func startLoading() {
  64. // rdar://26849668 - URLProtocol had some API's that didn't 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: (any 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.headers["Session-Configuration-Header"] = "foo"
  98. return configuration
  99. }()
  100. return Session(configuration: configuration)
  101. }()
  102. }
  103. // MARK: Tests
  104. @MainActor
  105. func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
  106. // Given
  107. let endpoint = Endpoint.responseHeaders.modifying(\.headers, to: ["Request-Header": "foobar"])
  108. let expectation = expectation(description: "GET request should succeed")
  109. var response: DataResponse<Data?, AFError>?
  110. // When
  111. manager.request(endpoint)
  112. .response { resp in
  113. response = resp
  114. expectation.fulfill()
  115. }
  116. waitForExpectations(timeout: timeout)
  117. // Then
  118. XCTAssertNotNil(response?.request)
  119. XCTAssertNotNil(response?.response)
  120. XCTAssertNotNil(response?.data)
  121. XCTAssertNil(response?.error)
  122. XCTAssertEqual(response?.response?.headers["Request-Header"], "foobar")
  123. XCTAssertEqual(response?.response?.headers["Session-Configuration-Header"], "foo")
  124. }
  125. }