Skip to content

Commit eb31d41

Browse files
authored
Use alternate means to detect if running on main thread to avoid problems with MainActor on Linux (#946)
1 parent de5f975 commit eb31d41

File tree

3 files changed

+36
-12
lines changed

3 files changed

+36
-12
lines changed

Sources/SnapshotTesting/AssertSnapshot.swift

+18-12
Original file line numberDiff line numberDiff line change
@@ -523,27 +523,33 @@ func sanitizePathComponent(_ string: String) -> String {
523523
}
524524
#endif
525525

526+
extension DispatchQueue {
527+
private static let key = DispatchSpecificKey<UInt8>()
528+
private static let value: UInt8 = 0
529+
530+
fileprivate static func mainSync<R>(execute block: () -> R) -> R {
531+
Self.main.setSpecific(key: key, value: value)
532+
if getSpecific(key: key) == value {
533+
return block()
534+
} else {
535+
return main.sync(execute: block)
536+
}
537+
}
538+
}
539+
526540
// We need to clean counter between tests executions in order to support test-iterations.
527541
private class CleanCounterBetweenTestCases: NSObject, XCTestObservation {
528542
private static var registered = false
529543

530544
static func registerIfNeeded() {
531-
if Thread.isMainThread {
532-
doRegisterIfNeeded()
533-
} else {
534-
DispatchQueue.main.sync {
535-
doRegisterIfNeeded()
545+
DispatchQueue.mainSync {
546+
if !registered {
547+
registered = true
548+
XCTestObservationCenter.shared.addTestObserver(CleanCounterBetweenTestCases())
536549
}
537550
}
538551
}
539552

540-
private static func doRegisterIfNeeded() {
541-
if !registered {
542-
registered = true
543-
XCTestObservationCenter.shared.addTestObserver(CleanCounterBetweenTestCases())
544-
}
545-
}
546-
547553
func testCaseDidFinish(_ testCase: XCTestCase) {
548554
counterQueue.sync {
549555
counterMap = [:]

Tests/SnapshotTestingTests/AssertSnapshotSwiftTests.swift

+14
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,18 @@
1515
assertSnapshot(of: user, as: .dump)
1616
}
1717
}
18+
19+
@MainActor
20+
@Suite(
21+
.snapshots(
22+
record: .missing
23+
)
24+
)
25+
struct MainActorTests {
26+
@Test func dump() {
27+
struct User { let id: Int, name: String, bio: String }
28+
let user = User(id: 1, name: "Blobby", bio: "Blobbed around the world.")
29+
assertSnapshot(of: user, as: .dump)
30+
}
31+
}
1832
#endif
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
▿ User
2+
- bio: "Blobbed around the world."
3+
- id: 1
4+
- name: "Blobby"

0 commit comments

Comments
 (0)