Testing And Benchmarking in Nim

Here’s the translation of the Go testing and benchmarking example to Nim:

Unit testing is an important part of writing principled Nim programs. The unittest module provides the tools we need to write unit tests.

For the sake of demonstration, this code is in the main module, but it could be any module. Testing code typically lives in the same module as the code it tests.

import unittest

# We'll be testing this simple implementation of an
# integer minimum. Typically, the code we're testing
# would be in a source file named something like
# `intutils.nim`, and the test file for it would then
# be named `intutils_test.nim`.

proc intMin(a, b: int): int =
  if a < b: a else: b

# A test is created by using the `test` macro from the unittest module.
test "basic test":
  check(intMin(2, -2) == -2)

# Writing tests can be repetitive, so it's idiomatic to
# use a table-driven style, where test inputs and
# expected outputs are listed in a sequence and a single loop
# walks over them and performs the test logic.

test "table-driven test":
  let tests = @[
    (a: 0, b: 1, want: 0),
    (a: 1, b: 0, want: 0),
    (a: 2, b: -2, want: -2),
    (a: 0, b: -1, want: -1),
    (a: -1, b: 0, want: -1)
  ]

  for tt in tests:
    check(intMin(tt.a, tt.b) == tt.want)

# Benchmark tests in Nim are typically created using
# the `bench` macro from a benchmarking library like `benchy`.
# Here's an example of how it might look:

import benchy

bench intMinBench:
  for i in 1..1_000_000:
    discard intMin(1, 2)

To run the tests, you would typically use the Nim compiler with the --run flag:

$ nim c -r test_file.nim
[Suite] basic test
  [OK] basic test
[Suite] table-driven test
  [OK] table-driven test

To run benchmarks, you would use a similar command, but the output would depend on the benchmarking library used.

In Nim, the testing and benchmarking approach is slightly different from some other languages. The unittest module provides a convenient way to write and run tests, while benchmarking often requires additional libraries. The overall concepts of unit testing and benchmarking remain similar, allowing developers to ensure correctness and measure performance of their Nim code.