1717import MetricsTestKit
1818import XCTest
1919
20- class MetricsExtensionsTests : XCTestCase {
20+ final class MetricsExtensionsTests : XCTestCase {
21+ @available ( * , deprecated)
2122 func testTimerBlock( ) throws {
2223 // bootstrap with our test metrics
2324 let metrics = TestMetrics ( )
@@ -184,6 +185,39 @@ class MetricsExtensionsTests: XCTestCase {
184185 testTimer. preferDisplayUnit ( . days)
185186 XCTAssertEqual ( testTimer. valueInPreferredUnit ( atIndex: 0 ) , value / ( 60 * 60 * 24 ) , accuracy: 0.000000001 , " expected value to match " )
186187 }
188+
189+ #if swift(>=5.7)
190+ func testTimerMeasure( ) async throws {
191+ // bootstrap with our test metrics
192+ let metrics = TestMetrics ( )
193+ MetricsSystem . bootstrapInternal ( metrics)
194+ // run the test
195+ let name = " timer- \( UUID ( ) . uuidString) "
196+ let delay = Duration . milliseconds ( 5 )
197+ let timer = Timer ( label: name)
198+ try await timer. measure {
199+ try await Task . sleep ( for: delay)
200+ }
201+ let expectedTimer = try metrics. expectTimer ( name)
202+ XCTAssertEqual ( 1 , expectedTimer. values. count, " expected number of entries to match " )
203+ XCTAssertGreaterThan ( expectedTimer. values [ 0 ] , delay. nanosecondsClamped, " expected delay to match " )
204+ }
205+
206+ func testTimerRecordDuration( ) throws {
207+ // bootstrap with our test metrics
208+ let metrics = TestMetrics ( )
209+ MetricsSystem . bootstrapInternal ( metrics)
210+ // run the test
211+ let name = " test-timer "
212+ let timer = Timer ( label: name)
213+ let duration = Duration . milliseconds ( 5 )
214+ timer. record ( duration)
215+
216+ let expectedTimer = try metrics. expectTimer ( name)
217+ XCTAssertEqual ( 1 , expectedTimer. values. count, " expected number of entries to match " )
218+ XCTAssertEqual ( expectedTimer. values [ 0 ] , duration. nanosecondsClamped, " expected delay to match " )
219+ }
220+ #endif
187221}
188222
189223// https://bugs.swift.org/browse/SR-6310
@@ -203,3 +237,25 @@ extension DispatchTimeInterval {
203237 }
204238 }
205239}
240+
241+ #if swift(>=5.7)
242+ @available ( macOS 13 , iOS 16 , tvOS 16 , watchOS 9 , * )
243+ extension Swift . Duration {
244+ fileprivate var nanosecondsClamped : Int64 {
245+ let components = self . components
246+
247+ let secondsComponentNanos = components. seconds. multipliedReportingOverflow ( by: 1_000_000_000 )
248+ let attosCompononentNanos = components. attoseconds / 1_000_000_000
249+ let combinedNanos = secondsComponentNanos. partialValue. addingReportingOverflow ( attosCompononentNanos)
250+
251+ guard
252+ !secondsComponentNanos. overflow,
253+ !combinedNanos. overflow
254+ else {
255+ return . max
256+ }
257+
258+ return combinedNanos. partialValue
259+ }
260+ }
261+ #endif
0 commit comments