Skip to content

Commit 66d13bf

Browse files
committed
Add Test.isRunning to let code determine if Swift Testing is active.
This PR adds a `Test.isRunning` static property that tells the caller if _any_ thread/task/queue/etc. is currently running Swift Testing code. This property is distinct from `Test.current` because that property has a value of `nil` on detached tasks. Resolves #475.
1 parent 0e2d9cb commit 66d13bf

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Sources/Testing/Running/Runner.RuntimeState.swift

+20
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ extension Configuration {
106106
_all.rawValue.instances.values
107107
}
108108

109+
/// The number of instances of this type that are currently set as the current
110+
/// configuration for a task.
111+
static var currentCount: Int {
112+
_all.withLock { all in
113+
all.instances.count
114+
}
115+
}
116+
109117
/// Add this instance to ``Configuration/all``.
110118
///
111119
/// - Returns: A unique number identifying `self` that can be
@@ -147,6 +155,9 @@ extension Test {
147155
/// by using [`Thread.detachNewThread(_:)`](https://developer.apple.com/documentation/foundation/thread/2088563-detachnewthread)
148156
/// or [`DispatchQueue.async(execute:)`](https://developer.apple.com/documentation/dispatch/dispatchqueue/2016103-async)),
149157
/// the value of this property may be `nil`.
158+
///
159+
/// To determine if any test is running on any task in the current process,
160+
/// use ``Test/isRunning``.
150161
public static var current: Self? {
151162
Runner.RuntimeState.current?.test
152163
}
@@ -165,6 +176,15 @@ extension Test {
165176
runtimeState.test = test
166177
return try await Runner.RuntimeState.$current.withValue(runtimeState, operation: body)
167178
}
179+
180+
/// Whether or not any test is running in the current process.
181+
///
182+
/// To get an instance of ``Test`` representing the test running on the
183+
/// current task, use ``Test/current``.
184+
@_spi(Experimental)
185+
public static var isRunning: Bool {
186+
Configuration.currentCount > 0
187+
}
168188
}
169189

170190
extension Test.Case {

Tests/TestingTests/RunnerTests.swift

+9
Original file line numberDiff line numberDiff line change
@@ -878,5 +878,14 @@ final class RunnerTests: XCTestCase {
878878
await runTest(for: DeprecatedVersionTests.self, configuration: configuration)
879879
await fulfillment(of: [testStarted, testSkipped], timeout: 0.0)
880880
}
881+
882+
func testTestIsRunning() async {
883+
// Only XCTest is running here.
884+
XCTAssertFalse(Test.isRunning)
885+
886+
await Test {
887+
XCTAssertTrue(Test.isRunning)
888+
}.run(configuration: .init())
889+
}
881890
}
882891
#endif

0 commit comments

Comments
 (0)