Skip to content

Commit 60eac93

Browse files
authored
Updates URLSessionInstrumentation to check task.state before setting FakeDelegaet (#539)
1 parent 62772bd commit 60eac93

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

Sources/Instrumentation/URLSession/URLSessionInstrumentation.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -600,14 +600,15 @@ public class URLSessionInstrumentation {
600600

601601
if #available(OSX 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
602602
guard Task.basePriority != nil else {
603+
// If not inside a Task basePriority is nil
603604
return
604605
}
605606
let instrumentedRequest = URLSessionLogger.processAndLogRequest(request, sessionTaskId: taskId, instrumentation: self, shouldInjectHeaders: true)
606607
task.setValue(instrumentedRequest, forKey: "currentRequest")
607608
self.setIdKey(value: taskId, for: task)
608609

609-
// If not inside a Task basePriority is nil
610-
if task.delegate == nil {
610+
611+
if task.delegate == nil && task.state != .running {
611612
task.delegate = FakeDelegate()
612613
}
613614
}

Tests/InstrumentationTests/URLSessionTests/URLSessionInstrumentationTests.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,22 @@ class URLSessionInstrumentationTests: XCTestCase {
304304
XCTAssertNotNil(URLSessionInstrumentationTests.requestCopy?.allHTTPHeaderFields?[W3CTraceContextPropagator.traceparent])
305305
}
306306

307+
public func testDataTaskWithUrlBlock_doesNotCrashWhenResumed_whenDataTaskIsRunning() {
308+
let url = URL(string: "http://localhost:33333/success")!
309+
let dataTask = URLSession.shared.dataTask(with: url) { _, _, _ in
310+
URLSessionInstrumentationTests.semaphore.signal()
311+
}
312+
313+
dataTask.resume()
314+
Task.detached {
315+
dataTask.resume()
316+
}
317+
318+
URLSessionInstrumentationTests.semaphore.wait()
319+
XCTAssertTrue(URLSessionInstrumentationTests.checker.createdRequestCalled)
320+
XCTAssertNotNil(URLSessionInstrumentationTests.requestCopy?.allHTTPHeaderFields?[W3CTraceContextPropagator.traceparent])
321+
}
322+
307323
public func testDownloadTaskWithUrlBlock() {
308324
let url = URL(string: "http://localhost:33333/success")!
309325

0 commit comments

Comments
 (0)