Skip to content

Commit 1f745ce

Browse files
Pushkar Kulkarniswizzlr
Pushkar Kulkarni
authored andcommitted
test for 915
1 parent 7f7f2bc commit 1f745ce

File tree

2 files changed

+110
-20
lines changed

2 files changed

+110
-20
lines changed

TestFoundation/HTTPServer.swift

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,14 @@ struct _HTTPRequest {
152152
body = lines.last!
153153
}
154154

155+
public func getCommaSeparatedHeaders() -> String {
156+
var allHeaders = ""
157+
for header in headers {
158+
allHeaders += header + ","
159+
}
160+
return allHeaders
161+
}
162+
155163
}
156164

157165
struct _HTTPResponse {
@@ -195,18 +203,24 @@ public class TestURLSessionServer {
195203
}
196204

197205
func process(request: _HTTPRequest) -> _HTTPResponse {
198-
if request.method == .GET {
199-
return getResponse(uri: request.uri)
206+
if request.method == .GET || request.method == .POST {
207+
return getResponse(request: request)
200208
} else {
201209
fatalError("Unsupported method!")
202210
}
203211
}
204212

205-
func getResponse(uri: String) -> _HTTPResponse {
213+
func getResponse(request: _HTTPRequest) -> _HTTPResponse {
214+
let uri = request.uri
206215
if uri == "/country.txt" {
207216
let text = capitals[String(uri.characters.dropFirst())]!
208217
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
209218
}
219+
220+
if uri == "/requestHeaders" {
221+
let text = request.getCommaSeparatedHeaders()
222+
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
223+
}
210224
return _HTTPResponse(response: .OK, body: capitals[String(uri.characters.dropFirst())]!)
211225
}
212226

TestFoundation/TestNSURLSession.swift

Lines changed: 93 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ class TestURLSession : XCTestCase {
3232
("test_finishTaskAndInvalidate", test_finishTasksAndInvalidate),
3333
("test_taskError", test_taskError),
3434
("test_taskCopy", test_taskCopy),
35+
("test_cancelTask", test_cancelTask),
36+
("test_taskTimeout", test_taskTimeout),
37+
("test_verifyRequestHeaders", test_verifyRequestHeaders),
3538
]
3639
}
3740

@@ -64,22 +67,22 @@ class TestURLSession : XCTestCase {
6467
serverReady.wait()
6568
let urlString = "http://127.0.0.1:\(serverPort)/Nepal"
6669
let url = URL(string: urlString)!
67-
let d = DataTask(with: expectation(description: "data task"))
70+
let d = DataTask(with: expectation(description: "data task"))
6871
d.run(with: url)
6972
waitForExpectations(timeout: 12)
7073
if !d.error {
7174
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
7275
}
7376
}
74-
77+
7578
func test_dataTaskWithURLCompletionHandler() {
7679
let serverReady = ServerSemaphore()
7780
globalDispatchQueue.async {
7881
do {
7982
try self.runServer(with: serverReady)
8083
} catch {
8184
XCTAssertTrue(true)
82-
return
85+
return
8386
}
8487
}
8588
serverReady.wait()
@@ -98,7 +101,7 @@ class TestURLSession : XCTestCase {
98101
}
99102

100103
let httpResponse = response as! HTTPURLResponse?
101-
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
104+
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
102105
expectedResult = String(data: data!, encoding: String.Encoding.utf8)!
103106
XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value")
104107
expect.fulfill()
@@ -120,7 +123,7 @@ class TestURLSession : XCTestCase {
120123
serverReady.wait()
121124
let urlString = "http://127.0.0.1:\(serverPort)/Peru"
122125
let urlRequest = URLRequest(url: URL(string: urlString)!)
123-
let d = DataTask(with: expectation(description: "data task"))
126+
let d = DataTask(with: expectation(description: "data task"))
124127
d.run(with: urlRequest)
125128
waitForExpectations(timeout: 12)
126129
if !d.error {
@@ -174,7 +177,7 @@ class TestURLSession : XCTestCase {
174177
}
175178
serverReady.wait()
176179
let urlString = "http://127.0.0.1:\(serverPort)/country.txt"
177-
let url = URL(string: urlString)!
180+
let url = URL(string: urlString)!
178181
let d = DownloadTask(with: expectation(description: "download task with delegate"))
179182
d.run(with: url)
180183
waitForExpectations(timeout: 12)
@@ -249,7 +252,7 @@ class TestURLSession : XCTestCase {
249252
task.resume()
250253
waitForExpectations(timeout: 12)
251254
}
252-
255+
253256
func test_finishTasksAndInvalidate() {
254257
let invalidateExpectation = expectation(description: "URLSession wasn't invalidated")
255258
let delegate = SessionDelegate(invalidateExpectation: invalidateExpectation)
@@ -264,7 +267,7 @@ class TestURLSession : XCTestCase {
264267
session.finishTasksAndInvalidate()
265268
waitForExpectations(timeout: 12)
266269
}
267-
270+
268271
func test_taskError() {
269272
let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")!
270273
let session = URLSession(configuration: URLSessionConfiguration.default,
@@ -279,24 +282,97 @@ class TestURLSession : XCTestCase {
279282
}
280283
//should result in Bad URL error
281284
task.resume()
282-
285+
283286
waitForExpectations(timeout: 5) { error in
284287
XCTAssertNil(error)
285-
288+
286289
XCTAssertNotNil(task.error)
287290
XCTAssertEqual((task.error as? URLError)?.code, .badURL)
288291
}
289292
}
290-
293+
291294
func test_taskCopy() {
292295
let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")!
293296
let session = URLSession(configuration: URLSessionConfiguration.default,
294297
delegate: nil,
295298
delegateQueue: nil)
296299
let task = session.dataTask(with: url)
297-
300+
298301
XCTAssert(task.isEqual(task.copy()))
299302
}
303+
304+
func test_cancelTask() {
305+
let serverReady = ServerSemaphore()
306+
globalDispatchQueue.async {
307+
do {
308+
try self.runServer(with: serverReady)
309+
} catch {
310+
XCTAssertTrue(true)
311+
return
312+
}
313+
}
314+
serverReady.wait()
315+
let url = URL(string: "http://127.0.0.1:\(serverPort)/Peru")!
316+
let d = DataTask(with: expectation(description: "Task to be canceled"))
317+
d.cancelExpectation = expectation(description: "URLSessionTask wasn't canceled")
318+
d.run(with: url)
319+
d.cancel()
320+
waitForExpectations(timeout: 12)
321+
}
322+
323+
func test_verifyRequestHeaders() {
324+
let serverReady = ServerSemaphore()
325+
globalDispatchQueue.async {
326+
do {
327+
try self.runServer(with: serverReady)
328+
} catch {
329+
XCTAssertTrue(true)
330+
return
331+
}
332+
}
333+
serverReady.wait()
334+
let config = URLSessionConfiguration.default
335+
config.timeoutIntervalForRequest = 5
336+
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
337+
var expect = expectation(description: "download task with handler")
338+
var req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/requestHeaders")!)
339+
let headers = ["header1": "value1"]
340+
req.httpMethod = "POST"
341+
req.allHTTPHeaderFields = headers
342+
var task = session.dataTask(with: req) { (data, _, error) -> Void in
343+
defer { expect.fulfill() }
344+
let headers = String(data: data!, encoding: String.Encoding.utf8)!
345+
XCTAssertNotNil(headers.range(of: "header1: value1"))
346+
}
347+
task.resume()
348+
349+
waitForExpectations(timeout: 30)
350+
}
351+
352+
func test_taskTimeout() {
353+
let serverReady = ServerSemaphore()
354+
globalDispatchQueue.async {
355+
do {
356+
try self.runServer(with: serverReady, startDelay: 3, sendDelay: 3, bodyChunks: 3)
357+
} catch {
358+
XCTAssertTrue(true)
359+
return
360+
}
361+
}
362+
serverReady.wait()
363+
let config = URLSessionConfiguration.default
364+
config.timeoutIntervalForRequest = 5
365+
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
366+
var expect = expectation(description: "download task with handler")
367+
let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/Peru")!)
368+
var task = session.dataTask(with: req) { (data, _, error) -> Void in
369+
defer { expect.fulfill() }
370+
XCTAssertNil(error)
371+
}
372+
task.resume()
373+
374+
waitForExpectations(timeout: 30)
375+
}
300376
}
301377

302378
class SessionDelegate: NSObject, URLSessionDelegate {
@@ -317,7 +393,7 @@ class DataTask : NSObject {
317393
public var error = false
318394

319395
init(with expectation: XCTestExpectation) {
320-
dataTaskExpectation = expectation
396+
dataTaskExpectation = expectation
321397
}
322398

323399
func run(with request: URLRequest) {
@@ -327,7 +403,7 @@ class DataTask : NSObject {
327403
task = session.dataTask(with: request)
328404
task.resume()
329405
}
330-
406+
331407
func run(with url: URL) {
332408
let config = URLSessionConfiguration.default
333409
config.timeoutIntervalForRequest = 8
@@ -351,7 +427,7 @@ extension DataTask : URLSessionTaskDelegate {
351427
dataTaskExpectation.fulfill()
352428
self.error = true
353429
}
354-
}
430+
}
355431

356432
class DownloadTask : NSObject {
357433
var totalBytesWritten: Int64 = 0
@@ -381,12 +457,12 @@ class DownloadTask : NSObject {
381457
}
382458

383459
extension DownloadTask : URLSessionDownloadDelegate {
384-
460+
385461
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
386462
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
387463
self.totalBytesWritten = totalBytesWritten
388464
}
389-
465+
390466
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
391467
do {
392468
let attr = try FileManager.default.attributesOfItem(atPath: location.path)

0 commit comments

Comments
 (0)