nim-chronos/tests/testtime.nim

53 lines
1.5 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 unittest
import ../chronos, ../chronos/timer
2018-05-22 22:29:07 +00:00
const TimersCount = 10
proc timeWorker(time: int): Future[int] {.async.} =
var st = fastEpochTime()
await sleepAsync(time)
var et = fastEpochTime()
result = int(et - st)
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
2018-10-03 00:56:16 +00:00
proc test(timeout: int): Future[int64] {.async.} =
2018-05-22 22:29:07 +00:00
var workers = newSeq[Future[int]](TimersCount)
for i in 0..<TimersCount:
workers[i] = timeWorker(timeout)
await waitAll(workers)
2018-10-03 00:56:16 +00:00
var sum = 0'i64
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
when isMainModule:
suite "Asynchronous timers test suite":
test $TimersCount & " timers with 10ms timeout":
var res = waitFor(test(10))
check (res >= 10) and (res <= 100)
test $TimersCount & " timers with 100ms timeout":
var res = waitFor(test(100))
check (res >= 100) and (res <= 1000)
test $TimersCount & " timers with 1000ms timeout":
var res = waitFor(test(1000))
2019-03-15 00:43:51 +00:00
check (res >= 1000) and (res <= 5000)