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

Add Test.isRunning to let code determine if Swift Testing is active. #514

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
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