|
| 1 | +// This source file is part of the Swift.org open source project |
| 2 | +// |
| 3 | +// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors |
| 4 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 5 | +// |
| 6 | +// See http://swift.org/LICENSE.txt for license information |
| 7 | +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 8 | +// |
| 9 | +#if DEPLOYMENT_RUNTIME_OBJC || os(Linux) |
| 10 | +import Foundation |
| 11 | +import XCTest |
| 12 | +#else |
| 13 | +import SwiftFoundation |
| 14 | +import SwiftXCTest |
| 15 | +#endif |
| 16 | + |
| 17 | +class TestNSURLProtocol : XCTestCase { |
| 18 | + |
| 19 | + static var serverPort: Int = -1 |
| 20 | + |
| 21 | + static var allTests: [(String, (TestNSURLProtocol) -> () throws -> Void)] { |
| 22 | + return [ |
| 23 | + ("test_InterceptResponse", test_InterceptResponse), |
| 24 | + ("test_InterceptRequest", test_InterceptRequest), |
| 25 | + ("test_protocols", test_protocols), |
| 26 | + ("test_customProtocolResponseWithDelegate", test_customProtocolResponseWithDelegate), |
| 27 | + ("test_customProtocolSetDataInResponseWithDelegate", test_customProtocolSetDataInResponseWithDelegate), |
| 28 | + ] |
| 29 | + } |
| 30 | + |
| 31 | + override class func setUp() { |
| 32 | + super.setUp() |
| 33 | + func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { |
| 34 | + let start = 21961 |
| 35 | + for port in start...(start+100) { //we must find at least one port to bind |
| 36 | + do { |
| 37 | + serverPort = port |
| 38 | + let test = try TestURLSessionServer(port: UInt16(port), startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks) |
| 39 | + try test.start(started: condition) |
| 40 | + try test.readAndRespond() |
| 41 | + test.stop() |
| 42 | + } catch let e as ServerError { |
| 43 | + if e.operation == "bind" { continue } |
| 44 | + throw e |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + let serverReady = ServerSemaphore() |
| 50 | + globalDispatchQueue.async { |
| 51 | + do { |
| 52 | + try runServer(with: serverReady) |
| 53 | + |
| 54 | + } catch { |
| 55 | + XCTAssertTrue(true) |
| 56 | + return |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + serverReady.wait() |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | + func test_InterceptResponse() { |
| 65 | + let urlString = "http://127.0.0.1:\(TestNSURLProtocol.serverPort)/USA" |
| 66 | + let url = URL(string: urlString)! |
| 67 | + let config = URLSessionConfiguration.default |
| 68 | + config.protocolClasses = [CustomProtocol.self] |
| 69 | + config.timeoutIntervalForRequest = 8 |
| 70 | + let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) |
| 71 | + let expect = expectation(description: "GET \(urlString): with a custom protocol") |
| 72 | + let task = session.dataTask(with: url) { data, response, error in |
| 73 | + defer { expect.fulfill() } |
| 74 | + if let e = error as? URLError { |
| 75 | + XCTAssertEqual(e.code, .timedOut, "Unexpected error code") |
| 76 | + return |
| 77 | + } |
| 78 | + let httpResponse = response as! HTTPURLResponse? |
| 79 | + XCTAssertEqual(429, httpResponse!.statusCode, "HTTP response code is not 429") |
| 80 | + } |
| 81 | + task.resume() |
| 82 | + waitForExpectations(timeout: 12) |
| 83 | + } |
| 84 | + |
| 85 | + func test_InterceptRequest() { |
| 86 | + let urlString = "ssh://127.0.0.1:\(TestNSURLProtocol.serverPort)/USA" |
| 87 | + let url = URL(string: urlString)! |
| 88 | + let config = URLSessionConfiguration.default |
| 89 | + config.protocolClasses = [InterceptableRequest.self] |
| 90 | + config.timeoutIntervalForRequest = 8 |
| 91 | + let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) |
| 92 | + let expect = expectation(description: "GET \(urlString): with a custom protocol") |
| 93 | + let task = session.dataTask(with: url) { data, response, error in |
| 94 | + defer { expect.fulfill() } |
| 95 | + if let e = error as? URLError { |
| 96 | + XCTAssertEqual(e.code, .timedOut, "Unexpected error code") |
| 97 | + return |
| 98 | + } |
| 99 | + let httpResponse = response as! HTTPURLResponse? |
| 100 | + let responseURL = URL(string: "http://google.com") |
| 101 | + XCTAssertEqual(responseURL, httpResponse?.url, "Unexpected url") |
| 102 | + XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200") |
| 103 | + } |
| 104 | + task.resume() |
| 105 | + waitForExpectations(timeout: 12) |
| 106 | + } |
| 107 | + |
| 108 | + func test_protocols() { |
| 109 | + let urlString = "http://127.0.0.1:\(TestNSURLProtocol.serverPort)/Nepal" |
| 110 | + let url = URL(string: urlString)! |
| 111 | + let config = URLSessionConfiguration.default |
| 112 | + config.protocolClasses = [InterceptableRequest.self, CustomProtocol.self] |
| 113 | + let expect = expectation(description: "GET \(urlString): with a custom protocol") |
| 114 | + let session = URLSession(configuration: config) |
| 115 | + let task = session.dataTask(with: url) { data, response, error in |
| 116 | + defer { expect.fulfill() } |
| 117 | + if let e = error as? URLError { |
| 118 | + XCTAssertEqual(e.code, .timedOut, "Unexpected error code") |
| 119 | + return |
| 120 | + } |
| 121 | + let httpResponse = response as! HTTPURLResponse |
| 122 | + print(httpResponse.statusCode) |
| 123 | + XCTAssertEqual(429, httpResponse.statusCode, "Status code is not 429") |
| 124 | + } |
| 125 | + task.resume() |
| 126 | + waitForExpectations(timeout: 12) |
| 127 | + } |
| 128 | + |
| 129 | + func test_customProtocolResponseWithDelegate() { |
| 130 | + let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru" |
| 131 | + let url = URL(string: urlString)! |
| 132 | + let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self]) |
| 133 | + d.responseReceivedExpectation = expectation(description: "GET \(urlString): response received") |
| 134 | + d.run(with: url) |
| 135 | + waitForExpectations(timeout: 12) |
| 136 | + } |
| 137 | + |
| 138 | + func test_customProtocolSetDataInResponseWithDelegate() { |
| 139 | + let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal" |
| 140 | + let url = URL(string: urlString)! |
| 141 | + let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self]) |
| 142 | + d.run(with: url) |
| 143 | + waitForExpectations(timeout: 12) |
| 144 | + if !d.error { |
| 145 | + XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result") |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +class InterceptableRequest : URLProtocol { |
| 151 | + |
| 152 | + override class func canInit(with request: URLRequest) -> Bool { |
| 153 | + return request.url?.scheme == "ssh" |
| 154 | + } |
| 155 | + |
| 156 | + override class func canonicalRequest(for request: URLRequest) -> URLRequest { |
| 157 | + return request |
| 158 | + } |
| 159 | + |
| 160 | + override func startLoading() { |
| 161 | + let urlString = "http://google.com" |
| 162 | + let url = URL(string: urlString)! |
| 163 | + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:]) |
| 164 | + self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) |
| 165 | + self.client?.urlProtocolDidFinishLoading(self) |
| 166 | + |
| 167 | + } |
| 168 | + |
| 169 | + override func stopLoading() { |
| 170 | + return |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +class CustomProtocol : URLProtocol { |
| 175 | + |
| 176 | + override class func canInit(with request: URLRequest) -> Bool { |
| 177 | + return true |
| 178 | + } |
| 179 | + |
| 180 | + func sendResponse(statusCode: Int, headers: [String: String] = [:], data: Data) { |
| 181 | + let response = HTTPURLResponse(url: self.request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers) |
| 182 | + let capital = "Kathmandu" |
| 183 | + let data = capital.data(using: String.Encoding.utf8) |
| 184 | + self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) |
| 185 | + self.client?.urlProtocol(self, didLoad: data!) |
| 186 | + self.client?.urlProtocolDidFinishLoading(self) |
| 187 | + } |
| 188 | + |
| 189 | + override class func canonicalRequest(for request: URLRequest) -> URLRequest { |
| 190 | + return request |
| 191 | + } |
| 192 | + |
| 193 | + override func startLoading() { |
| 194 | + sendResponse(statusCode: 429, data: Data()) |
| 195 | + } |
| 196 | + |
| 197 | + override func stopLoading() { |
| 198 | + return |
| 199 | + } |
| 200 | +} |
0 commit comments