nim-raft/tests/test_basic_timers.nim

69 lines
1.8 KiB
Nim
Raw Normal View History

# nim-raft
# Copyright (c) 2023 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
import unittest2
import basic_timers
2023-08-25 09:00:40 +00:00
import random
2023-08-25 09:00:40 +00:00
const
MAX_TIMERS = 50
SLOW_TIMERS_MIN = 300
2023-08-25 09:33:31 +00:00
SLOW_TIMERS_MAX = 400
FAST_TIMERS_MIN = 10
FAST_TIMERS_MAX = 100
WAIT_FOR_SLOW_TIMERS = 200
FINAL_WAIT = 300
2023-08-31 14:05:41 +00:00
proc basicTimersMain*() =
var
2023-09-03 00:53:48 +00:00
slowTimers: array[0..MAX_TIMERS, Future[void]]
fastTimers: array[0..MAX_TIMERS, Future[void]]
2023-08-25 09:00:40 +00:00
var
2023-09-03 00:53:48 +00:00
slowCnt: ref int
RaftDummyTimerCallback = proc () {.nimcall, gcsafe.} = discard
RaftTimerCallbackCnt = proc (cnt: ref int): RaftTimerCallback =
proc () {.gcsafe.} = cnt[].inc
slowCnt = new(int)
slowCnt[] = 0
suite "Create and test basic timers":
2023-08-25 09:33:31 +00:00
test "Create 'slow' and 'fast' timers":
2023-08-25 09:00:40 +00:00
for i in 0..MAX_TIMERS:
2023-09-06 16:18:02 +00:00
slowTimers[i] = RaftTimerCreateCustomImpl(max(SLOW_TIMERS_MIN, rand(SLOW_TIMERS_MAX)), RaftTimerCallbackCnt(slowCnt))
2023-08-25 09:33:31 +00:00
2023-08-25 09:00:40 +00:00
for i in 0..MAX_TIMERS:
2023-09-06 16:18:02 +00:00
fastTimers[i] = RaftTimerCreateCustomImpl(max(FAST_TIMERS_MIN, rand(FAST_TIMERS_MAX)), RaftDummyTimerCallback)
2023-08-25 09:33:31 +00:00
2023-08-25 09:00:40 +00:00
test "Wait for and cancel 'slow' timers":
2023-08-31 14:05:41 +00:00
waitFor sleepAsync(WAIT_FOR_SLOW_TIMERS)
2023-08-25 09:00:40 +00:00
for i in 0..MAX_TIMERS:
2023-09-03 00:53:48 +00:00
if not slowTimers[i].finished:
2023-09-06 16:18:02 +00:00
asyncSpawn cancelAndWait(slowTimers[i])
2023-08-25 09:33:31 +00:00
2023-08-31 14:05:41 +00:00
test "Final wait timers":
2023-08-25 09:00:40 +00:00
waitFor sleepAsync(FINAL_WAIT)
2023-08-25 09:33:31 +00:00
test "Check timers consistency":
2023-08-25 09:33:31 +00:00
var
pass = true
2023-08-25 09:00:40 +00:00
for i in 0..MAX_TIMERS:
2023-09-03 00:53:48 +00:00
if not fastTimers[i].finished:
debugEcho repr(fastTimers[i])
2023-08-25 09:33:31 +00:00
pass = false
break
check pass
2023-09-03 00:53:48 +00:00
check slowCnt[] == 0
if isMainModule:
2023-08-31 14:05:41 +00:00
basicTimersMain()