2022-05-17 14:42:03 +00:00
|
|
|
import std/times
|
2023-04-19 13:06:00 +00:00
|
|
|
import pkg/chronos
|
2022-05-19 19:56:03 +00:00
|
|
|
import codex/clock
|
2022-05-17 14:42:03 +00:00
|
|
|
|
|
|
|
export clock
|
|
|
|
|
|
|
|
type
|
|
|
|
MockClock* = ref object of Clock
|
|
|
|
time: SecondsSince1970
|
2023-04-19 13:06:00 +00:00
|
|
|
waiting: seq[Waiting]
|
|
|
|
Waiting = ref object
|
|
|
|
until: SecondsSince1970
|
|
|
|
future: Future[void]
|
2022-05-17 14:42:03 +00:00
|
|
|
|
2023-06-22 15:11:18 +00:00
|
|
|
func new*(
|
|
|
|
_: type MockClock,
|
|
|
|
time: SecondsSince1970 = getTime().toUnix
|
|
|
|
): MockClock =
|
|
|
|
## Create a mock clock instance
|
2022-05-17 14:42:03 +00:00
|
|
|
MockClock(time: time)
|
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc set*(clock: MockClock, time: SecondsSince1970) =
|
2022-05-17 14:42:03 +00:00
|
|
|
clock.time = time
|
2023-04-19 13:06:00 +00:00
|
|
|
var index = 0
|
|
|
|
while index < clock.waiting.len:
|
|
|
|
if clock.waiting[index].until <= clock.time:
|
|
|
|
clock.waiting[index].future.complete()
|
|
|
|
clock.waiting.del(index)
|
|
|
|
else:
|
|
|
|
inc index
|
2022-05-17 14:42:03 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc advance*(clock: MockClock, seconds: int64) =
|
|
|
|
clock.set(clock.time + seconds)
|
2022-05-17 14:42:03 +00:00
|
|
|
|
2024-02-16 22:12:16 +00:00
|
|
|
method now*(clock: MockClock): SecondsSince1970 =
|
2022-05-17 14:42:03 +00:00
|
|
|
clock.time
|
2023-04-19 13:06:00 +00:00
|
|
|
|
|
|
|
method waitUntil*(clock: MockClock, time: SecondsSince1970) {.async.} =
|
2024-02-16 22:12:16 +00:00
|
|
|
if time > clock.now():
|
2023-04-19 13:06:00 +00:00
|
|
|
let future = newFuture[void]()
|
|
|
|
clock.waiting.add(Waiting(until: time, future: future))
|
|
|
|
await future
|