Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท FFI and Tooling

Testing and Debugging Nim Programs

Learn to test Nim code with std/unittest, assert and doAssert, use compiler flags such as --checks and -d:release, debug with echo and gdb, and read stack traces.

Nim catches many mistakes at compile time, but logic errors still need tests, and surprises still need debugging. The standard library has a unit-testing module, the compiler has switches that turn safety checks on and off, and because Nim compiles to C, you can use the usual native debuggers.

The Nim compiler is not available on this site, so the Nim code is read-only; the C stand-ins model a small test runner and an assertion macro to show how the pieces work.

assert and doAssert

assert checks a condition while developing and is removed in release builds (-d:release). doAssert always runs. Use assert for internal assumptions and doAssert for conditions that must hold even in production.

NIM
proc average(xs: openArray[float]): float =
  assert xs.len > 0, "average of nothing"
  var total = 0.0
  for x in xs: total += x
  total / xs.len.float

doAssert average([1.0, 2.0, 3.0]) == 2.0

A failed assertion stops the program with the message and the line. The stand-in implements the same idea, including the file and line reporting:

C C stand-in: an assertion macro with line info

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

std/unittest

For real projects use std/unittest. Put files in tests/ and run nimble test (see Nimble and Packages).

NIM
import std/unittest

suite "average":
  test "plain numbers":
    check average([1.0, 2.0, 3.0]) == 2.0

  test "single value":
    check average([5.0]) == 5.0

  test "empty input raises":
    expect AssertionDefect:
      discard average(newSeq[float]())

  setup:
    echo "runs before each test"

check prints both sides of a failing comparison, which makes failures easier to read than a bare assert. expect verifies that a block raises a specific exception type. suite, setup and teardown group tests. Output lists [OK] or [FAILED] per test and a summary.

Run one test by name with nim c -r tests/test1.nim "average::plain numbers" or set the NIMTEST_NO_COLOR environment variable for plain logs in CI.

Compiler switches

Switch Effect
-d:release Optimize, drop assert and many checks
-d:danger Release plus remove all run-time checks (overflow, bounds)
--checks:on Keep range, index and overflow checks
--stackTrace:on --lineTrace:on Detailed stack traces
--debugger:native Emit debug info for gdb/lldb
--warnings:on --hints:on Show diagnostics

By default (nim c), a debug build, an out-of-range index raises IndexDefect, and integer overflow raises OverflowDefect. The stand-in shows how a checked access differs from unchecked C:

C C stand-in: a checked index like Nim's debug build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Debugging techniques

  1. echo and debugEcho: quick, and repr(x) shows structure of any value.
  2. Read the stack trace. Nim prints the chain of procs with file and line; the bottom entry is where the error was raised.
  3. when defined(debug): blocks: put expensive checks behind a define.
  4. --debugger:native with gdb or lldb: nim c --debugger:native app.nim, then gdb ./app. Nim identifiers appear with a mangled suffix in the C code, which the debugger shows.
  5. --passC:-fsanitize=address: run the generated C under AddressSanitizer to find memory errors when using ptr or FFI.
  6. nim check file.nim type checks without compiling and finds errors fast.

Exceptions are ordinary objects. Catch them in a try and print getCurrentExceptionMsg(); use defer to run cleanup. raise newException(ValueError, "...") makes your own. For failures that are bugs and should not be caught (index out of range, nil access), Nim raises defects, which derive from Defect and are not normally handled.

Writing good tests

  • Test one behavior per test, with names that read as sentences.
  • Cover edges: empty input, one element, the largest and smallest values.
  • Keep tests deterministic: seed random numbers, and avoid the clock and network.
  • Test the public API of a module; avoid reaching into private fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which check disappears in a -d:release build?

    assert is for development; doAssert always runs.
  2. 2. What does expect AssertionDefect: verify?

    expect passes only when the given exception is raised.
  3. 3. Which flag keeps debug info for gdb?

    It emits debug symbols for native debuggers.
  4. 4. What does nim check do?

    It reports compile errors quickly.

Summary

  • assert is for development, doAssert always runs.
  • std/unittest provides suite, test, check, expect.
  • Compiler switches control optimization and safety checks.
  • Use stack traces, --debugger:native and sanitizers to find bugs.

Next: Project: Word Counter