Skip to content

Commit 91036e2

Browse files
author
Pushkar Kulkarni
committed
Add missing delegate method invocations with upload tasks(SR-5516)
1 parent 79322e9 commit 91036e2

File tree

3 files changed

+57
-3
lines changed

3 files changed

+57
-3
lines changed

Foundation/NSURLSession/http/HTTPURLProtocol.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ internal class _HTTPURLProtocol: URLProtocol {
1414

1515
fileprivate var easyHandle: _EasyHandle!
1616
fileprivate var totalDownloaded = 0
17+
fileprivate var totalUploaded: Int64 = 0
18+
fileprivate var requestBodyLength: Int64 = 0
1719
fileprivate var tempFileURL: URL
1820

1921
public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
@@ -127,6 +129,7 @@ fileprivate extension _HTTPURLProtocol {
127129
set(requestBodyLength: .noBody)
128130
case (_, .some(let length)):
129131
set(requestBodyLength: .length(length))
132+
requestBodyLength = Int64(length)
130133
case (_, .none):
131134
set(requestBodyLength: .unknown)
132135
}
@@ -495,6 +498,16 @@ extension _HTTPURLProtocol: _EasyHandleDelegate {
495498
}
496499
}
497500

501+
fileprivate func notifyDelegate(aboutUploadedData count: Int64) {
502+
let session = self.task?.session as! URLSession
503+
guard case .taskDelegate(let delegate) = session.behaviour(for: self.task!), self.task is URLSessionUploadTask else { return }
504+
totalUploaded += count
505+
session.delegateQueue.addOperation {
506+
delegate.urlSession(session, task: self.task!, didSendBodyData: count,
507+
totalBytesSent: self.totalUploaded, totalBytesExpectedToSend: self.requestBodyLength)
508+
}
509+
}
510+
498511
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
499512
guard case .transferInProgress(let ts) = internalState else { fatalError("Requested to fill write buffer, but transfer isn't in progress.") }
500513
guard let source = ts.requestBodySource else { fatalError("Requested to fill write buffer, but transfer state has no body source.") }
@@ -503,6 +516,7 @@ extension _HTTPURLProtocol: _EasyHandleDelegate {
503516
copyDispatchData(data, infoBuffer: buffer)
504517
let count = data.count
505518
assert(count > 0)
519+
notifyDelegate(aboutUploadedData: Int64(count))
506520
return .bytes(count)
507521
case .done:
508522
return .bytes(0)

TestFoundation/HTTPServer.swift

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ public class TestURLSessionServer {
330330
}
331331

332332
func process(request: _HTTPRequest) -> _HTTPResponse {
333-
if request.method == .GET || request.method == .POST {
333+
if request.method == .GET || request.method == .POST || request.method == .PUT {
334334
return getResponse(request: request)
335335
} else {
336336
fatalError("Unsupported method!")
@@ -339,14 +339,20 @@ public class TestURLSessionServer {
339339

340340
func getResponse(request: _HTTPRequest) -> _HTTPResponse {
341341
let uri = request.uri
342+
343+
if uri == "/upload" {
344+
let text = "Upload completed!"
345+
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
346+
}
347+
342348
if uri == "/country.txt" {
343349
let text = capitals[String(uri.characters.dropFirst())]!
344-
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
350+
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
345351
}
346352

347353
if uri == "/requestHeaders" {
348354
let text = request.getCommaSeparatedHeaders()
349-
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
355+
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
350356
}
351357

352358
if uri == "/UnitedStates" {

TestFoundation/TestNSURLSession.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class TestURLSession : LoopbackServerTest {
4242
("test_missingContentLengthButStillABody", test_missingContentLengthButStillABody),
4343
("test_illegalHTTPServerResponses", test_illegalHTTPServerResponses),
4444
("test_dataTaskWithSharedDelegate", test_dataTaskWithSharedDelegate),
45+
("test_simpleUploadWithDelegate", test_simpleUploadWithDelegate),
4546
]
4647
}
4748

@@ -443,6 +444,21 @@ class TestURLSession : LoopbackServerTest {
443444
dataTask.resume()
444445
waitForExpectations(timeout: 20)
445446
}
447+
448+
func test_simpleUploadWithDelegate() {
449+
let delegate = HTTPUploadDelegate()
450+
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
451+
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/upload"
452+
var request = URLRequest(url: URL(string: urlString)!)
453+
request.httpMethod = "PUT"
454+
455+
delegate.uploadCompletedExpectation = expectation(description: "PUT \(urlString): Upload data")
456+
457+
let fileData = Data(count: 16*1024)
458+
let task = session.uploadTask(with: request, from: fileData)
459+
task.resume()
460+
waitForExpectations(timeout: 20)
461+
}
446462
}
447463

448464
class SharedDelegate: NSObject {
@@ -649,3 +665,21 @@ extension HTTPRedirectionDataTask : URLSessionTaskDelegate {
649665
completionHandler(request)
650666
}
651667
}
668+
669+
class HTTPUploadDelegate: NSObject {
670+
var uploadCompletedExpectation: XCTestExpectation!
671+
var totalBytesSent: Int64 = 0
672+
}
673+
674+
extension HTTPUploadDelegate: URLSessionTaskDelegate {
675+
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
676+
self.totalBytesSent = totalBytesSent
677+
}
678+
}
679+
680+
extension HTTPUploadDelegate: URLSessionDataDelegate {
681+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
682+
XCTAssertEqual(self.totalBytesSent, 16*1024)
683+
uploadCompletedExpectation.fulfill()
684+
}
685+
}

0 commit comments

Comments
 (0)