Removed test code from coro.nim and created three real tests for coroutines

This commit is contained in:
Rokas Kupstys 2017-02-20 17:03:39 +02:00
commit 5aef77a3d3
8 changed files with 71 additions and 92 deletions

View file

@ -294,95 +294,3 @@ proc wait*(c: proc(), interval=0.01) =
## Returns only after coroutine ``c`` has returned. ``interval`` is time in seconds how often.
while alive(c):
suspend(interval)
when isMainModule:
var
stackCheckValue = 1100220033
first: float64 = 0
second: float64 = 1
steps = 10
i: int
order = newSeq[int](10)
proc testFibonacci(id: int, sleep: float32) =
var sleepTime: float
while steps > 0:
echo id, " executing, slept for ", sleepTime
order[i] = id
i += 1
steps -= 1
swap first, second
second += first
var sleepStart = getTicks()
suspend(sleep)
sleepTime = float(getTicks() - sleepStart) / 1_000_000_000
start(proc() = testFibonacci(1, 0.01))
start(proc() = testFibonacci(2, 0.021))
run()
doAssert stackCheckValue == 1100220033
doAssert first == 55.0
doAssert order == @[1, 2, 1, 1, 2, 1, 1, 2, 1, 1]
order = newSeq[int](10)
i = 0
proc testExceptions(id: int, sleep: float) =
try:
order[i] = id; i += 1
suspend(sleep)
order[i] = id; i += 1
raise (ref ValueError)()
except:
order[i] = id; i += 1
suspend(sleep)
order[i] = id; i += 1
suspend(sleep)
order[i] = id; i += 1
start(proc() = testExceptions(1, 0.01))
start(proc() = testExceptions(2, 0.021))
run()
doAssert order == @[1, 2, 1, 1, 1, 2, 2, 1, 2, 2]
doAssert stackCheckValue == 1100220033
order = newSeq[int](10)
i = 0
iterator suspendingIterator(sleep: float): int =
for i in 0..4:
yield i
suspend(sleep)
proc terstIterators(id: int, sleep: float) =
for n in suspendingIterator(sleep):
order[i] = n
i += 1
start(proc() = terstIterators(1, 0.01))
start(proc() = terstIterators(2, 0.021))
run()
doAssert order == @[0, 0, 1, 2, 1, 3, 4, 2, 3, 4]
doAssert stackCheckValue == 1100220033
type Foo = ref object
number: int
GC_fullCollect()
var occupiedMemory = getOccupiedMem()
i = 0
var objects = newSeq[Foo](100)
proc terstGc(id: int, sleep: float) =
for n in 0..<50:
objects[i] = Foo(number: n)
i += 1
start(proc() = terstIterators(1, 0.01))
start(proc() = terstIterators(2, 0.021))
run()
doAssert occupiedMemory < getOccupiedMem()
objects = nil
GC_fullCollect()
doAssert occupiedMemory >= getOccupiedMem()