Skip to content

Separate test-suite for URLProtocol #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Foundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

/* Begin PBXBuildFile section */
0383A1751D2E558A0052E5D1 /* TestNSStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0383A1741D2E558A0052E5D1 /* TestNSStream.swift */; };
03B6F5841F15F339004F25AF /* TestNSURLProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03B6F5831F15F339004F25AF /* TestNSURLProtocol.swift */; };
1520469B1D8AEABE00D02E36 /* HTTPServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1520469A1D8AEABE00D02E36 /* HTTPServer.swift */; };
159884921DCC877700E3314C /* TestNSHTTPCookieStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */; };
231503DB1D8AEE5D0061694D /* TestNSDecimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */; };
Expand Down Expand Up @@ -479,6 +480,7 @@

/* Begin PBXFileReference section */
0383A1741D2E558A0052E5D1 /* TestNSStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSStream.swift; sourceTree = "<group>"; };
03B6F5831F15F339004F25AF /* TestNSURLProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestNSURLProtocol.swift; sourceTree = "<group>"; };
1520469A1D8AEABE00D02E36 /* HTTPServer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPServer.swift; sourceTree = "<group>"; };
159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestNSHTTPCookieStorage.swift; sourceTree = "<group>"; };
22B9C1E01C165D7A00DECFF9 /* TestNSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDate.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1484,6 +1486,7 @@
CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */,
D4FE895A1D703D1100DA7986 /* TestURLRequest.swift */,
5B6F17961C48631C00935030 /* TestUtils.swift */,
03B6F5831F15F339004F25AF /* TestNSURLProtocol.swift */,
);
name = Tests;
sourceTree = "<group>";
Expand Down Expand Up @@ -2372,6 +2375,7 @@
BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */,
63DCE9D41EAA432400E9CB02 /* TestISO8601DateFormatter.swift in Sources */,
EA01AAEC1DA839C4008F4E07 /* TestProgress.swift in Sources */,
03B6F5841F15F339004F25AF /* TestNSURLProtocol.swift in Sources */,
5B13B3411C582D4C00651CE2 /* TestNSRegularExpression.swift in Sources */,
5B13B3491C582D4C00651CE2 /* TestNSTimeZone.swift in Sources */,
5B13B34B1C582D4C00651CE2 /* TestNSURLRequest.swift in Sources */,
Expand Down
38 changes: 38 additions & 0 deletions TestFoundation/HTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ import Dispatch
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import Glibc
import XCTest
#else
import CoreFoundation
import SwiftFoundation
import Darwin
import SwiftXCTest
#endif

public let globalDispatchQueue = DispatchQueue.global()
Expand Down Expand Up @@ -394,3 +396,39 @@ public class ServerSemaphore {
dispatchSemaphore.signal()
}
}

class LoopbackServerTest : XCTestCase {
static var serverPort: Int = -1

override class func setUp() {
super.setUp()
func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
let start = 21961
for port in start...(start+100) { //we must find at least one port to bind
do {
serverPort = port
let test = try TestURLSessionServer(port: UInt16(port), startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks)
try test.start(started: condition)
try test.readAndRespond()
test.stop()
} catch let e as ServerError {
if e.operation == "bind" { continue }
throw e
}
}
}

let serverReady = ServerSemaphore()
globalDispatchQueue.async {
do {
try runServer(with: serverReady)

} catch {
XCTAssertTrue(true)
return
}
}

serverReady.wait()
}
}
165 changes: 165 additions & 0 deletions TestFoundation/TestNSURLProtocol.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif

class TestNSURLProtocol : LoopbackServerTest {

static var allTests: [(String, (TestNSURLProtocol) -> () throws -> Void)] {
return [
("test_interceptResponse", test_interceptResponse),
("test_interceptRequest", test_interceptRequest),
("test_multipleCustomProtocols", test_multipleCustomProtocols),
("test_customProtocolResponseWithDelegate", test_customProtocolResponseWithDelegate),
("test_customProtocolSetDataInResponseWithDelegate", test_customProtocolSetDataInResponseWithDelegate),
]
}

func test_interceptResponse() {
let urlString = "http://127.0.0.1:\(TestNSURLProtocol.serverPort)/USA"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomProtocol.self]
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse?
XCTAssertEqual(429, httpResponse!.statusCode, "HTTP response code is not 429")
}
task.resume()
waitForExpectations(timeout: 12)
}

func test_interceptRequest() {
let urlString = "ssh://127.0.0.1:\(TestNSURLProtocol.serverPort)/USA"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [InterceptableRequest.self]
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse?
let responseURL = URL(string: "http://google.com")
XCTAssertEqual(responseURL, httpResponse?.url, "Unexpected url")
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 12)
}

func test_multipleCustomProtocols() {
let urlString = "http://127.0.0.1:\(TestNSURLProtocol.serverPort)/Nepal"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [InterceptableRequest.self, CustomProtocol.self]
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let session = URLSession(configuration: config)
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse
print(httpResponse.statusCode)
XCTAssertEqual(429, httpResponse.statusCode, "Status code is not 429")
}
task.resume()
waitForExpectations(timeout: 12)
}

func test_customProtocolResponseWithDelegate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
d.responseReceivedExpectation = expectation(description: "GET \(urlString): response received")
d.run(with: url)
waitForExpectations(timeout: 12)
}

func test_customProtocolSetDataInResponseWithDelegate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
d.run(with: url)
waitForExpectations(timeout: 12)
if !d.error {
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
}
}
}

class InterceptableRequest : URLProtocol {

override class func canInit(with request: URLRequest) -> Bool {
return request.url?.scheme == "ssh"
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override func startLoading() {
let urlString = "http://google.com"
let url = URL(string: urlString)!
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocolDidFinishLoading(self)

}

override func stopLoading() {
return
}
}

class CustomProtocol : URLProtocol {

override class func canInit(with request: URLRequest) -> Bool {
return true
}

func sendResponse(statusCode: Int, headers: [String: String] = [:], data: Data) {
let response = HTTPURLResponse(url: self.request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)
let capital = "Kathmandu"
let data = capital.data(using: String.Encoding.utf8)
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocol(self, didLoad: data!)
self.client?.urlProtocolDidFinishLoading(self)
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override func startLoading() {
sendResponse(statusCode: 429, data: Data())
}

override func stopLoading() {
return
}
}
94 changes: 1 addition & 93 deletions TestFoundation/TestNSURLSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@
import SwiftXCTest
#endif

class TestURLSession : XCTestCase {

static var serverPort: Int = -1
class TestURLSession : LoopbackServerTest {

static var allTests: [(String, (TestURLSession) -> () throws -> Void)] {
return [
Expand All @@ -37,8 +35,6 @@ class TestURLSession : XCTestCase {
("test_verifyRequestHeaders", test_verifyRequestHeaders),
("test_verifyHttpAdditionalHeaders", test_verifyHttpAdditionalHeaders),
("test_timeoutInterval", test_timeoutInterval),
("test_customProtocol", test_customProtocol),
("test_customProtocolResponseWithDelegate", test_customProtocolResponseWithDelegate),
("test_httpRedirection", test_httpRedirection),
("test_httpRedirectionTimeout", test_httpRedirectionTimeout),
("test_http0_9SimpleResponses", test_http0_9SimpleResponses),
Expand All @@ -48,38 +44,6 @@ class TestURLSession : XCTestCase {
]
}

override class func setUp() {
super.setUp()
func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
let start = 21961
for port in start...(start+100) { //we must find at least one port to bind
do {
serverPort = port
let test = try TestURLSessionServer(port: UInt16(port), startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks)
try test.start(started: condition)
try test.readAndRespond()
test.stop()
} catch let e as ServerError {
if e.operation == "bind" { continue }
throw e
}
}
}

let serverReady = ServerSemaphore()
globalDispatchQueue.async {
do {
try runServer(with: serverReady)

} catch {
XCTAssertTrue(true)
return
}
}

serverReady.wait()
}

func test_dataTaskWithURL() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let url = URL(string: urlString)!
Expand Down Expand Up @@ -338,37 +302,6 @@ class TestURLSession : XCTestCase {
waitForExpectations(timeout: 30)
}

func test_customProtocol () {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/USA"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomProtocol.self]
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a custom protocol")

let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse?
XCTAssertEqual(429, httpResponse!.statusCode, "HTTP response code is not 429")
}
task.resume()
waitForExpectations(timeout: 12)
}

func test_customProtocolResponseWithDelegate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
d.responseReceivedExpectation = expectation(description: "GET \(urlString): response received")
d.run(with: url)
waitForExpectations(timeout: 12)
}

func test_httpRedirection() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
let url = URL(string: urlString)!
Expand Down Expand Up @@ -629,31 +562,6 @@ extension DownloadTask : URLSessionTaskDelegate {
}
}

class CustomProtocol : URLProtocol {

override class func canInit(with request: URLRequest) -> Bool {
return true
}

func sendResponse(statusCode: Int, headers: [String: String] = [:], data: Data) {
let response = HTTPURLResponse(url: self.request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocolDidFinishLoading(self)
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override func startLoading() {
sendResponse(statusCode: 429, data: Data())
}

override func stopLoading() {
return
}
}

class HTTPRedirectionDataTask : NSObject {
let dataTaskExpectation: XCTestExpectation!
var session: URLSession! = nil
Expand Down
1 change: 1 addition & 0 deletions TestFoundation/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ XCTMain([
testCase(TestNSURL.allTests),
testCase(TestNSURLComponents.allTests),
testCase(TestNSURLCredential.allTests),
testCase(TestNSURLProtocol.allTests),
testCase(TestNSURLRequest.allTests),
testCase(TestURLRequest.allTests),
testCase(TestNSURLResponse.allTests),
Expand Down