Skip to content

Commit 9a1e03f

Browse files
committed
Swift Testing: Reset file counter for each test
This introduces a new task local to the test scoping trait to allow a test to be repeatedly run. Fixes #963.
1 parent 3f8d058 commit 9a1e03f

File tree

2 files changed

+41
-11
lines changed

2 files changed

+41
-11
lines changed

Sources/SnapshotTesting/AssertSnapshot.swift

+38-10
Original file line numberDiff line numberDiff line change
@@ -318,12 +318,7 @@ public func verifySnapshot<Value, Format>(
318318
if let name = name {
319319
identifier = sanitizePathComponent(name)
320320
} else {
321-
let counter = counterQueue.sync { () -> Int in
322-
let key = snapshotDirectoryUrl.appendingPathComponent(testName)
323-
counterMap[key, default: 0] += 1
324-
return counterMap[key]!
325-
}
326-
identifier = String(counter)
321+
identifier = String(counter.next())
327322
}
328323

329324
let testName = sanitizePathComponent(testName)
@@ -504,8 +499,19 @@ public func verifySnapshot<Value, Format>(
504499

505500
// MARK: - Private
506501

507-
private let counterQueue = DispatchQueue(label: "co.pointfree.SnapshotTesting.counter")
508-
private var counterMap: [URL: Int] = [:]
502+
private var counter: File.Counter {
503+
#if canImport(Testing)
504+
if Test.current != nil {
505+
return File.counter
506+
} else {
507+
return _counter
508+
}
509+
#else
510+
return _counter
511+
#endif
512+
}
513+
514+
private let _counter = File.Counter()
509515

510516
func sanitizePathComponent(_ string: String) -> String {
511517
return
@@ -546,8 +552,30 @@ private class CleanCounterBetweenTestCases: NSObject, XCTestObservation {
546552
}
547553

548554
func testCaseDidFinish(_ testCase: XCTestCase) {
549-
counterQueue.sync {
550-
counterMap = [:]
555+
_counter.reset()
556+
}
557+
}
558+
559+
enum File {
560+
@TaskLocal static var counter = Counter()
561+
562+
final class Counter: @unchecked Sendable {
563+
private var count = 0
564+
private let lock = NSLock()
565+
566+
init() {}
567+
568+
func next() -> Int {
569+
lock.lock()
570+
defer { lock.unlock() }
571+
count += 1
572+
return count
573+
}
574+
575+
func reset() {
576+
lock.lock()
577+
defer { lock.unlock() }
578+
count = 0
551579
}
552580
}
553581
}

Sources/SnapshotTesting/SnapshotsTestTrait.swift

+3-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@
4646
record: configuration.record,
4747
diffTool: configuration.diffTool
4848
) {
49-
try await function()
49+
try await File.$counter.withValue(File.Counter()) {
50+
try await function()
51+
}
5052
}
5153
}
5254
}

0 commit comments

Comments
 (0)