Skip to content

Commit 69db9d9

Browse files
committed
Separate test-suite for URLProtocol
1 parent 680225c commit 69db9d9

File tree

4 files changed

+205
-58
lines changed

4 files changed

+205
-58
lines changed

Foundation.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

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

480481
/* Begin PBXFileReference section */
481482
0383A1741D2E558A0052E5D1 /* TestNSStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSStream.swift; sourceTree = "<group>"; };
483+
03B6F5831F15F339004F25AF /* TestNSURLProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestNSURLProtocol.swift; sourceTree = "<group>"; };
482484
1520469A1D8AEABE00D02E36 /* HTTPServer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPServer.swift; sourceTree = "<group>"; };
483485
159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestNSHTTPCookieStorage.swift; sourceTree = "<group>"; };
484486
22B9C1E01C165D7A00DECFF9 /* TestNSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDate.swift; sourceTree = "<group>"; };
@@ -1484,6 +1486,7 @@
14841486
CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */,
14851487
D4FE895A1D703D1100DA7986 /* TestURLRequest.swift */,
14861488
5B6F17961C48631C00935030 /* TestUtils.swift */,
1489+
03B6F5831F15F339004F25AF /* TestNSURLProtocol.swift */,
14871490
);
14881491
name = Tests;
14891492
sourceTree = "<group>";
@@ -2372,6 +2375,7 @@
23722375
BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */,
23732376
63DCE9D41EAA432400E9CB02 /* TestISO8601DateFormatter.swift in Sources */,
23742377
EA01AAEC1DA839C4008F4E07 /* TestProgress.swift in Sources */,
2378+
03B6F5841F15F339004F25AF /* TestNSURLProtocol.swift in Sources */,
23752379
5B13B3411C582D4C00651CE2 /* TestNSRegularExpression.swift in Sources */,
23762380
5B13B3491C582D4C00651CE2 /* TestNSTimeZone.swift in Sources */,
23772381
5B13B34B1C582D4C00651CE2 /* TestNSURLRequest.swift in Sources */,
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
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+
}

TestFoundation/TestNSURLSession.swift

Lines changed: 0 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@ class TestURLSession : XCTestCase {
3737
("test_verifyRequestHeaders", test_verifyRequestHeaders),
3838
("test_verifyHttpAdditionalHeaders", test_verifyHttpAdditionalHeaders),
3939
("test_timeoutInterval", test_timeoutInterval),
40-
("test_customProtocol", test_customProtocol),
41-
("test_customProtocolResponseWithDelegate", test_customProtocolResponseWithDelegate),
4240
("test_httpRedirection", test_httpRedirection),
4341
("test_httpRedirectionTimeout", test_httpRedirectionTimeout),
4442
("test_http0_9SimpleResponses", test_http0_9SimpleResponses),
@@ -338,37 +336,6 @@ class TestURLSession : XCTestCase {
338336
waitForExpectations(timeout: 30)
339337
}
340338

341-
func test_customProtocol () {
342-
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/USA"
343-
let url = URL(string: urlString)!
344-
let config = URLSessionConfiguration.default
345-
config.protocolClasses = [CustomProtocol.self]
346-
config.timeoutIntervalForRequest = 8
347-
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
348-
let expect = expectation(description: "GET \(urlString): with a custom protocol")
349-
350-
let task = session.dataTask(with: url) { data, response, error in
351-
defer { expect.fulfill() }
352-
if let e = error as? URLError {
353-
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
354-
return
355-
}
356-
let httpResponse = response as! HTTPURLResponse?
357-
XCTAssertEqual(429, httpResponse!.statusCode, "HTTP response code is not 429")
358-
}
359-
task.resume()
360-
waitForExpectations(timeout: 12)
361-
}
362-
363-
func test_customProtocolResponseWithDelegate() {
364-
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
365-
let url = URL(string: urlString)!
366-
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
367-
d.responseReceivedExpectation = expectation(description: "GET \(urlString): response received")
368-
d.run(with: url)
369-
waitForExpectations(timeout: 12)
370-
}
371-
372339
func test_httpRedirection() {
373340
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/UnitedStates"
374341
let url = URL(string: urlString)!
@@ -629,31 +596,6 @@ extension DownloadTask : URLSessionTaskDelegate {
629596
}
630597
}
631598

632-
class CustomProtocol : URLProtocol {
633-
634-
override class func canInit(with request: URLRequest) -> Bool {
635-
return true
636-
}
637-
638-
func sendResponse(statusCode: Int, headers: [String: String] = [:], data: Data) {
639-
let response = HTTPURLResponse(url: self.request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)
640-
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
641-
self.client?.urlProtocolDidFinishLoading(self)
642-
}
643-
644-
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
645-
return request
646-
}
647-
648-
override func startLoading() {
649-
sendResponse(statusCode: 429, data: Data())
650-
}
651-
652-
override func stopLoading() {
653-
return
654-
}
655-
}
656-
657599
class HTTPRedirectionDataTask : NSObject {
658600
let dataTaskExpectation: XCTestExpectation!
659601
var session: URLSession! = nil

TestFoundation/main.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ XCTMain([
8181
testCase(TestNSURL.allTests),
8282
testCase(TestNSURLComponents.allTests),
8383
testCase(TestNSURLCredential.allTests),
84+
testCase(TestNSURLProtocol.allTests),
8485
testCase(TestNSURLRequest.allTests),
8586
testCase(TestURLRequest.allTests),
8687
testCase(TestNSURLResponse.allTests),

0 commit comments

Comments
 (0)