ZetCode

Scheme unit testing

last modified November 25, 2026 Guile 3.0

A unit test is a small program that calls a procedure with known arguments and checks the result. A collection of such tests is run after every change, so that a mistake shows up at once instead of weeks later. Scheme has a standard testing library, SRFI 64, which Guile ships as the (srfi srfi-64) module. This article tests a small statistics module with it. The examples are run with GNU Guile 3.0.7.

A first test

A test suite starts with test-begin and ends with test-end, both given the name of the suite. Between them, test-equal compares an expected value with the value of an expression.

first.scm
(use-modules (srfi srfi-64))

(define (mean xs)
  (/ (apply + xs) (length xs)))

(test-begin "mean")

(test-equal 3 (mean '(1 2 3 4 5)))
(test-equal 5/2 (mean '(1 2 3 4)))
(test-equal 7 (mean '(7)))

(test-end "mean")

The procedure under test, mean, computes the arithmetic mean of a list. Each test-equal takes the expected value first and the expression second, and compares them with equal?. The second test expects the exact rational 5/2, because the mean of exact integers is exact. test-begin prints the name of the suite and the name of the log file; test-end prints the totals. A suite that passes says nothing about the individual tests.

$ guile first.scm
%%%% Starting test mean  (Writing full log to "mean.log")
# of expected passes      3

Reading a failure

A test earns its keep when it fails. Tests can have a name, given as an optional first argument, which appears in the report. The next program tests a median procedure that contains a bug.

failing.scm
(use-modules (srfi srfi-64))

(define (median xs)
  (let ((n (length xs)))
    (if (odd? n)
        (list-ref xs (quotient n 2))
        (/ (+ (list-ref xs (- (quotient n 2) 1))
              (list-ref xs (quotient n 2)))
           2))))

(test-begin "median")

(test-equal "odd count" 3 (median '(1 2 3 4 5)))
(test-equal "even count" 5/2 (median '(1 2 3 4)))
(test-equal "unsorted" 3 (median '(5 3 1 4 2)))

(test-end "median")

The median is the middle value of the sorted data; for an even count it is the mean of the two middle values. median takes the middle element but forgets to sort the list first. The first two tests pass, because their input happens to be sorted. The third reports FAIL with the file name, the line of the test, and its name.

The details are in the log file, named after the suite. For each test it records the source form, the result kind, and the actual and expected values. The grep command prints the entry of the failed test. The procedure returned 1, the third element of the unsorted list.

$ guile failing.scm
%%%% Starting test median  (Writing full log to "median.log")
failing.scm:15: FAIL unsorted
# of expected passes      2
# of unexpected failures  1
$ grep -A 7 'test-name: "unsorted"' median.log
  test-name: "unsorted"
  source-file: "failing.scm"
  source-line: 15
  source-form: (test-equal "unsorted" 3 (median (quote (5 3 1 4 2))))
Test end:
  result-kind: fail
  actual-value: 1
  expected-value: 3

Testing a module

Tests live in their own file, separate from the code they test. The code goes into a module, as described in the modules and libraries article, and the test file imports it. The stats.scm module holds the corrected median together with three more procedures.

stats.scm
(define-module (stats)
  #:export (mean median variance std-dev))

(define (mean xs)
  (when (null? xs)
    (error "mean: empty list"))
  (/ (apply + xs) (length xs)))

(define (median xs)
  (when (null? xs)
    (error "median: empty list"))
  (let ((v (list->vector (sort xs <)))
        (n (length xs)))
    (if (odd? n)
        (vector-ref v (quotient n 2))
        (/ (+ (vector-ref v (- (quotient n 2) 1))
              (vector-ref v (quotient n 2)))
           2))))

(define (variance xs)
  (let ((m (mean xs)))
    (mean (map (lambda (x) (* (- x m) (- x m))) xs))))

(define (std-dev xs)
  (sqrt (variance xs)))

median now sorts the list and copies it into a vector, so that the middle elements are reached by index. mean and median raise an error for an empty list, which a later section tests. variance is the mean of the squared distances from the mean, and std-dev, the standard deviation, is its square root.

stats-test.scm
(use-modules (srfi srfi-64)
             (stats))

(test-begin "stats")

(test-equal "mean" 5/2 (mean '(1 2 3 4)))
(test-equal "median of odd count" 3 (median '(5 3 1 4 2)))
(test-equal "median of even count" 5/2 (median '(4 1 3 2)))
(test-equal "variance" 4 (variance '(2 4 4 4 5 5 7 9)))
(test-equal "standard deviation" 2 (std-dev '(2 4 4 4 5 5 7 9)))

(test-end "stats")

The test file imports both SRFI 64 and the module. The test data for the variance is chosen so that the variance is the exact 4; sqrt of an exact square returns the exact 2, so the standard deviation can be compared with test-equal too. The -L . option adds the current directory to the load path, so that Guile finds stats.scm.

$ guile -L . stats-test.scm
%%%% Starting test stats  (Writing full log to "stats.log")
# of expected passes      5

Kinds of assertions

SRFI 64 has several checks besides test-equal. They differ in how they compare the values, as described in the booleans and equality article.

assertions.scm
(use-modules (srfi srfi-64)
             (stats))

(define data '(2.5 3.1 4.7 1.9))

(test-begin "assertions")

(test-assert "mean is positive" (positive? (mean data)))
(test-assert "median lies between min and max"
  (<= (apply min data) (median data) (apply max data)))

(test-eqv "exact mean" 3 (mean '(1 3 5)))
(test-eqv "inexact mean" 3.0 (mean '(1.0 3.0 5.0)))
(test-eq "empty list" '() (filter negative? data))

(test-equal "mean as float" 3.05 (mean data))
(test-approximate "mean within 1e-9" 3.05 (mean data) 1e-9)
(test-approximate "std-dev" 1.0428 (std-dev data) 0.0001)

(test-end "assertions")

test-assert passes when its expression returns a true value; it suits properties that are not a single expected value, such as the median lying between the minimum and the maximum. test-eqv compares with eqv? and test-eq with eq?. eqv? tells exact 3 from inexact 3.0, so the expected value must have the right exactness.

The test mean as float fails: the sum of the four floating point numbers divided by four is 3.0500000000000003, not 3.05. Inexact results should be checked with test-approximate, which takes an error margin as its last argument and passes when the actual value lies within it.

$ guile -L . assertions.scm
%%%% Starting test assertions  (Writing full log to "assertions.log")
assertions.scm:16: FAIL mean as float
# of expected passes      7
# of unexpected failures  1

Testing errors

Invalid input should be rejected, and that behaviour deserves tests too. test-error passes when its expression raises an exception, as described in the exceptions article.

errors.scm
(use-modules (srfi srfi-64)
             (stats))

(test-begin "errors")

(test-error "mean of empty list" #t (mean '()))
(test-error "median of empty list" #t (median '()))
(test-error "median of symbols" #t (median '(a b c)))

(test-error "no error raised" #t (mean '(1 2)))
(test-equal "error in an expression" 0 (variance '()))

(test-end "errors")

The second argument of test-error is the expected error type; #t accepts any exception. With only two arguments, the first one is taken as the type, not as the name, so a named test needs all three. SRFI 64 also allows a type such as a condition predicate, but Guile 3.0.7 does not check it: a test passes for any exception, whatever type is given.

The two failures show the opposite cases. no error raised fails because (mean '(1 2)) returns normally. In error in an expression, variance raises an error inside test-equal. The test fails, and the error does not stop the suite; the log records it as actual-error.

$ guile -L . errors.scm
%%%% Starting test errors  (Writing full log to "errors.log")
errors.scm:10: FAIL no error raised
errors.scm:11: FAIL error in an expression
# of expected passes      3
# of unexpected failures  2
$ grep -A 8 'test-name: "error in' errors.log
  test-name: "error in an expression"
  source-file: "errors.scm"
  source-line: 11
  source-form: (test-equal "error in an expression" 0 (variance (quote ())))
Test end:
  result-kind: fail
  actual-value: #f
  actual-error: (misc-error #f "mean: empty list" () #f)
  expected-value: 0

Test groups

Larger suites are divided into groups. A group is a nested pair of test-begin and test-end; the test-group form wraps the pair around its body.

groups.scm
(use-modules (srfi srfi-64)
             (stats))

(test-begin "stats")

(test-group "mean"
  (test-equal "integers" 2 (mean '(1 2 3)))
  (test-equal "fraction" 1/2 (mean '(0 1)))
  (test-error "empty" #t (mean '())))

(test-group "median"
  (test-equal "odd" 2 (median '(3 1 2)))
  (test-equal "even" 3 (median '(4 1 2 6))))

(test-begin "spread")
(test-equal "variance of equal values" 0 (variance '(5 5 5)))
(test-equal "std-dev of equal values" 0 (std-dev '(5 5 5)))
(test-end "spread")

(test-end "stats")

The mean and median groups use test-group; the spread group uses an explicit test-begin and test-end. The name given to test-end must match the open group; a mismatch is an error. The console report counts the tests of all groups together, and the log file marks where each group begins and ends.

$ guile -L . groups.scm
%%%% Starting test stats  (Writing full log to "stats.log")
# of expected passes      7
$ grep Group stats.log
Group begin: stats
Group begin: mean
Group end: mean
Group begin: median
Group end: median
Group begin: spread
Group end: spread
Group end: stats

Table-driven tests

When many tests differ only in their data, the data can be written as a table and the tests generated with a loop. Adding a case is then a matter of adding a row.

table.scm
(use-modules (srfi srfi-64)
             (stats))

(define median-cases
  '(("single value" (7) 7)
    ("two values" (1 4) 5/2)
    ("odd count" (9 1 5) 5)
    ("even count" (8 2 6 4) 5)
    ("negative values" (-3 -1 -2) -2)
    ("duplicates" (2 2 9 2) 2)
    ("unsorted floats" (0.5 2.5 1.5) 1.5)))

(test-begin "median-table")

(for-each
 (lambda (row)
   (let ((name (car row))
         (input (cadr row))
         (expected (caddr row)))
     (test-equal name expected (median input))))
 median-cases)

(test-end "median-table")

Each row of median-cases holds a test name, the input list, and the expected median. for-each calls test-equal for every row, so the seven rows produce seven named tests. Because the test names come from the table, a failure report still says which case broke.

$ guile -L . table.scm
%%%% Starting test median-table  (Writing full log to "median-table.log")
# of expected passes      7

The exit status

Test suites are often run by a build tool or a continuous integration server, which decides success by the exit status of the program. A Guile test file exits with status 0 even when tests fail, so the status has to be set by hand.

status.scm
(use-modules (srfi srfi-64)
             (stats))

(test-begin "status")

(test-equal "mean" 2 (mean '(1 2 3)))
(test-equal "median" 2 (median '(1 2 3 10)))

(define runner (test-runner-current))
(test-end "status")

(let ((failed (+ (test-runner-fail-count runner)
                 (test-runner-xpass-count runner))))
  (format #t "~a test(s) failed~%" failed)
  (exit (zero? failed)))

test-runner-current returns the test runner, the object that runs the tests and counts the results. The runner is saved before the outermost test-end, which resets the current runner to #f; the saved runner keeps its counts. test-runner-fail-count counts unexpected failures and test-runner-xpass-count unexpected successes, described in the next section. (exit #f) ends the program with status 1, as shown in the command-line arguments article.

$ guile -L . status.scm
%%%% Starting test status  (Writing full log to "status.log")
status.scm:7: FAIL median
# of expected passes      1
# of unexpected failures  1
1 test(s) failed
$ echo $?
1

Skipping tests and expected failures

Some tests are too slow to run every time, and some fail because of a known problem that will be fixed later. SRFI 64 can skip the first kind and mark the second as expected to fail.

skipping.scm
(use-modules (srfi srfi-64)
             (stats))

(test-begin "skipping")

(test-skip "slow")
(test-equal "slow" 500000 (mean (iota 1000001)))
(test-equal "fast" 2 (mean '(1 2 3)))

(test-skip 2)
(test-equal "skipped 1" 1 (mean '(1)))
(test-equal "skipped 2" 2 (mean '(2)))
(test-equal "runs again" 3 (mean '(3)))

(test-expect-fail "vector input")
(test-equal "vector input" 2 (median #(3 1 2)))

(test-expect-fail 1)
(test-equal "fixed" 5 (median '(4 6)))

(test-end "skipping")

test-skip takes a test name or a count. With a name, it skips the next test of that name; with a count, it skips that many of the following tests. test-expect-fail works the same way, but runs the test: a failure is counted as an expected failure and does not count against the suite.

median works on lists, so the vector input fails as expected. The test named fixed was marked to fail, but it passes; SRFI 64 reports it as XPASS, an unexpected success. It is a signal that the problem is gone and the marker should be removed.

$ guile -L . skipping.scm
%%%% Starting test skipping  (Writing full log to "skipping.log")
skipping.scm:19: XPASS fixed
# of expected passes      2
# of expected failures    1
# of unexpected successes 1
# of skipped tests        3

A custom test runner

The default runner prints only failures and totals, and writes a log file. A custom runner can report in any format. It is built from test-runner-null, which does nothing, by installing procedures that the runner calls at certain events.

runner.scm
(use-modules (srfi srfi-64)
             (stats))

(define (compact-runner)
  (let ((runner (test-runner-null)))
    (test-runner-on-test-end! runner
      (lambda (r)
        (let ((kind (test-result-kind r)))
          (format #t "~a ~a~%"
                  (if (memq kind '(pass xfail)) "ok  " "FAIL")
                  (test-runner-test-name r))
          (when (eq? kind 'fail)
            (format #t "     expected: ~s~%     actual:   ~s~%"
                    (test-result-ref r 'expected-value)
                    (test-result-ref r 'actual-value))))))
    (test-runner-on-final! runner
      (lambda (r)
        (format #t "~a passed, ~a failed~%"
                (test-runner-pass-count r)
                (test-runner-fail-count r))))
    runner))

(test-runner-current (compact-runner))

(test-begin "stats")
(test-equal "mean" 5/2 (mean '(1 2 3 4)))
(test-equal "median" 4 (median '(1 2 4 8)))
(test-equal "variance" 0 (variance '(3 3 3)))
(test-error "empty" #t (median '()))
(test-end "stats")

test-runner-on-test-end! installs a procedure that is called after each test with the runner as its argument. test-result-kind returns the result as a symbol: pass, fail, xpass, xfail, or skip. test-result-ref reads the values that the default runner writes to its log. test-runner-on-final! is called when the outermost suite ends. Calling test-runner-current with an argument makes the new runner current before test-begin. This runner writes no log file.

$ guile -L . runner.scm
ok   mean
FAIL median
     expected: 4
     actual:   3
ok   variance
ok   empty
3 passed, 1 failed

Source

SRFI-64 — GNU Guile Reference Manual

SRFI 64: A Scheme API for test suites

In this article we have tested Scheme code with SRFI 64: we have written a first suite, read a failure and the log file, tested a module, used the different assertions, tested for errors, grouped tests, generated tests from a table, set the exit status, skipped tests and marked expected failures, and written a custom test runner. The modules and libraries article shows how to organise the code under test, and the small interpreter article builds a program that is worth testing this way.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.