add tests/asyncunit & helpers

This commit is contained in:
Ludovic Chenut 2024-03-07 17:23:21 +01:00
parent 0521012ffc
commit f445c5c47d
No known key found for this signature in database
GPG Key ID: D9A59B1907F1D50C
2 changed files with 94 additions and 0 deletions

46
tests/asyncunit.nim Normal file
View File

@ -0,0 +1,46 @@
import unittest2, chronos
export unittest2, chronos
template asyncTeardown*(body: untyped): untyped =
teardown:
waitFor((
proc() {.async, gcsafe.} =
body
)())
template asyncSetup*(body: untyped): untyped =
setup:
waitFor((
proc() {.async, gcsafe.} =
body
)())
template asyncTest*(name: string, body: untyped): untyped =
test name:
waitFor((
proc() {.async, gcsafe.} =
body
)())
template flakyAsyncTest*(name: string, attempts: int, body: untyped): untyped =
test name:
var attemptNumber = 0
while attemptNumber < attempts:
let isLastAttempt = attemptNumber == attempts - 1
inc attemptNumber
try:
waitFor((
proc() {.async, gcsafe.} =
body
)())
except Exception as e:
if isLastAttempt: raise e
else: testStatusIMPL = TestStatus.FAILED
finally:
if not isLastAttempt:
if testStatusIMPL == TestStatus.FAILED:
# Retry
testStatusIMPL = TestStatus.OK
else:
break

48
tests/helpers.nim Normal file
View File

@ -0,0 +1,48 @@
when (NimMajor, NimMinor) < (1, 4):
{.push raises: [Defect].}
else:
{.push raises: [].}
import chronos
import unittest2
export unittest2
const
StreamTransportTrackerName = "stream.transport"
StreamServerTrackerName = "stream.server"
DgramTransportTrackerName = "datagram.transport"
trackerNames = [
StreamTransportTrackerName,
StreamServerTrackerName,
DgramTransportTrackerName,
]
template asyncTest*(name: string, body: untyped): untyped =
test name:
waitFor((proc () {.async, gcsafe.} = body)())
iterator testTrackers*(extras: openArray[string] = []): TrackerBase =
for name in trackerNames:
let t = getTracker(name)
if not isNil(t): yield t
for name in extras:
let t = getTracker(name)
if not isNil(t): yield t
template checkTracker*(name: string) =
var tracker = getTracker(name)
if tracker.isLeaked():
checkpoint tracker.dump()
fail()
template checkTrackers*() =
for tracker in testTrackers():
if tracker.isLeaked():
checkpoint tracker.dump()
fail()
# Also test the GC is not fooling with us
try:
GC_fullCollect()
except:
discard