Unit testing of asynchrononous code in Nim
Go to file
Ben 5154c0d79d
bumps ci to nim 1.6.18
2024-08-14 10:44:49 +02:00
.github/workflows bumps ci to nim 1.6.18 2024-08-14 10:44:49 +02:00
asynctest add exception handling for Chronos V4 2024-01-15 19:28:09 -03:00
testmodules add exception handling for Chronos V4 2024-01-15 19:28:09 -03:00
.editorconfig Asynchronous testing in Nim 2021-01-11 13:35:19 +01:00
.gitignore Fix local dependencies in tests 2023-08-28 17:35:03 +02:00
License.md Add license 2022-01-10 11:14:39 +01:00
Readme.md version 0.5.2 2024-08-14 10:11:51 +02:00
asynctest.nim Add helpful compiler errors on old import paths 2024-01-09 11:40:31 +01:00
asynctest.nimble version 0.5.2 2024-08-14 10:11:51 +02:00
config.nims Add setup files (#2) 2022-07-12 23:30:36 +03:00
nimble.lock Add setup files (#2) 2022-07-12 23:30:36 +03:00

Readme.md

asynctest

Complements the standard unittest module in Nim to allow testing of asynchronous code.

Installation

Use the Nimble package manager to add asynctest to an existing project. Add the following to its .nimble file:

requires "asynctest >= 0.5.2 & < 0.6.0"

Usage

Replace import unittest with one of the following imports, and you can await asynchronous calls in tests, setup and teardown.

When you use Nim's standard library only (asyncdispatch and unittest):

import asynctest/asyncdispatch/unittest

When you use chronos or unittest2, pick the import that matches your choices:

import asynctest/asyncdispatch/unittest2  # standard async and unittest2
import asynctest/chronos/unittest         # chronos and standard unittest
import asynctest/chronos/unittest2        # chronos and unittest2

Example


import asynctest/asyncdispatch/unittest

proc someAsyncProc {.async.} =
  # perform some async operations using await

suite "test async proc":

  setup:
    # invoke await in each test setup:
    await someAsyncProc()

  teardown:
    # invoke await in each test teardown:
    await someAsyncProc()

  test "async test":
    # invoke await in tests:
    await someAsyncProc()

check eventually

When you find yourself adding calls to sleepAsync to your tests, you might want to consider using check eventually instead. It will repeatedly check an expression until it becomes true. It has a built-in timeout of 5 seconds that you can override.

var x: int

proc slowProcedure {.async.} =
  # perform a slow operation
  x = 42

let future = slowProcedure()
check eventually x == 42
await future

setupAll and teardownAll

The setup and teardown code runs before and after every test, just like the standard unittest module. In addition we provide setupAll and teardownAll. The setupAll code runs once before all tests in the suite, and the teardownAll runs once after all tests in the suite. Use these only as a last resort when setting up the test environment is very costly. Be careful that the tests do not modify the environment that you set up, lest you introduce dependencies between tests.