Skip to content

Commit

Permalink
Add Test.isRunning to let code determine if Swift Testing is active.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
grynspan committed Jun 29, 2024
1 parent 0e2d9cb commit 66d13bf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Sources/Testing/Running/Runner.RuntimeState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ extension Configuration {
_all.rawValue.instances.values
}

/// The number of instances of this type that are currently set as the current
/// configuration for a task.
static var currentCount: Int {
_all.withLock { all in
all.instances.count
}
}

/// Add this instance to ``Configuration/all``.
///
/// - Returns: A unique number identifying `self` that can be
Expand Down Expand Up @@ -147,6 +155,9 @@ extension Test {
/// by using [`Thread.detachNewThread(_:)`](https://developer.apple.com/documentation/foundation/thread/2088563-detachnewthread)
/// or [`DispatchQueue.async(execute:)`](https://developer.apple.com/documentation/dispatch/dispatchqueue/2016103-async)),
/// the value of this property may be `nil`.
///
/// To determine if any test is running on any task in the current process,
/// use ``Test/isRunning``.
public static var current: Self? {
Runner.RuntimeState.current?.test
}
Expand All @@ -165,6 +176,15 @@ extension Test {
runtimeState.test = test
return try await Runner.RuntimeState.$current.withValue(runtimeState, operation: body)
}

/// Whether or not any test is running in the current process.
///
/// To get an instance of ``Test`` representing the test running on the
/// current task, use ``Test/current``.
@_spi(Experimental)
public static var isRunning: Bool {
Configuration.currentCount > 0
}
}

extension Test.Case {
Expand Down
9 changes: 9 additions & 0 deletions Tests/TestingTests/RunnerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -878,5 +878,14 @@ final class RunnerTests: XCTestCase {
await runTest(for: DeprecatedVersionTests.self, configuration: configuration)
await fulfillment(of: [testStarted, testSkipped], timeout: 0.0)
}

func testTestIsRunning() async {
// Only XCTest is running here.
XCTAssertFalse(Test.isRunning)

await Test {
XCTAssertTrue(Test.isRunning)
}.run(configuration: .init())
}
}
#endif

0 comments on commit 66d13bf

Please sign in to comment.