nim-chronos/tests/testtime.nim

62 lines
1.9 KiB
Nim
Raw Normal View History

# Chronos Test Suite
# (c) Copyright 2018-Present
2018-05-22 22:29:07 +00:00
# Status Research & Development GmbH
#
# Licensed under either of
# Apache License, version 2.0, (LICENSE-APACHEv2)
# MIT license (LICENSE-MIT)
import os, unittest
import ../chronos, ../chronos/timer
2018-05-22 22:29:07 +00:00
const TimersCount = 10
proc timeWorker(time: Duration): Future[Duration] {.async.} =
var st = Moment.now()
2018-05-22 22:29:07 +00:00
await sleepAsync(time)
var et = Moment.now()
result = et - st
2018-05-22 22:29:07 +00:00
proc waitAll[T](futs: seq[Future[T]]): Future[void] =
var counter = len(futs)
var retFuture = newFuture[void]("waitAll")
proc cb(udata: pointer) =
dec(counter)
if counter == 0:
retFuture.complete()
for fut in futs:
fut.addCallback(cb)
return retFuture
proc test(timeout: Duration): Future[Duration] {.async.} =
var workers = newSeq[Future[Duration]](TimersCount)
2018-05-22 22:29:07 +00:00
for i in 0..<TimersCount:
workers[i] = timeWorker(timeout)
await waitAll(workers)
var sum: Duration
2018-05-22 22:29:07 +00:00
for i in 0..<TimersCount:
var time = workers[i].read()
sum = sum + time
2018-10-03 00:56:16 +00:00
result = sum div 10'i64
2018-05-22 22:29:07 +00:00
proc testTimer(): bool =
let a = Moment.now()
waitFor(sleepAsync(1000.milliseconds))
let b = Moment.now()
let d = b - a
result = (d >= 1000.milliseconds) and (d <= 2_000.milliseconds)
2018-05-22 22:29:07 +00:00
when isMainModule:
suite "Asynchronous timers test suite":
test "Timer reliability test [" & asyncTimer & "]":
check testTimer() == true
2018-05-22 22:29:07 +00:00
test $TimersCount & " timers with 10ms timeout":
var res = waitFor(test(10.milliseconds))
check (res >= 10.milliseconds) and (res <= 100.milliseconds)
2018-05-22 22:29:07 +00:00
test $TimersCount & " timers with 100ms timeout":
var res = waitFor(test(100.milliseconds))
check (res >= 100.milliseconds) and (res <= 1000.milliseconds)
2018-05-22 22:29:07 +00:00
test $TimersCount & " timers with 1000ms timeout":
var res = waitFor(test(1000.milliseconds))
check (res >= 1000.milliseconds) and (res <= 5000.milliseconds)