URLProtocolTests.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. 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
  65. // Hopefully will be fixed in a future seed
  66. // URLProtocol had some API's that didnt make the value type conversion
  67. let mutableRequest = (request.urlRequest as NSURLRequest).mutableCopy() as! NSMutableURLRequest
  68. URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: mutableRequest)
  69. activeTask = session.dataTask(with: mutableRequest as URLRequest)
  70. activeTask?.resume()
  71. }
  72. override func stopLoading() {
  73. activeTask?.cancel()
  74. }
  75. }
  76. // MARK: -
  77. extension ProxyURLProtocol: URLSessionDelegate {
  78. // MARK: NSURLSessionDelegate
  79. func URLSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data) {
  80. client?.urlProtocol(self, didLoad: data)
  81. }
  82. func URLSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  83. if let response = task.response {
  84. client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  85. }
  86. client?.urlProtocolDidFinishLoading(self)
  87. }
  88. }
  89. // MARK: -
  90. class URLProtocolTestCase: BaseTestCase {
  91. var manager: SessionManager!
  92. // MARK: Setup and Teardown
  93. override func setUp() {
  94. super.setUp()
  95. manager = {
  96. let configuration: URLSessionConfiguration = {
  97. let configuration = URLSessionConfiguration.default
  98. configuration.protocolClasses = [ProxyURLProtocol.self]
  99. configuration.httpAdditionalHeaders = ["session-configuration-header": "foo"]
  100. return configuration
  101. }()
  102. return SessionManager(configuration: configuration)
  103. }()
  104. }
  105. // MARK: Tests
  106. func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
  107. // Given
  108. let urlString = "https://httpbin.org/response-headers"
  109. let url = URL(string: urlString)!
  110. var urlRequest = URLRequest(url: url)
  111. urlRequest.httpMethod = HTTPMethod.get.rawValue
  112. urlRequest.setValue("foobar", forHTTPHeaderField: "request-header")
  113. let expectation = self.expectation(description: "GET request should succeed")
  114. var response: DefaultDataResponse?
  115. // When
  116. manager.request(urlRequest)
  117. .response { resp in
  118. response = resp
  119. expectation.fulfill()
  120. }
  121. waitForExpectations(timeout: timeout, handler: nil)
  122. // Then
  123. XCTAssertNotNil(response?.request)
  124. XCTAssertNotNil(response?.response)
  125. XCTAssertNotNil(response?.data)
  126. XCTAssertNil(response?.error)
  127. if let headers = response?.response?.allHeaderFields {
  128. XCTAssertEqual(headers["request-header"] as? String, "foobar")
  129. XCTAssertEqual(headers["session-configuration-header"] as? String, "foo")
  130. } else {
  131. XCTFail("headers should not be nil")
  132. }
  133. }
  134. }