Skip to content

Commit 245d527

Browse files
authored
Better collocate XCTFail source code context (#67)
XCTest usually does a pretty good job of attaching an out-of-test XCTFail to the source code context that makes it most visible to Xcode users, but for complex tests it seems to stop working after awhile, and it also seems to have gotten less reliable in Xcode 15. So we can do our best to take over. We can use @tgrapperon's call stack code to find the test frame and manually assign it to the issue's source code context.
1 parent 4af50b3 commit 245d527

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

Sources/XCTestDynamicOverlay/XCTFail.swift

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,8 @@ import Foundation
1616
attachHostApplicationWarningIfNeeded(&message)
1717
guard
1818
let currentTestCase = XCTCurrentTestCase,
19-
let XCTIssue = NSClassFromString("XCTIssue")
20-
as Any as? NSObjectProtocol,
21-
let alloc = XCTIssue.perform(NSSelectorFromString("alloc"))?
22-
.takeUnretainedValue(),
23-
let issue =
24-
alloc
19+
let issue = (NSClassFromString("XCTIssue") as Any as? NSObjectProtocol)?
20+
.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue()
2521
.perform(
2622
Selector(("initWithType:compactDescription:")),
2723
with: 0,
@@ -34,6 +30,19 @@ import Foundation
3430
}
3531
return
3632
}
33+
if let testFrame = Thread.callStackSymbols.enumerated().first(where: { isTestFrame($1) }),
34+
let sourceCodeContext =
35+
(NSClassFromString("XCTSourceCodeContext") as Any as? NSObjectProtocol)?
36+
.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue()
37+
.perform(
38+
Selector(("initWithCallStackAddresses:location:")),
39+
with: Array(Thread.callStackReturnAddresses[testFrame.offset...]),
40+
with: nil
41+
)?
42+
.takeUnretainedValue()
43+
{
44+
_ = issue.perform(Selector(("setSourceCodeContext:")), with: sourceCodeContext)
45+
}
3746
_ = currentTestCase.perform(Selector(("recordIssue:")), with: issue)
3847
}
3948

0 commit comments

Comments
 (0)