From ce1e03aa4efd793c62cd5a308456352453bdfe9d Mon Sep 17 00:00:00 2001 From: gmega Date: Mon, 27 Nov 2023 09:49:44 -0300 Subject: [PATCH] add test for simple non-blocking future --- tests/profiler/testmetrics.nim | 27 +++++++++++++++++++++------ tests/profiler/utils.nim | 20 +++++++++++++++++++- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/tests/profiler/testmetrics.nim b/tests/profiler/testmetrics.nim index 1e80377..ec12d9e 100644 --- a/tests/profiler/testmetrics.nim +++ b/tests/profiler/testmetrics.nim @@ -14,21 +14,37 @@ suite "profiler metrics test suite": clearRecording() revertCallbacks() resetTime() + + proc recordedMetrics(): ProfilerMetrics = + result.processAllEvents(rawRecording) - test "should compute correct times for a simple future": + test "should compute correct times for a simple blocking future": proc simple() {.async.} = advanceTime(50.milliseconds) waitFor simple() - var metrics = ProfilerMetrics() - metrics.processAllEvents(rawRecording) + var metrics = recordedMetrics() let simpleMetrics = metrics.forProc("simple") check simpleMetrics.execTime == 50.milliseconds check simpleMetrics.wallClockTime == 50.milliseconds - test "should compute correct times for blocking children": + test "should compute correct times for a simple non-blocking future": + proc simple {.async.} = + advanceTime(10.milliseconds) + await advanceTimeAsync(50.milliseconds) + advanceTime(10.milliseconds) + + waitFor simple() + + var metrics = recordedMetrics() + let simpleMetrics = metrics.forProc("simple") + + check simpleMetrics.execTime == 20.milliseconds + check simpleMetrics.wallClockTime == 70.milliseconds + + test "should compute correct times whent there is a single blocking child": proc child() {.async.} = advanceTime(10.milliseconds) @@ -39,8 +55,7 @@ suite "profiler metrics test suite": waitFor parent() - var metrics = ProfilerMetrics() - metrics.processAllEvents(rawRecording) + var metrics = recordedMetrics() let parentMetrics = metrics.forProc("parent") let childMetrics = metrics.forProc("child") diff --git a/tests/profiler/utils.nim b/tests/profiler/utils.nim index 96e4166..8237632 100644 --- a/tests/profiler/utils.nim +++ b/tests/profiler/utils.nim @@ -63,4 +63,22 @@ proc resetTime*() = fakeTime = Moment.now() proc advanceTime*(duration: Duration) = - fakeTime += duration \ No newline at end of file + fakeTime += duration + +proc advanceTimeAsync*(duration: Duration): Future[void] = + # Simulates a non-blocking operation that takes the provided duration to + # complete. + var retFuture = newFuture[void]("advanceTimeAsync") + var timer: TimerCallback + + proc completion(data: pointer) {.gcsafe.} = + if not(retFuture.finished()): + advanceTime(duration) + retFuture.complete() + + # The actual value for the timer is irrelevant, the important thing is that + # this causes the parent to pause before we advance time. + timer = setTimer(Moment.fromNow(10.milliseconds), + completion, cast[pointer](retFuture)) + + return retFuture