tcltest(3tcl)

πŸ’… NAME

okay bestie, this is tcltest(3tcl) from Tcl Bundled Packages β€” and it's literally test harness support code and utilities. That's the whole vibe. πŸŽ€


✨ SYNOPSIS

package require tcltest ?2.5?

tcltest::test name description ?-option value ...?
tcltest::test name description ?constraints? body result

tcltest::loadTestedCommands
tcltest::makeDirectory name ?directory?
tcltest::removeDirectory name ?directory?
tcltest::makeFile contents name ?directory?
tcltest::removeFile name ?directory?
tcltest::viewFile name ?directory?
tcltest::cleanupTests ?runningMultipleTests?
tcltest::runAllTests

tcltest::configure
tcltest::configure -option
tcltest::configure -option value ?-option value ...?
tcltest::customMatch mode command
tcltest::testConstraint constraint ?value?
tcltest::outputChannel ?channel?
tcltest::errorChannel ?channel?
tcltest::interpreter ?interp?

tcltest::debug ?level?
tcltest::errorFile ?filename?
tcltest::limitConstraints ?boolean?
tcltest::loadFile ?filename?
tcltest::loadScript ?script?
tcltest::match ?patternList?
tcltest::matchDirectories ?patternList?
tcltest::matchFiles ?patternList?
tcltest::outputFile ?filename?
tcltest::preserveCore ?level?
tcltest::singleProcess ?boolean?
tcltest::skip ?patternList?
tcltest::skipDirectories ?patternList?
tcltest::skipFiles ?patternList?
tcltest::temporaryDirectory ?directory?
tcltest::testsDirectory ?directory?
tcltest::verbose ?level?

tcltest::test name description optionList
tcltest::normalizeMsg msg
tcltest::normalizePath pathVar
tcltest::workingDirectory ?dir?

🌸 DESCRIPTION

The tcltest package provides several utility commands useful in the construction of test suites for code instrumented to be run by evaluation of Tcl commands. Notably the built-in commands of the Tcl library itself are tested by a test suite using the tcltest package. iconic behavior, honestly. ✨

All the commands provided by the tcltest package are defined in and exported from the ::tcltest namespace, as indicated in the SYNOPSIS above. In the following sections, all commands will be described by their simple names, in the interest of brevity.

The central command of tcltest is test that defines and runs a test. Testing with test involves evaluation of a Tcl script and comparing the result to an expected result, as configured and controlled by a number of options. Several other commands provided by tcltest govern the configuration of test and the collection of many test commands into test suites.

See CREATING TEST SUITES WITH TCLTEST below for an extended example of how to use the commands of tcltest to produce test suites for your Tcl-enabled code. 🫢


πŸ› οΈ COMMANDS

test name description ?-option value ...?

Defines and possibly runs a test with the name name and description description. The name and description of a test are used in messages reported by test during the test, as configured by the options of tcltest. The remaining option value arguments to test define the test, including the scripts to run, the conditions under which to run them, the expected result, and the means by which the expected and actual results should be compared. See TESTS below for a complete description of the valid options and how they define a test. The test command returns an empty string. πŸ’…

test name description ?constraints? body result

This form of test is provided to support test suites written for version 1 of the tcltest package, and also a simpler interface for a common usage. It is the same as test name description -constraints constraints -body body -result result. All other options to test take their default values. When constraints is omitted, this form of test can be distinguished from the first because all options begin with -. πŸŽ€

loadTestedCommands

Evaluates in the caller's context the script specified by configure -load or configure -loadfile. Returns the result of that script evaluation, including any error raised by the script. Use this command and the related configuration options to provide the commands to be tested to the interpreter running the test suite. very "bring your own commands to the function" energy. ✨

makeFile contents name ?directory?

Creates a file named name relative to directory directory and writes contents to that file using the encoding encoding system. If contents does not end with a newline, a newline will be appended so that the file named name does end with a newline. Because the system encoding is used, this command is only suitable for making text files. The file will be removed by the next evaluation of cleanupTests, unless it is removed by removeFile first. The default value of directory is the directory configure -tmpdir. Returns the full path of the file created. Use this command to create any text file required by a test with contents as needed. πŸ“

removeFile name ?directory?

Forces the file referenced by name to be removed. This file name should be relative to directory. The default value of directory is the directory configure -tmpdir. Returns an empty string. Use this command to delete files created by makeFile. 🧚

makeDirectory name ?directory?

Creates a directory named name relative to directory directory. The directory will be removed by the next evaluation of cleanupTests, unless it is removed by removeDirectory first. The default value of directory is the directory configure -tmpdir. Returns the full path of the directory created. Use this command to create any directories that are required to exist by a test. πŸ’–

removeDirectory name ?directory?

Forces the directory referenced by name to be removed. This directory should be relative to directory. The default value of directory is the directory configure -tmpdir. Returns an empty string. Use this command to delete any directories created by makeDirectory. 🌸

viewFile file ?directory?

Returns the contents of file, except for any final newline, just as read -nonewline would return. This file name should be relative to directory. The default value of directory is the directory configure -tmpdir. Use this command as a convenient way to turn the contents of a file generated by a test into the result of that test for matching against an expected result. The contents of the file are read using the system encoding, so its usefulness is limited to text files. πŸ¦‹

cleanupTests

Intended to clean up and summarize after several tests have been run. Typically called once per test file, at the end of the file after all tests have been completed. For best effectiveness, be sure that the cleanupTests is evaluated even if an error occurs earlier in the test file evaluation. do not skip this one, bestie β€” it's the after-party cleanup. 😭

Prints statistics about the tests run and removes files that were created by makeDirectory and makeFile since the last cleanupTests. Names of files and directories in the directory configure -tmpdir created since the last cleanupTests, but not created by makeFile or makeDirectory are printed to outputChannel. This command also restores the original shell environment, as described by the global env array. Returns an empty string. ✨

runAllTests

This is a main command meant to run an entire suite of tests, spanning multiple files and/or directories, as governed by the configurable options of tcltest. See RUNNING ALL TESTS below for a complete description of the many variations possible with runAllTests. πŸ‘‘

βš™οΈ CONFIGURATION COMMANDS

configure

Returns the list of configurable options supported by tcltest. See CONFIGURABLE OPTIONS below for the full list of options, their valid values, and their effect on tcltest operations. πŸ’…

configure option

Returns the current value of the supported configurable option option. Raises an error if option is not a supported configurable option. πŸŽ€

configure option value ?-option value ...?

Sets the value of each configurable option option to the corresponding value value, in order. Raises an error if an option is not a supported configurable option, or if value is not a valid value for the corresponding option, or if a value is not provided. When an error is raised, the operation of configure is halted, and subsequent option value arguments are not processed. so yeah, one bad option and the whole little parade stops. πŸ›‘

If the environment variable ::env(TCLTEST_OPTIONS) exists when the tcltest package is loaded (by package require tcltest) then its value is taken as a list of arguments to pass to configure. This allows the default values of the configuration options to be set by the environment. 🌈

customMatch mode script

Registers mode as a new legal value of the -match option to test. When the -match mode option is passed to test, the script script will be evaluated to compare the actual result of evaluating the body of the test to the expected result. To perform the match, the script is completed with two additional words, the expected result, and the actual result, and the completed script is evaluated in the global namespace. The completed script is expected to return a boolean value indicating whether or not the results match. The built-in matching modes of test are exact, glob, and regexp. πŸ”₯

testConstraint constraint ?boolean?

Sets or returns the boolean value associated with the named constraint. See TEST CONSTRAINTS below for more information. πŸ’œ

interpreter ?executableName?

Sets or returns the name of the executable to be execed by runAllTests to run each test file when configure -singleproc is false. The default value for interpreter is the name of the currently running program as returned by info nameofexecutable. yes, "execed" is the word. we respect it. πŸ™ˆ

outputChannel ?channel?

Sets or returns the output channel. This defaults to stdout. Any test that prints test related output should send that output to outputChannel rather than letting that output default to stdout. ✨

  • errorChannel ?channel? β€” gets or sets the error channel πŸ’… it defaults to stderr, obviously. And bestie, if any of your tests print error messages, pls pls pls send that output to errorChannel instead of yeeting it straight at stderr πŸ™ˆ we're classy here.

πŸŽ€ SHORTCUT CONFIGURATION COMMANDS πŸŽ€

okay so these are literally just the glow-up versions of the config commands β€” every single one is a lil shortcut that does the same thing as its long-form cousin ✨ no cap:

  • debug ?level? β€” same as configure -debug ?level?.
  • errorFile ?filename? β€” same as configure -errfile ?filename?.
  • limitConstraints ?boolean? β€” same as configure -limitconstraints ?boolean?.
  • loadFile ?filename? β€” same as configure -loadfile ?filename?.
  • loadScript ?script? β€” same as configure -load ?script?.
  • match ?patternList? β€” same as configure -match ?patternList?.
  • matchDirectories ?patternList? β€” same as configure -relateddir ?patternList?.
  • matchFiles ?patternList? β€” same as configure -file ?patternList?.
  • outputFile ?filename? β€” same as configure -outfile ?filename?.
  • preserveCore ?level? β€” same as configure -preservecore ?level?.
  • singleProcess ?boolean? β€” same as configure -singleproc ?boolean?.
  • skip ?patternList? β€” same as configure -skip ?patternList?.
  • skipDirectories ?patternList? β€” same as configure -asidefromdir ?patternList?.
  • skipFiles ?patternList? β€” same as configure -notfile ?patternList?.
  • temporaryDirectory ?directory? β€” same as configure -tmpdir ?directory?.
  • testsDirectory ?directory? β€” same as configure -testdir ?directory?.
  • verbose ?level? β€” same as configure -verbose ?level?.

πŸ’€ OTHER COMMANDS πŸ’€

so the rest of the commands that tcltest hands out? yeah, they've got better alternatives now β€” either from tcltest itself or from Tcl. They're still hanging around to keep your existing test suites from breaking, but bestie... don't use them in new code, okay? fr fr. 🫢

  • test name description optionList β€” ngl this form of test existed so you could pass a whole bunch of options spanning several lines as one single argument wrapped in braces, instead of having to backslash-quote every newline between the args πŸ’€ The optionList argument is supposed to be a list with an even number of elements, representing option and value arguments to pass to test. But here's the tea: those values are not passed directly, like they are in the alternate forms of switch. Instead, this form makes an unfortunate attempt to overthrow Tcl's substitution rules by performing substitutions on some of the list elements, basically trying to implement a "do what I mean" interpretation of a brace-enclosed "block". The result? nearly impossible to document clearly, which is exactly why this form is not recommended. Go look at the examples in CREATING TEST SUITES WITH TCLTEST below to see that this form is really not necessary to avoid backslash-quoted newlines πŸ’… And if you, for some reason, insist on using it? Examine the source code of tcltest if you want to know the substitution details, or just enclose the third through last argument to test in braces and hope for the best πŸ˜­πŸ™
  • workingDirectory ?directoryName? β€” sets or returns the current working directory while the test suite is running πŸƒβ€β™€οΈ the default value for workingDirectory is the directory in which the test suite was launched. The Tcl commands cd and pwd are sufficient replacements, so like... you don't need this one.
  • normalizeMsg msg β€” returns the result of removing the "extra" newlines from msg, where "extra" is, and I quote, rather imprecise πŸ’€ Tcl offers plenty of string processing commands to modify strings as you wish, and customMatch allows flexible matching of actual and expected results β€” so yeah, plenty of options, boo.
  • normalizePath pathVar β€” resolves symlinks in a path, thus creating a path without internal redirection ✨ it's assumed that pathVar is absolute, and heads up: pathVar is modified in place. The Tcl command file normalize is a sufficient replacement 🌸

πŸ¦‹ TESTS πŸ¦‹

The test command is literally the heart of the tcltest package πŸ’– its essential function? Evaluate a Tcl script and compare the result against an expected result. The options of test define the test script, the environment in which to evaluate it, the expected result, and how to compare the actual result to the expected result. And side note: some configuration options of tcltest also influence how test operates πŸ‘‘

The valid options for test are summarized:

test name description
        ?-constraints keywordList|expression?
        ?-setup setupScript?
        ?-body testScript?
        ?-cleanup cleanupScript?
        ?-result expectedAnswer?
        ?-output expectedOutput?
        ?-errorOutput expectedError?
        ?-returnCodes codeList?
        ?-errorCode expectedErrorCode?
        ?-match mode?

The name can be literally any string, but the convention is to pick a name following this pattern:

target-majorNum.minorNum

For white-box (regression) tests, target should be the name of the C function or Tcl procedure being tested πŸ§ͺ For black-box tests, target should be the name of the feature being tested. Some conventions call for the names of black-box tests to have the suffix _bb. Related tests should share a major number. And as a test suite evolves, it's best to have the same test name keep corresponding to the same test, so it stays meaningful to say things like "Test foo-1.3 passed in all releases up to 3.4, but began failing in release 3.5." πŸ“ˆ (iconic sentence honestly)

During evaluation of test, the name will be compared to the lists of string matching patterns returned by configure -match and configure -skip. The test runs only if name matches any of the patterns from configure -match and matches none of the patterns from configure -skip. Simple as.

The description should be a short textual description of the test. It gets included in output produced by the test β€” typically test failure messages. Good description values should briefly explain the purpose of the test to users of a test suite πŸ‘―β€β™€οΈ The name of a Tcl or C function being tested should be included in the description for regression tests. And if the test case exists to reproduce a bug, include the bug ID in the description πŸ›

Valid attributes and associated values are:

  • -constraints keywordList|expression β€” the optional -constraints attribute can be a list of one or more keywords, or an expression. If the -constraints value is a list of keywords, each of those keywords should be the name of a constraint defined by a call to testConstraint. If any of the listed constraints is false or does not exist, the test is skipped. If the -constraints value is an expression, that expression is evaluated β€” and if the expression evaluates to true, then the test is run ✨
Heads up bestie: the expression form of -constraints may interfere with the operation of configure -constraints and configure -limitconstraints, and it is not recommended πŸ’€

Appropriate constraints should be added to any tests that shouldn't always be run. Like, conditional evaluation of a test should be accomplished by the -constraints option, not by conditional evaluation of test. That way, the same number of tests are always reported by the test suite β€” though the number skipped may change based on the testing environment 🌈 The default value is an empty list. See TEST CONSTRAINTS below for a list of built-in constraints and info on how to add your own πŸŽ€

  • -setup script β€” the optional -setup attribute indicates a script that runs before the script indicated by the -body attribute. If evaluation of script raises an error, the test fails. The default value is an empty script. 🫧
  • -body script β€” the -body attribute indicates the script to run to carry out the test, which must return a result that can be checked for correctness. If evaluation of script raises an error, the test fails β€” unless the -returnCodes option is used to state that an error is expected πŸ‘€ The default value is an empty script.
  • -cleanup script β€” the optional -cleanup attribute indicates a script that runs after the script indicated by the -body attribute. If evaluation of script raises an error, the test fails. The default value is an empty script. 🧹
  • -match mode β€” the -match attribute determines how expected answers supplied by -result, -output, and -errorOutput are compared. Valid values for mode are regexp, glob, exact, and any value registered by a prior call to customMatch. The default value is exact. 🎯
  • -result expectedValue β€” the -result attribute supplies the expectedValue against which the return value from script will be compared. The default value is an empty string.
  • -output expectedValue β€” the -output attribute supplies the expectedValue against which any output sent to stdout or outputChannel during evaluation of the script(s) will be compared. Note that only output printed using the global puts command is used for comparison πŸ‘€ If -output is not specified, output sent to stdout and outputChannel is not processed for comparison.
  • -errorOutput expectedValue β€” the -errorOutput attribute supplies the expectedValue against which any output sent to stderr or errorChannel during evaluation of the script(s) will be compared. Note that only output printed using the global puts command is used for comparison πŸ‘€ If -errorOutput is not specified, output sent to stderr and errorChannel is not processed for comparison.
  • -returnCodes expectedCodeList β€” the optional -returnCodes attribute supplies expectedCodeList, a list of return codes that may be accepted from evaluation of the -body script. If evaluation of the -body script returns a code not in the expectedCodeList, the test fails. All return codes known to return, in both numeric and symbolic form β€” including extended return codes β€” are acceptable elements in the expectedCodeList. Default value is <yellow>ok return</yellow> ✨
  • -errorCode expectedErrorCode β€” okay so this one's ✨optional✨, and it's a glob pattern. It gets matched against the error code that comes back when the -body script gets evaluated, and bestie, if that returned code doesn't match your expectedErrorCode? The test fails, no cap πŸ’€. The default value is literally just * (yes, matches everything, she's flexible). And heads up: if -returnCodes doesn't already include error, it gets set to error. Periodt.

So here's the vibe check for a test to actually pass 🫢: it has to successfully evaluate its -setup, -body, and -cleanup scripts. The return code of the -body script and its result have to match the expected values. And if those were specified, the output and error data from the test have to match the expected -output and -errorOutput values. If any of these conditions aren't met? Test fails, that's it, that's the law πŸ’…. Oh and btw β€” all the scripts are evaluated in the context of the caller of test.

And listen β€” as long as you call test with valid syntax and legal values for all the attributes, it will not raise an error. Not me being dramatic, that's just the design πŸŽ€. Test failures get reported as output written to outputChannel instead. In default operation, a successful test produces no output (silence is golden, queen behavior πŸ‘‘). The output messages that test produces are controlled by the configure -verbose option, detailed down in CONFIGURABLE OPTIONS below. And any output that the test scripts themselves produce should go through puts to outputChannel or errorChannel β€” that way everyone using the test suite can easily capture output with the configure -outfile and configure -errfile options, and so the -output and -errorOutput attributes actually work the way they're supposed to. Teamwork makes the dream work 🌈✨


πŸŽ€ TEST CONSTRAINTS πŸŽ€

So constraints are basically the bouncers of the test world β€” they determine whether or not a test should be skipped πŸ™ˆ. Every constraint has a name (which, bestie, can be any string) and a boolean value. Every test has a -constraints value which is a list of constraint names. And there are two modes of constraint control, so let's get into it πŸ’….

🌸 Mode 1: the default (the chill one)

Most of the time you're using the default mode, indicated by setting configure -limitconstraints to false. The test will run only if all constraints in the list are true-valued. So the -constraints option of test is a super convenient, symbolic way to define whatever conditions are required for the test to be possible or meaningful, iykyk ✨. For example β€” a test with -constraints unix will only be run if the constraint unix is true, which means the test suite is being run on a Unix platform 🐧.

Each test should include whatever -constraints are required to constrain it to run only where appropriate, fr fr. Several constraints are predefined in the tcltest package β€” full list below πŸ‘‡. The registration of user-defined constraints is done by the testConstraint command, and user-defined constraints can appear within a test file, or within the script specified by the configure -load or configure -loadfile options. Flexible πŸ’–.

The following is a list of constraints predefined by the tcltest package itself:

  • singleTestInterp β€” This test can only be run if all test files are sourced into a single interpreter.
  • unix β€” This test can only be run on any Unix platform 🐧.
  • win β€” This test can only be run on any Windows platform πŸͺŸ.
  • nt β€” This test can only be run on any Windows NT platform.
  • mac β€” This test can only be run on any Mac platform 🍎.
  • unixOrWin β€” This test can only be run on a Unix or Windows platform.
  • macOrWin β€” This test can only be run on a Mac or Windows platform.
  • macOrUnix β€” This test can only be run on a Mac or Unix platform.
  • tempNotWin β€” This test can not be run on Windows. This flag is used to temporarily disable a test (just benching her for a bit, she'll be back πŸ₯²).
  • tempNotMac β€” This test can not be run on a Mac. This flag is used to temporarily disable a test.
  • unixCrash β€” This test crashes if it is run on Unix πŸ’€. This flag is used to temporarily disable a test.
  • winCrash β€” This test crashes if it is run on Windows πŸ’€. This flag is used to temporarily disable a test.
  • macCrash β€” This test crashes if it is run on a Mac πŸ’€. This flag is used to temporarily disable a test.
  • emptyTest β€” This test is empty, and so not worth running, but it remains as a place-holder for a test to be written in the future πŸŽ€. This constraint has value false to cause tests to be skipped unless the user specifies otherwise.
  • knownBug β€” This test is known to fail and the bug is not yet fixed 😭. This constraint has value false to cause tests to be skipped unless the user specifies otherwise.
  • nonPortable β€” This test can only be run in some known development environment. Some tests are inherently non-portable because they depend on things like word length, file system configuration, window manager, etc. This constraint has value false to cause tests to be skipped unless the user specifies otherwise.
  • userInteraction β€” This test requires interaction from the user πŸ™‹. This constraint has value false to causes tests to be skipped unless the user specifies otherwise.
  • interactive β€” This test can only be run in if the interpreter is in interactive mode (when the global ::tcl_interactive variable is set to 1).
  • nonBlockFiles β€” This test can only be run if platform supports setting files into nonblocking mode.
  • asyncPipeClose β€” This test can only be run if platform supports async flush and async close on a pipe.
  • unixExecs β€” This test can only be run if this machine has Unix-style commands cat, echo, sh, wc, rm, sleep, fgrep, ps, chmod, and mkdir available.
  • hasIsoLocale β€” This test can only be run if can switch to an ISO locale.
  • root β€” This test can only run if Unix user is root πŸ‘‘.
  • notRoot β€” This test can only run if Unix user is not root.
  • eformat β€” This test can only run if app has a working version of sprintf with respect to the β€œe” format of floating-point numbers.
  • stdio β€” This test can only be run if interpreter can be opened as a pipe.

πŸ‘‘ Mode 2: -limitconstraints true (the strict one)

The alternative mode of constraint control is enabled by setting configure -limitconstraints to true. With that configuration setting, all existing constraints other than those in the constraint list returned by configure -constraints are set to false. And when the value of configure -constraints is set, all those constraints are set to true ✨.

The effect? When both options configure -constraints and configure -limitconstraints are in use, only those tests including only constraints from the configure -constraints list are run; all others are skipped πŸ™ˆ. For example, one might set up a configuration with

configure -constraints knownBug \
          -limitconstraints true \
          -verbose pass

to run exactly those tests that exercise known bugs, and discover whether any of them pass β€” indicating the bug had been fixed. Chef's kiss, honestly πŸ”₯


πŸ¦‹ RUNNING ALL TESTS πŸ¦‹

The single command runAllTests is evaluated to run an entire test suite, spanning many files and directories 😀. The configuration options of tcltest control the precise operations. And runAllTests opens by printing a summary of its configuration to outputChannel β€” she likes to announce herself πŸ’….

Test files to be evaluated are sought in the directory configure -testdir. The list of files in that directory that match any of the patterns in configure -file and match none of the patterns in configure -notfile is generated and sorted. Then each file gets evaluated in turn πŸŽ€.

If configure -singleproc is true, then each file will be sourced in the caller's context. If it is false, then a copy of interpreter will be exec'd to evaluate each file πŸƒ. The multi-process operation is useful when testing can cause errors so severe that a process terminates πŸ’€. Even though such an error may terminate a child process evaluating one file, the main process can just keep going with the rest of the test suite β€” resilience, queen 🌈. In multi-process operation, the configuration of tcltest in the main process is passed to the child processes as command line arguments, with the exception of configure -outfile. The runAllTests command in the main process collects all output from the child processes and collates their results into one main report πŸ“. Any reports of individual test failures, or messages requested by a configure -verbose setting, are passed directly on to outputChannel by the main process.

After evaluating all selected test files, a summary of the results is printed to outputChannel. The summary includes:

  • the total number of tests evaluated, broken down into those skipped, those passed, and those failed ✨
  • the number of files evaluated, and the names of any files with failing tests or errors
  • a list of the constraints that caused tests to be skipped, and the number of tests skipped for each 🫢

Also, messages are printed if it appears that evaluation of a test file has caused any temporary files to be left behind in configure -tmpdir (messy, not cute, clean up bestie πŸ™ˆ).

Having completed and summarized all selected test files, runAllTests then recursively acts on subdirectories of configure -testdir πŸ”. All subdirectories that match any of the patterns in configure -relateddir and do not match any of the patterns in configure -asidefromdir are examined. If a file named all.tcl is found in such a directory, it will be sourced in the caller's context. And whether or not an examined directory contains an all.tcl file, its subdirectories are also scanned against the configure -relateddir and configure -asidefromdir patterns 🧚. That way, tons of directories in a directory tree can have all their test files evaluated by a single runAllTests command. Iconic behavior, she covers the whole map πŸ’œ

✨ CONFIGURABLE OPTIONS ✨

okay bestie, this is where you get to tune the whole thing πŸ’… the configure command is your remote control β€” it sets AND queries all the configurable options of tcltest. here's the full menu, no skips:

  • -singleproc boolean β€” controls whether runAllTests spawns a child process for each and every test file. if boolean is true? no spawning at all, it's all one process, the way that it just stays home 🏠. default is false.
  • -debug level β€” sets the debug level to level, an integer saying how much debug tea should be spilled to stdout. note that debug messages always go to stdout, no matter what you set configure -outfile to β€” they do not care, they live there. default is 0. levels go like this:
    • 0 β€” print nothing, zero debug info, silent like a ghost πŸ‘»
    • 1 β€” spill info about whether a test got skipped because it doesn't match the tests you specified with configure -match (that's userSpecifiedNonMatch) or matches the tests you specified with configure -skip (that's userSpecifiedSkip). also print warnings about possible lack of cleanup or balance in test files. AND print warnings about any re-use of test names.
    • 2 β€” display the flag array parsed by the command line processor, the contents of the global env array, and all user-defined variables that exist in the current namespace as they are used.
    • 3 β€” display info about what the individual procs in the test harness are doing. like fully narrating their lives fr fr.
  • -verbose level β€” sets the type of output verbosity to level, which is a list of zero or more of: body, pass, skip, start, error, line, msec and usec. default is body error. here's what each one means:
    • body (b) β€” display the body of failed tests
    • pass (p) β€” print output when a test passes πŸŽ‰
    • skip (s) β€” print output when a test is skipped
    • start (t) β€” print output whenever a test starts
    • error (e) β€” print errorInfo and errorCode, if they exist, when a test's return code does not match its expected return code
    • line (l) β€” print source file line info of failed tests
    • msec (m) β€” print each test's execution time in milliseconds ⏱️
    • usec (u) β€” print each test's execution time in microseconds
heads up bestie: the msec and usec verbosity levels are provided as indicative measures only. they do not solve the whole repeatability problem, which you should genuinely consider in performance tests or benchmarks. if you want to use these levels to thoroughly track performance degradations, consider wrapping your test bodies with time commands. no cap.

the single-letter abbreviations listed above are also recognized, so configure -verbose pt is the same as configure -verbose {pass start}. iconic shorthand, we love efficiency πŸ’–

  • -preservecore level β€” sets the core preservation level to level. this level decides how stringent the checks for core files are. default is 0. levels go:
    • 0 β€” no checking β€” don't check for core files at the end of each test command, but do check for them in runAllTests after all test files have been evaluated.
    • 1 β€” also check for core files at the end of each test command.
    • 2 β€” check for core files at all times described above, AND save a copy of each core file produced in configure -tmpdir. keeping receipts πŸ“Έ
  • -limitconstraints boolean β€” sets the mode by which test honors constraints, as described in TESTS above. default is false.
  • -constraints list β€” sets all the constraints in list to true. also used together with configure -limitconstraints true to control an alternative constraint mode, as described in TESTS above. default is an empty list.
  • -tmpdir directory β€” sets the temporary directory used by makeFile, makeDirectory, viewFile, removeFile, and removeDirectory as the default directory where temporary files and directories created by test files should go. default is workingDirectory. it's giving designated craft corner πŸŽ€
  • -testdir directory β€” sets the directory that runAllTests searches for test files and subdirectories. default is workingDirectory.
  • -file patternList β€” sets the list of patterns that runAllTests uses to figure out which test files to evaluate. default is *.test.
  • -notfile patternList β€” sets the list of patterns that runAllTests uses to figure out which test files to skip. default is l.*.test, so that any SCCS lock files get skipped. bye felicia πŸ‘‹
  • -relateddir patternList β€” sets the list of patterns that runAllTests uses to figure out which subdirectories to search for an all.tcl file. default is *.
  • -asidefromdir patternList β€” sets the list of patterns that runAllTests uses to figure out which subdirectories to skip when searching for an all.tcl file. default is an empty list.
  • -match patternList β€” sets the list of patterns that test uses to figure out whether a test should be run. default is *.
  • -skip patternList β€” sets the list of patterns that test uses to figure out whether a test should be skipped. default is an empty list.
  • -load script β€” sets a script to be evaluated by loadTestedCommands. default is an empty script.
  • -loadfile filename β€” sets the filename from which to read a script to be evaluated by loadTestedCommands. this is an alternative to -load. ⚠️ the two cannot be used together, pick one bestie.
  • -outfile filename β€” sets the file that all output produced by tcltest gets written to. a file named filename will be opened for writing, and the resulting channel will be set as the value of outputChannel.
  • -errfile filename β€” sets the file that all error output produced by tcltest gets written to. a file named filename will be opened for writing, and the resulting channel will be set as the value of errorChannel. keeping the tantrums and the regular output in separate rooms, respectfully πŸ™ˆ

πŸ’– CREATING TEST SUITES WITH TCLTEST πŸ’–

okay bestie, so the fundamental element of a whole test suite is just the individual test command. that's it. that's the atom. let's start with some examples because reading prose about testing is giving nothing, we need the vibes. ✨

  1. a test of a script that returns normally:
test example-1.0 {normal return} {
    format %s value
} value
  1. a test of a script that needs context setup and cleanup. peep the bracing and indenting style that means you never need a line continuation character πŸŽ€:
test example-1.1 {test file existence} -setup {
    set file [makeFile {} test]
} -body {
    file exists $file
} -cleanup {
    removeFile test
} -result 1
  1. a test of a script that raises an error:
test example-1.2 {error return} -body {
    error message
} -returnCodes error -result message
  1. a test with a constraint:
test example-1.3 {user owns created files} -constraints {
    unix
} -setup {
    set file [makeFile {} test]
} -body {
    file attributes $file -owner
} -cleanup {
    removeFile test
} -result $::tcl_platform(user)

🌸 the next layer up: the test file

so one level higher in the organization chart, a bunch of test commands get gathered into a single test file. these files should have names ending in .test β€” because that's literally the default pattern runAllTests uses to sniff out test files. πŸ’…

a good rule of thumb (iykyk): one test file for each source code file in your project. and the move is to edit the test file and the source file together, keeping the tests synced with your code changes. no letting them drift apart, that's a situationship not a test suite.

most of the code in a test file should just be the test commands themselves. got a test you want to skip sometimes? use constraints, not conditional evaluation of test. fr fr.

  1. recommended system for writing conditional tests, using constraints to guard:
testConstraint X [expr $myRequirement]
test goodConditionalTest {} X {
    # body
} result
  1. discouraged system for writing conditional tests, using if to guard:
if $myRequirement {
    test badConditionalTest {} {
        #body
    } result
}

use the -setup and -cleanup options to establish and release all the context requirements of the test body. and pleaseeee do not make tests depend on prior tests in the file β€” because those prior tests might get skipped and then your test is just standing there alone with no context 😭. if several consecutive tests need the same context, stash the appropriate setup and cleanup scripts in a variable and pass that to each test's -setup and -cleanup options. this is a better solution than doing setup outside of test commands, because the setup will only be done if it's actually necessary, and any errors during setup get reported instead of just aborting the whole test file. iconic behavior tbh.

a test file should be able to get combined with other test files without interfering with them β€” even when configure -singleproc 1 makes all the files get evaluated in one common interpreter. a simple way to achieve this: have your tests define all their commands and variables in a namespace that gets deleted once the test file evaluation is done. a good namespace to use is a child namespace test of the namespace of the module you're testing. 🧚

your test file should also be able to be evaluated directly as a script, not depending on being called by some main runAllTests. which means each test file should process command line arguments so the tester gets all the configuration control that tcltest provides. periodt.

and after all the tests in a test file? call the command cleanupTests. don't forget, bestie.

  1. here's a sketch of a sample test file illustrating all of those points:
package require tcltest 2.5
::tcltest::configure {*}$::argv
package require example
namespace eval ::example::test {
    namespace import ::tcltest::*
    testConstraint X [expr {...}]
    variable SETUP {#common setup code}
    variable CLEANUP {#common cleanup code}
    test example-1 {} -setup $SETUP -body {
        # First test
    } -cleanup $CLEANUP -result {...}
    test example-2 {} -constraints X -setup $SETUP -body {
        # Second test; constrained
    } -cleanup $CLEANUP -result {...}
    test example-3 {} {
        # Third test; no context required
    } {...}
    cleanupTests
}
namespace delete ::example::test

πŸ‘‘ the final form: the full test suite

the next level of organization is a full test suite, made up of several test files. one script controls the entire suite. the basic function of this script is to call runAllTests after doing whatever setup is necessary. this script is usually named all.tcl β€” because that's the default name runAllTests uses when combining multiple test suites into one testing run. πŸ’–

  1. here's a sketch of a sample test suite main script:
package require tcltest 2.5
package require example
::tcltest::configure -testdir \
        [file dirname [file normalize [info script]]]
::tcltest::configure {*}$::argv
::tcltest::runAllTests

🫢 COMPATIBILITY 🫢

okay so a bunch of commands and variables in the ::tcltest namespace that earlier releases of tcltest provided have not been documented here. they are no longer part of the supported public interface of tcltest, and you should not use them in new test suites. hard pass. 🚫

that said β€” to keep supporting existing test suites written against the older interface specs, many of those deprecated commands and variables still work exactly as before. for example, in many circumstances, configure will be automatically called shortly after package require tcltest 2.1 succeeds, with arguments from the variable ::argv. this exists to support test suites that depend on the old behavior where tcltest was automatically configured from command line arguments. nostalgic, but old.

new test files should not depend on that automatic behavior, and should instead explicitly include:

::tcltest::configure {*}$::argv

...to establish a configuration from command line arguments. do it the explicit way, bestie. πŸ’…


πŸ’€ KNOWN ISSUES πŸ’€

there are two known issues related to nested evaluations of test. let's get into it.

issue one: the stack level situation. it's about the stack level in which test scripts are executed. tests nested within other tests may be executed at the same stack level as the outermost test. for example, in the following code:

test level-1.1 {level 1} {
    -body {
        test level-2.1 {level 2} {
        }
    }
}

any script executed in level-2.1 may be executed at the same stack level as the script defined for level-1.1. yeah. 😭

on top of that, while two tests have been run, results will only be reported by cleanupTests for tests at the same level as test level-1.1. however, test results for all tests run prior to level-1.1 will be available when test level-2.1 runs. what that means practically: if you try to access the test results for test level-2.1, it may say that β€œm” tests have run, β€œn” tests have been skipped, β€œo” tests have passed and β€œp” tests have failed β€” where β€œm”, β€œn”, β€œo”, and β€œp” refer to tests that were run at the same test level as test level-1.1. so like, the numbers are not about the thing you think they're about. got it? πŸŒ€

issue two: the puts interception thing. implementation of output and error comparison in the test command depends on usage of puts in your application code. output is intercepted by redefining the global puts command while the defined test script is being run. errors thrown by C procedures, or printed directly from C applications, will not be caught by the test command. therefore, usage of the -output and -errorOutput options to test is useful only for pure Tcl applications that use puts to produce output. C code? it's giving invisible. πŸ‘»


πŸ“ KEYWORDS πŸ“

test, test harness, test suite


okay bestie that's a wrap on the whole page!! πŸŽ€ this was tcltest, version 2.5, living in the tcltest(3tcl) section of the manual β€” go forth and write tests that actually tell you what broke, you're the main character of your own test suite now πŸ‘‘βœ¨πŸ’œ

πŸ“¦ where this page comes from