ZetCode

Tcl testing

last modified November 24, 2026 Tcl 8.6

Every non-trivial Tcl script needs a way to check that it still does what it was written to do. The tcltest package, bundled with Tcl, provides the test command, a result comparison engine, setup and cleanup hooks, constraints for platform-specific tests and a summary of the whole run. It is the framework used by Tcl's own test suite.

This article starts with one test and grows it into a small module with a test file and a suite runner. All examples target Tcl 8.6 and the tcltest 2.5.3 package that ships with it.

Why tcltest

Checking output by hand works until a change breaks something far away from where you are looking. A test framework records each check, compares the actual result with the expected one, and reports the failures in one place. The smallest useful test file loads the package, defines a test and calls cleanupTests.

first.tcl
package require tcltest
namespace import tcltest::*

test addition-1 {two plus three is five} {
    expr {2 + 3}
} 5

cleanupTests

The four arguments of test are the test name, a description, the body to evaluate and the expected result. The name should be unique inside the file, because it identifies the test in reports; the description is a human-readable summary. cleanupTests prints the summary and removes files created by tcltest helpers. Run the file with tclsh, exactly like any other script.

$ tclsh first.tcl
first.tcl:	Total	1	Passed	1	Skipped	0	Failed	0

Testing results and return codes

By default the result is compared with the expected value exactly. A longer body is written with -body and -result, which also opens the door to other options. An error raised by the body counts as a failure unless -returnCodes says that an error is expected. For looser comparisons, -match accepts glob or regexp.

results.tcl
package require tcltest
namespace import tcltest::*

proc divide {a b} {
    if {$b == 0} {
        error "division by zero"
    }
    return [expr {$a / $b}]
}

test divide-1 {integer division} {
    divide 10 2
} 5

test divide-2 {division by zero is an error} -body {
    divide 10 0
} -returnCodes error -result "division by zero"

test divide-3 {the result is matched exactly} -body {
    divide 9 2
} -result 4.5

cleanupTests

The second test passes because it expects the error text. The third one fails on purpose: Tcl's integer division returns 4 for 9 / 2, not 4.5. The report prints the body, the actual result and the expected result, which is usually enough to see whether the code or the expectation is wrong.

$ tclsh results.tcl


==== divide-3 the result is matched exactly FAILED
==== Contents of test case:

    divide 9 2

---- Result was:
4
---- Result should have been (exact matching):
4.5
==== divide-3 FAILED

results.tcl:	Total	3	Passed	2	Skipped	0	Failed	1

Setup and cleanup

Tests must not depend on the order in which they run. The -setup script prepares the environment before the body, and -cleanup removes it afterwards. All three scripts share the caller's scope, so a variable set in the setup is visible in the body and in the cleanup. The cleanup also runs when the body raises an error.

setup.tcl
package require tcltest
namespace import tcltest::*

test file-1 {the setup script creates the file} -setup {
    set f [open sample.txt w]
    puts $f "line one"
    close $f
} -body {
    file exists sample.txt
} -cleanup {
    file delete sample.txt
} -result 1

test file-2 {the previous cleanup removed the file} -body {
    file exists sample.txt
} -result 0

cleanupTests

The first test creates the file in its setup and deletes it in its cleanup. The second test proves that the deletion happened, so the two tests are independent. For files that only exist during a test run, tcltest also offers makeFile and removeFile, which keep the temporary directory tidy.

$ tclsh setup.tcl
setup.tcl:	Total	2	Passed	2	Skipped	0	Failed	0

Constraints

Some tests only make sense on a particular platform or with an optional package installed. A constraint lets such a test be skipped instead of failed. tcltest predefines unixOnly, winOnly and several others, and testConstraint defines your own.

constraints.tcl
package require tcltest
namespace import tcltest::*

testConstraint knownBug 0

test platform-1 {platform is unix} -constraints unixOnly -body {
    expr {$tcl_platform(platform) eq "unix"}
} -result 1

test later-1 {waiting for a fix} -constraints knownBug -body {
    expr {1 + 1}
} -result 2

cleanupTests

The platform test runs on this Linux machine, while knownBug is false, so the second test is skipped without evaluating its body. The summary counts the skipped test and names the constraint responsible, which keeps a known problem visible without breaking the run.

$ tclsh constraints.tcl
constraints.tcl:	Total	2	Passed	1	Skipped	1	Failed	0
Number of tests skipped for each constraint:
	1	knownBug

Grouping tests into files

Real projects split tests into .test files, usually one per module or feature. Each file loads tcltest, defines its tests and ends with cleanupTests, so it can also be run on its own. The summary line uses the file name, which makes a multi-file report readable.

text.test
package require tcltest
namespace import tcltest::*

proc initials {name} {
    set result ""
    foreach part $name {
        append result [string index $part 0]
    }
    return $result
}

test initials-1 {initials of a three part name} {
    initials {Jane Ann Doe}
} JAD

test initials-2 {initials of a single name} {
    initials {Peter}
} P

set failed $::tcltest::numTests(Failed)
cleanupTests
exit [expr {$failed > 0}]

The two tests cover a three-part name and a single name. The last three lines matter for automation: cleanupTests resets the counters, so the number of failures is saved first and turned into an exit status. A test file that exits with 1 can be detected by a shell script or a continuous integration job.

$ tclsh text.test
text.test:	Total	2	Passed	2	Skipped	0	Failed	0
$ echo $?
0

Running suites and checking exit status

A suite is a directory of .test files plus a runner. Tcl's own runAllTests command does this, but a short loop over glob shows what happens: every file runs as a child process, and its exit status decides whether the suite succeeds.

all.tcl
set dir [file dirname [file normalize [info script]]]
set status 0

foreach file [lsort [glob -directory $dir *.test]] {
    set name [file tail $file]
    if {[catch {exec [info nameofexecutable] $file} output]} {
        puts "FAILED: $name"
        set status 1
    } else {
        puts $output
    }
}

exit $status

glob -directory collects the test files, and lsort keeps the order stable. exec runs the current interpreter on each file, and catch notices a nonzero exit status. The runner prints the child's summary on success and a failure line otherwise. A failing test file makes the whole suite exit with 1.

$ tclsh all.tcl
text.test:	Total	2	Passed	2	Skipped	0	Failed	0
$ echo $?
0

A small module with tests

The final example puts a module and its tests together. The module is a plain Tcl file with a namespace that defines two procedures, and the test file loads it relative to its own location so the working directory does not matter.

stats.tcl
namespace eval ::stats {
    variable version 1.0

    proc mean {values} {
        set total 0
        foreach value $values {
            incr total $value
        }
        return [expr {double($total) / [llength $values]}]
    }

    proc median {values} {
        set sorted [lsort -real $values]
        set n [llength $sorted]
        set mid [expr {$n / 2}]
        if {$n % 2} {
            return [lindex $sorted $mid]
        }
        return [expr {([lindex $sorted $mid-1] + [lindex $sorted $mid]) / 2.0}]
    }
}

mean divides the sum by the number of values, and median sorts the list and picks the middle element, averaging the two middle elements for an even-sized list. The Tcl namespace command page explains the ::stats prefix used by the tests.

stats.test
package require tcltest
namespace import tcltest::*

source [file join [file dirname [info script]] stats.tcl]

test mean-1 {mean of three numbers} {
    ::stats::mean {2 4 6}
} 4.0

test mean-2 {mean of two numbers} {
    ::stats::mean {1 2}
} 1.5

test median-1 {median of an odd sized list} {
    ::stats::median {5 1 3}
} 3

test median-2 {median of an even sized list} {
    ::stats::median {1 2 3 4}
} 2.5

set failed $::tcltest::numTests(Failed)
cleanupTests
exit [expr {$failed > 0}]

The tests call the module through its namespace and compare the returned numbers. The source line uses file dirname [info script], so the test file finds stats.tcl in the same directory. The suite runner now finds both test files and reports two summary lines.

$ tclsh all.tcl
stats.test:	Total	4	Passed	4	Skipped	0	Failed	0
text.test:	Total	2	Passed	2	Skipped	0	Failed	0
$ echo $?
0

Source

The tcltest manual documents the test options, the configuration commands and the file layout used by larger suites.

This article moved from a single test to a test file with an exit status and a suite runner, then tested a small module. The Tcl catch command page explains the return codes used by the runner, and Tcl source command covers loading the module under test.

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 Tcl Tutorials.