Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use alternate means to detect if running on main thread #946

Merged
merged 1 commit into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions Sources/SnapshotTesting/AssertSnapshot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -516,27 +516,33 @@ func sanitizePathComponent(_ string: String) -> String {
}
#endif

extension DispatchQueue {
private static let key = DispatchSpecificKey<UInt8>()
private static let value: UInt8 = 0

fileprivate static func mainSync<R>(execute block: () -> R) -> R {
Self.main.setSpecific(key: key, value: value)
if getSpecific(key: key) == value {
return block()
} else {
return main.sync(execute: block)
}
}
}

// We need to clean counter between tests executions in order to support test-iterations.
private class CleanCounterBetweenTestCases: NSObject, XCTestObservation {
private static var registered = false

static func registerIfNeeded() {
if Thread.isMainThread {
doRegisterIfNeeded()
} else {
DispatchQueue.main.sync {
doRegisterIfNeeded()
DispatchQueue.mainSync {
if !registered {
registered = true
XCTestObservationCenter.shared.addTestObserver(CleanCounterBetweenTestCases())
}
}
}

private static func doRegisterIfNeeded() {
if !registered {
registered = true
XCTestObservationCenter.shared.addTestObserver(CleanCounterBetweenTestCases())
}
}

func testCaseDidFinish(_ testCase: XCTestCase) {
counterQueue.sync {
counterMap = [:]
Expand Down
14 changes: 14 additions & 0 deletions Tests/SnapshotTestingTests/AssertSnapshotSwiftTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,18 @@
assertSnapshot(of: user, as: .dump)
}
}

@MainActor
@Suite(
.snapshots(
record: .missing
)
)
struct MainActorTests {
@Test func dump() {
struct User { let id: Int, name: String, bio: String }
let user = User(id: 1, name: "Blobby", bio: "Blobbed around the world.")
assertSnapshot(of: user, as: .dump)
}
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
▿ User
- bio: "Blobbed around the world."
- id: 1
- name: "Blobby"