Skip to content

Commit 25467eb

Browse files
author
Pushkar N Kulkarni
committed
Loopback tests for URLSession
1 parent 58b375f commit 25467eb

File tree

2 files changed

+73
-26
lines changed

2 files changed

+73
-26
lines changed

TestFoundation/TestNSURLSession.swift

Lines changed: 70 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ import XCTest
1515
import SwiftFoundation
1616
import SwiftXCTest
1717
#endif
18+
import Dispatch
1819

1920
class TestURLSession : XCTestCase {
2021

22+
var serverPort: Int = -1
23+
2124
static var allTests: [(String, (TestURLSession) -> () throws -> Void)] {
2225
return [
2326
("test_dataTaskWithURL", test_dataTaskWithURL),
@@ -32,8 +35,35 @@ class TestURLSession : XCTestCase {
3235
]
3336
}
3437

38+
private func runServer(with condition: DispatchSemaphore) throws {
39+
let start = 21961
40+
for port in start...(start+100) { //we must find at least one port to bind
41+
do {
42+
serverPort = port
43+
let test = try TestURLSessionServer(port: UInt16(port))
44+
try test.start(started: condition)
45+
try test.readAndRespond()
46+
test.stop()
47+
} catch let e as ServerError {
48+
if e.operation != "bind" { continue }
49+
throw e
50+
}
51+
}
52+
}
53+
3554
func test_dataTaskWithURL() {
36-
let urlString = "https://restcountries.eu/rest/v1/name/Nepal?fullText=true"
55+
let serverReady = DispatchSemaphore(value: 0)
56+
let queue = DispatchQueue.global()
57+
queue.async {
58+
do {
59+
try self.runServer(with: serverReady)
60+
} catch {
61+
XCTAssertTrue(true)
62+
return
63+
}
64+
}
65+
serverReady.wait()
66+
let urlString = "http://127.0.0.1:\(serverPort)/Nepal"
3767
let url = URL(string: urlString)!
3868
let d = DataTask(with: expectation(description: "data task"))
3969
d.run(with: url)
@@ -44,7 +74,18 @@ class TestURLSession : XCTestCase {
4474
}
4575

4676
func test_dataTaskWithURLCompletionHandler() {
47-
let urlString = "https://restcountries.eu/rest/v1/name/USA?fullText=true"
77+
let serverReady = DispatchSemaphore(value: 0)
78+
let queue = DispatchQueue.global()
79+
queue.async {
80+
do {
81+
try self.runServer(with: serverReady)
82+
} catch {
83+
XCTAssertTrue(true)
84+
return
85+
}
86+
}
87+
serverReady.wait()
88+
let urlString = "http://127.0.0.1:\(serverPort)/USA"
4889
let url = URL(string: urlString)!
4990
let config = URLSessionConfiguration.default
5091
config.timeoutIntervalForRequest = 8
@@ -60,13 +101,7 @@ class TestURLSession : XCTestCase {
60101

61102
let httpResponse = response as! HTTPURLResponse?
62103
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
63-
do {
64-
let json = try JSONSerialization.jsonObject(with: data!, options: [])
65-
let arr = json as? Array<Any>
66-
let first = arr![0]
67-
let result = first as? [String : Any]
68-
expectedResult = result!["capital"] as! String
69-
} catch { }
104+
expectedResult = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!._bridgeToSwift()
70105
XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value")
71106
expect.fulfill()
72107
}
@@ -75,7 +110,18 @@ class TestURLSession : XCTestCase {
75110
}
76111

77112
func test_dataTaskWithURLRequest() {
78-
let urlString = "https://restcountries.eu/rest/v1/name/Peru?fullText=true"
113+
let serverReady = DispatchSemaphore(value: 0)
114+
let queue = DispatchQueue.global()
115+
queue.async {
116+
do {
117+
try self.runServer(with: serverReady)
118+
} catch {
119+
XCTAssertTrue(true)
120+
return
121+
}
122+
}
123+
serverReady.wait()
124+
let urlString = "http://127.0.0.1:\(serverPort)/Peru"
79125
let urlRequest = URLRequest(url: URL(string: urlString)!)
80126
let d = DataTask(with: expectation(description: "data task"))
81127
d.run(with: urlRequest)
@@ -86,7 +132,18 @@ class TestURLSession : XCTestCase {
86132
}
87133

88134
func test_dataTaskWithURLRequestCompletionHandler() {
89-
let urlString = "https://restcountries.eu/rest/v1/name/Italy?fullText=true"
135+
let serverReady = DispatchSemaphore(value: 0)
136+
let queue = DispatchQueue.global()
137+
queue.async {
138+
do {
139+
try self.runServer(with: serverReady)
140+
} catch {
141+
XCTAssertTrue(true)
142+
return
143+
}
144+
}
145+
serverReady.wait()
146+
let urlString = "http://127.0.0.1:\(serverPort)/Italy"
90147
let urlRequest = URLRequest(url: URL(string: urlString)!)
91148
let config = URLSessionConfiguration.default
92149
config.timeoutIntervalForRequest = 8
@@ -101,13 +158,7 @@ class TestURLSession : XCTestCase {
101158
}
102159
let httpResponse = response as! HTTPURLResponse?
103160
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
104-
do {
105-
let json = try JSONSerialization.jsonObject(with: data!, options: [])
106-
let arr = json as? Array<Any>
107-
let first = arr![0]
108-
let result = first as? [String : Any]
109-
expectedResult = result!["capital"] as! String
110-
} catch { }
161+
expectedResult = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!._bridgeToSwift()
111162
XCTAssertEqual("Rome", expectedResult, "Did not receive expected value")
112163
expect.fulfill()
113164
}
@@ -194,14 +245,7 @@ class DataTask: NSObject {
194245

195246
extension DataTask : URLSessionDataDelegate {
196247
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
197-
do {
198-
let json = try JSONSerialization.jsonObject(with: data, options: [])
199-
let arr = json as? Array<Any>
200-
let first = arr![0]
201-
let result = first as? [String : Any]
202-
capital = result!["capital"] as! String
203-
} catch { }
204-
248+
capital = NSString(data: data, encoding: String.Encoding.utf8.rawValue)!._bridgeToSwift()
205249
dataTaskExpectation.fulfill()
206250
}
207251
}

build.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,8 +458,11 @@
458458
# TODO: Probably this should be another 'product', but for now it's simply a phase
459459
foundation_tests = SwiftExecutable('TestFoundation', [
460460
'TestFoundation/main.swift',
461+
'TestFoundation/HTTPServer.swift',
461462
] + glob.glob('./TestFoundation/Test*.swift')) # all TestSomething.swift are considered sources to the test project in the TestFoundation directory
462463

464+
Configuration.current.extra_ld_flags = '-L'+Configuration.current.variables["LIBDISPATCH_BUILD_DIR"]+'/src/.libs'
465+
463466
foundation_tests.add_dependency(foundation_tests_resources)
464467
foundation.add_phase(foundation_tests_resources)
465468
foundation.add_phase(foundation_tests)

0 commit comments

Comments
 (0)