From c4b23d73a9fdeabbf43a6c5f34417fc64ee6a9d3 Mon Sep 17 00:00:00 2001 From: Eric Mastro Date: Thu, 24 Feb 2022 22:15:45 +1100 Subject: [PATCH] feat: add support for suite before and after `before` executes async code before all tests in the suite. `after` executes async code after all tests in the suite. --- Readme.md | 12 ++++++++++-- asynctest/templates.nim | 19 ++++++++++++++++++- testmodules/stdlib/testbody.nim | 14 ++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 4576086..d783b88 100644 --- a/Readme.md +++ b/Readme.md @@ -33,12 +33,20 @@ proc someAsyncProc {.async.} = suite "test async proc": + setupAll: + # invoke await in the suite setup: + await someAsyncProc() + + teardownAll: + # invoke await in the suite teardown: + await someAsyncProc() + setup: - # invoke await in the test setup: + # invoke await in each test setup: await someAsyncProc() teardown: - # invoke await in the test teardown: + # invoke await in each test teardown: await someAsyncProc() test "async test": diff --git a/asynctest/templates.nim b/asynctest/templates.nim index 5666475..af575a7 100644 --- a/asynctest/templates.nim +++ b/asynctest/templates.nim @@ -1,6 +1,18 @@ template suite*(name, body) = + suite name: + # Runs before all tests in the suite + template setupAll(setupAllBody) {.used.} = + let b = proc {.async.} = setupAllBody + waitFor b() + + # Runs after all tests in the suite + template teardownAll(teardownAllBody) {.used.} = + template teardownAllIMPL: untyped {.inject.} = + let a = proc {.async.} = teardownAllBody + waitFor a() + template setup(setupBody) {.used.} = setup: let asyncproc = proc {.async.} = setupBody @@ -11,7 +23,12 @@ template suite*(name, body) = let asyncproc = proc {.async.} = teardownBody waitFor asyncproc() - let suiteproc = proc = body # Avoids GcUnsafe2 warnings with chronos + let suiteproc = proc = # Avoids GcUnsafe2 warnings with chronos + body + + when declared(teardownAllIMPL): + teardownAllIMPL() + suiteproc() template test*(name, body) = diff --git a/testmodules/stdlib/testbody.nim b/testmodules/stdlib/testbody.nim index 967fc52..b3a8ca0 100644 --- a/testmodules/stdlib/testbody.nim +++ b/testmodules/stdlib/testbody.nim @@ -15,3 +15,17 @@ suite "test async proc": test "async test": # invoke await in tests: await someAsyncProc() + +suite "test async setupAll and teardownAll, allow multiple suites": + + setupAll: + # invoke await in the test setup: + await someAsyncProc() + + teardownAll: + # invoke await in the test teardown: + await someAsyncProc() + + test "async test": + # invoke await in tests: + await someAsyncProc()