Skip to content

Commit f398886

Browse files
author
Pushkar Kulkarni
committed
Add missing delegate method invocations with upload tasks(SR-5516)
1 parent f550ea6 commit f398886

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
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 bodyLength: 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+
bodyLength = Int64(length)
130133
case (_, .none):
131134
set(requestBodyLength: .unknown)
132135
}
@@ -495,6 +498,16 @@ extension _HTTPURLProtocol: _EasyHandleDelegate {
495498
}
496499
}
497500

501+
fileprivate func notifyDelegate(aboutSentData count: Int64) {
502+
guard let session = self.task?.session as? URLSession else { fatalError() }
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.bodyLength)
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(aboutSentData: Int64(count))
506520
return .bytes(count)
507521
case .done:
508522
return .bytes(0)

TestFoundation/HTTPServer.swift

Lines changed: 7 additions & 1 deletion
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,6 +339,12 @@ 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.characters.count)", body: text)
346+
}
347+
342348
if uri == "/country.txt" {
343349
let text = capitals[String(uri.characters.dropFirst())]!
344350
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)

TestFoundation/TestNSURLSession.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class TestURLSession : LoopbackServerTest {
4141
("test_outOfRangeButCorrectlyFormattedHTTPCode", test_outOfRangeButCorrectlyFormattedHTTPCode),
4242
("test_missingContentLengthButStillABody", test_missingContentLengthButStillABody),
4343
("test_illegalHTTPServerResponses", test_illegalHTTPServerResponses),
44+
("test_simpleUploadWithDelegate", test_simpleUploadWithDelegate),
4445
]
4546
}
4647

@@ -429,6 +430,21 @@ class TestURLSession : LoopbackServerTest {
429430
waitForExpectations(timeout: 12)
430431
}
431432
}
433+
434+
func test_simpleUploadWithDelegate() {
435+
let delegate = HTTPUploadDelegate()
436+
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
437+
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/upload"
438+
var request = URLRequest(url: URL(string: urlString)!)
439+
request.httpMethod = "PUT"
440+
441+
delegate.uploadCompletedExpectation = expectation(description: "PUT \(urlString): Upload data")
442+
443+
let fileData = Data(count: 16*1024)
444+
let task = session.uploadTask(with: request, from: fileData)
445+
task.resume()
446+
waitForExpectations(timeout: 20)
447+
}
432448
}
433449

434450
class SessionDelegate: NSObject, URLSessionDelegate {
@@ -619,3 +635,21 @@ extension HTTPRedirectionDataTask : URLSessionTaskDelegate {
619635
completionHandler(request)
620636
}
621637
}
638+
639+
class HTTPUploadDelegate: NSObject {
640+
var uploadCompletedExpectation: XCTestExpectation!
641+
var totalBytesSent: Int64 = 0
642+
}
643+
644+
extension HTTPUploadDelegate: URLSessionTaskDelegate {
645+
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
646+
self.totalBytesSent = totalBytesSent
647+
}
648+
}
649+
650+
extension HTTPUploadDelegate: URLSessionDataDelegate {
651+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
652+
XCTAssertEqual(self.totalBytesSent, 16*1024)
653+
uploadCompletedExpectation.fulfill()
654+
}
655+
}

0 commit comments

Comments
 (0)