From f445c5c47d1db8d498999ffc1238cacc19f73df8 Mon Sep 17 00:00:00 2001 From: Ludovic Chenut Date: Thu, 7 Mar 2024 17:23:21 +0100 Subject: [PATCH] add tests/asyncunit & helpers --- tests/asyncunit.nim | 46 +++++++++++++++++++++++++++++++++++++++++++ tests/helpers.nim | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 tests/asyncunit.nim create mode 100644 tests/helpers.nim diff --git a/tests/asyncunit.nim b/tests/asyncunit.nim new file mode 100644 index 0000000..1589bf6 --- /dev/null +++ b/tests/asyncunit.nim @@ -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 diff --git a/tests/helpers.nim b/tests/helpers.nim new file mode 100644 index 0000000..dad73b3 --- /dev/null +++ b/tests/helpers.nim @@ -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