Skip to content

Commit 3c78f9c

Browse files
authored
Merge pull request #916 from swizzlr/master
2 parents 41542b2 + 38bff22 commit 3c78f9c

File tree

3 files changed

+76
-25
lines changed

3 files changed

+76
-25
lines changed

Foundation/NSURLSession/NSURLSessionTask.swift

+10-3
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,16 @@ fileprivate extension URLSessionTask {
554554

555555
// HTTP Options:
556556
easyHandle.set(followLocation: false)
557-
easyHandle.set(customHeaders: curlHeaders(for: request))
557+
558+
let customHeaders: [String]
559+
let headersForRequest = curlHeaders(for: request)
560+
if ((request.httpMethod == "POST") && (request.value(forHTTPHeaderField: "Content-Type") == nil)) {
561+
customHeaders = headersForRequest + ["Content-Type:application/x-www-form-urlencoded"]
562+
} else {
563+
customHeaders = headersForRequest
564+
}
565+
566+
easyHandle.set(customHeaders: customHeaders)
558567

559568
//TODO: The CURLOPT_PIPEDWAIT option is unavailable on Ubuntu 14.04 (libcurl 7.36)
560569
//TODO: Introduce something like an #if, if we want to set them here
@@ -575,8 +584,6 @@ fileprivate extension URLSessionTask {
575584
easyHandle.set(requestMethod: request.httpMethod ?? "GET")
576585
if request.httpMethod == "HEAD" {
577586
easyHandle.set(noBody: true)
578-
} else if ((request.httpMethod == "POST") && (request.value(forHTTPHeaderField: "Content-Type") == nil)) {
579-
easyHandle.set(customHeaders: ["Content-Type:application/x-www-form-urlencoded"])
580587
}
581588
}
582589
}

TestFoundation/HTTPServer.swift

+17-3
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,14 @@ struct _HTTPRequest {
191191
body = lines.last!
192192
}
193193

194+
public func getCommaSeparatedHeaders() -> String {
195+
var allHeaders = ""
196+
for header in headers {
197+
allHeaders += header + ","
198+
}
199+
return allHeaders
200+
}
201+
194202
}
195203

196204
struct _HTTPResponse {
@@ -240,18 +248,24 @@ public class TestURLSessionServer {
240248
}
241249

242250
func process(request: _HTTPRequest) -> _HTTPResponse {
243-
if request.method == .GET {
244-
return getResponse(uri: request.uri)
251+
if request.method == .GET || request.method == .POST {
252+
return getResponse(request: request)
245253
} else {
246254
fatalError("Unsupported method!")
247255
}
248256
}
249257

250-
func getResponse(uri: String) -> _HTTPResponse {
258+
func getResponse(request: _HTTPRequest) -> _HTTPResponse {
259+
let uri = request.uri
251260
if uri == "/country.txt" {
252261
let text = capitals[String(uri.characters.dropFirst())]!
253262
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
254263
}
264+
265+
if uri == "/requestHeaders" {
266+
let text = request.getCommaSeparatedHeaders()
267+
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
268+
}
255269
return _HTTPResponse(response: .OK, body: capitals[String(uri.characters.dropFirst())]!)
256270
}
257271

TestFoundation/TestNSURLSession.swift

+49-19
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class TestURLSession : XCTestCase {
3434
("test_taskCopy", test_taskCopy),
3535
("test_cancelTask", test_cancelTask),
3636
("test_taskTimeout", test_taskTimeout),
37+
("test_verifyRequestHeaders", test_verifyRequestHeaders),
3738
]
3839
}
3940

@@ -66,22 +67,22 @@ class TestURLSession : XCTestCase {
6667
serverReady.wait()
6768
let urlString = "http://127.0.0.1:\(serverPort)/Nepal"
6869
let url = URL(string: urlString)!
69-
let d = DataTask(with: expectation(description: "data task"))
70+
let d = DataTask(with: expectation(description: "data task"))
7071
d.run(with: url)
7172
waitForExpectations(timeout: 12)
7273
if !d.error {
7374
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
7475
}
7576
}
76-
77+
7778
func test_dataTaskWithURLCompletionHandler() {
7879
let serverReady = ServerSemaphore()
7980
globalDispatchQueue.async {
8081
do {
8182
try self.runServer(with: serverReady)
8283
} catch {
8384
XCTAssertTrue(true)
84-
return
85+
return
8586
}
8687
}
8788
serverReady.wait()
@@ -100,7 +101,7 @@ class TestURLSession : XCTestCase {
100101
}
101102

102103
let httpResponse = response as! HTTPURLResponse?
103-
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
104+
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
104105
expectedResult = String(data: data!, encoding: String.Encoding.utf8)!
105106
XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value")
106107
expect.fulfill()
@@ -122,7 +123,7 @@ class TestURLSession : XCTestCase {
122123
serverReady.wait()
123124
let urlString = "http://127.0.0.1:\(serverPort)/Peru"
124125
let urlRequest = URLRequest(url: URL(string: urlString)!)
125-
let d = DataTask(with: expectation(description: "data task"))
126+
let d = DataTask(with: expectation(description: "data task"))
126127
d.run(with: urlRequest)
127128
waitForExpectations(timeout: 12)
128129
if !d.error {
@@ -176,7 +177,7 @@ class TestURLSession : XCTestCase {
176177
}
177178
serverReady.wait()
178179
let urlString = "http://127.0.0.1:\(serverPort)/country.txt"
179-
let url = URL(string: urlString)!
180+
let url = URL(string: urlString)!
180181
let d = DownloadTask(with: expectation(description: "download task with delegate"))
181182
d.run(with: url)
182183
waitForExpectations(timeout: 12)
@@ -251,7 +252,7 @@ class TestURLSession : XCTestCase {
251252
task.resume()
252253
waitForExpectations(timeout: 12)
253254
}
254-
255+
255256
func test_finishTasksAndInvalidate() {
256257
let invalidateExpectation = expectation(description: "URLSession wasn't invalidated")
257258
let delegate = SessionDelegate(invalidateExpectation: invalidateExpectation)
@@ -266,7 +267,7 @@ class TestURLSession : XCTestCase {
266267
session.finishTasksAndInvalidate()
267268
waitForExpectations(timeout: 12)
268269
}
269-
270+
270271
func test_taskError() {
271272
let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")!
272273
let session = URLSession(configuration: URLSessionConfiguration.default,
@@ -281,22 +282,22 @@ class TestURLSession : XCTestCase {
281282
}
282283
//should result in Bad URL error
283284
task.resume()
284-
285+
285286
waitForExpectations(timeout: 5) { error in
286287
XCTAssertNil(error)
287-
288+
288289
XCTAssertNotNil(task.error)
289290
XCTAssertEqual((task.error as? URLError)?.code, .badURL)
290291
}
291292
}
292-
293+
293294
func test_taskCopy() {
294295
let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")!
295296
let session = URLSession(configuration: URLSessionConfiguration.default,
296297
delegate: nil,
297298
delegateQueue: nil)
298299
let task = session.dataTask(with: url)
299-
300+
300301
XCTAssert(task.isEqual(task.copy()))
301302
}
302303

@@ -318,7 +319,36 @@ class TestURLSession : XCTestCase {
318319
d.cancel()
319320
waitForExpectations(timeout: 12)
320321
}
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+
322352
func test_taskTimeout() {
323353
let serverReady = ServerSemaphore()
324354
globalDispatchQueue.async {
@@ -340,7 +370,7 @@ class TestURLSession : XCTestCase {
340370
XCTAssertNil(error)
341371
}
342372
task.resume()
343-
373+
344374
waitForExpectations(timeout: 30)
345375
}
346376
}
@@ -365,7 +395,7 @@ class DataTask : NSObject {
365395
public var error = false
366396

367397
init(with expectation: XCTestExpectation) {
368-
dataTaskExpectation = expectation
398+
dataTaskExpectation = expectation
369399
}
370400

371401
func run(with request: URLRequest) {
@@ -375,7 +405,7 @@ class DataTask : NSObject {
375405
task = session.dataTask(with: request)
376406
task.resume()
377407
}
378-
408+
379409
func run(with url: URL) {
380410
let config = URLSessionConfiguration.default
381411
config.timeoutIntervalForRequest = 8
@@ -405,7 +435,7 @@ extension DataTask : URLSessionTaskDelegate {
405435
}
406436
self.error = true
407437
}
408-
}
438+
}
409439

410440
class DownloadTask : NSObject {
411441
var totalBytesWritten: Int64 = 0
@@ -435,12 +465,12 @@ class DownloadTask : NSObject {
435465
}
436466

437467
extension DownloadTask : URLSessionDownloadDelegate {
438-
468+
439469
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
440470
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
441471
self.totalBytesWritten = totalBytesWritten
442472
}
443-
473+
444474
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
445475
do {
446476
let attr = try FileManager.default.attributesOfItem(atPath: location.path)

0 commit comments

Comments
 (0)