Skip to content

Commit 096e52a

Browse files
committed
Added isSystemTimingStable test condition trait
1 parent c67de0b commit 096e52a

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

Sources/TestingExtensions/Traits.swift

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ extension Trait where Self == Testing.ConditionTrait {
4141
/// Test case usage:
4242
///
4343
/// ```swift
44-
/// @Test(.enabledIfShiftOnlyIsDown) func foo async throws {
44+
/// @Test(.enabledIfShiftOnlyIsDown) func foo() async throws {
4545
/// // test logic...
4646
/// }
4747
/// ```
@@ -50,4 +50,42 @@ extension Trait where Self == Testing.ConditionTrait {
5050
}
5151
}
5252

53+
// MARK: - System Timing Precision
54+
55+
/// Returns `true` if system conditions are suitable for executing tests that rely on precise system timing.
56+
public func isSystemTimingStable(
57+
duration: TimeInterval = 0.1,
58+
tolerance: TimeInterval = 0.01
59+
) -> Bool {
60+
let durationMS = UInt32(duration * TimeInterval(USEC_PER_SEC))
61+
62+
let start = Date()
63+
usleep(durationMS)
64+
let end = Date()
65+
let diff = end.timeIntervalSince(start)
66+
67+
let range = (duration - tolerance) ... (duration + tolerance)
68+
return range.contains(diff)
69+
}
70+
71+
extension Trait where Self == Testing.ConditionTrait {
72+
/// Convenience proxy for `.enabled(if: isSystemTimingStable())`.
73+
///
74+
/// Returns `true` if system conditions are suitable for executing tests that rely on precise system timing.
75+
///
76+
/// Test case usage:
77+
///
78+
/// ```swift
79+
/// @Test(.enabledIfSystemTimingStable()) func foo() async throws {
80+
/// // test logic...
81+
/// }
82+
/// ```
83+
public static func enabledIfSystemTimingStable(
84+
duration: TimeInterval = 0.1,
85+
tolerance: TimeInterval = 0.01
86+
) -> ConditionTrait {
87+
.enabled(if: isSystemTimingStable(duration: duration, tolerance: tolerance))
88+
}
89+
}
90+
5391
#endif

0 commit comments

Comments
 (0)