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 tostderr, obviously. And bestie, if any of your tests print error messages, pls pls pls send that output toerrorChannelinstead of yeeting it straight atstderrπ 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 asconfigure -debug ?level?.errorFile ?filename?β same asconfigure -errfile ?filename?.limitConstraints ?boolean?β same asconfigure -limitconstraints ?boolean?.loadFile ?filename?β same asconfigure -loadfile ?filename?.loadScript ?script?β same asconfigure -load ?script?.match ?patternList?β same asconfigure -match ?patternList?.matchDirectories ?patternList?β same asconfigure -relateddir ?patternList?.matchFiles ?patternList?β same asconfigure -file ?patternList?.outputFile ?filename?β same asconfigure -outfile ?filename?.preserveCore ?level?β same asconfigure -preservecore ?level?.singleProcess ?boolean?β same asconfigure -singleproc ?boolean?.skip ?patternList?β same asconfigure -skip ?patternList?.skipDirectories ?patternList?β same asconfigure -asidefromdir ?patternList?.skipFiles ?patternList?β same asconfigure -notfile ?patternList?.temporaryDirectory ?directory?β same asconfigure -tmpdir ?directory?.testsDirectory ?directory?β same asconfigure -testdir ?directory?.verbose ?level?β same asconfigure -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 oftestexisted 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 π TheoptionListargument is supposed to be a list with an even number of elements, representing option and value arguments to pass totest. But here's the tea: those values are not passed directly, like they are in the alternate forms ofswitch. 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 inCREATING TEST SUITES WITH TCLTESTbelow 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 oftcltestif you want to know the substitution details, or just enclose the third through last argument totestin braces and hope for the best ππworkingDirectory ?directoryName?β sets or returns the current working directory while the test suite is running πββοΈ the default value forworkingDirectoryis the directory in which the test suite was launched. The Tcl commandscdandpwdare sufficient replacements, so like... you don't need this one.normalizeMsg msgβ returns the result of removing the "extra" newlines frommsg, where "extra" is, and I quote, rather imprecise π Tcl offers plenty of string processing commands to modify strings as you wish, andcustomMatchallows 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 thatpathVaris absolute, and heads up:pathVaris modified in place. The Tcl commandfile normalizeis 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-constraintsattribute can be a list of one or more keywords, or an expression. If the-constraintsvalue is a list of keywords, each of those keywords should be the name of a constraint defined by a call totestConstraint. If any of the listed constraints is false or does not exist, the test is skipped. If the-constraintsvalue 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-constraintsmay interfere with the operation ofconfigure -constraintsandconfigure -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-setupattribute indicates a script that runs before the script indicated by the-bodyattribute. If evaluation ofscriptraises an error, the test fails. The default value is an empty script. π«§-body scriptβ the-bodyattribute indicates the script to run to carry out the test, which must return a result that can be checked for correctness. If evaluation ofscriptraises an error, the test fails β unless the-returnCodesoption is used to state that an error is expected π The default value is an empty script.-cleanup scriptβ the optional-cleanupattribute indicates a script that runs after the script indicated by the-bodyattribute. If evaluation ofscriptraises an error, the test fails. The default value is an empty script. π§Ή-match modeβ the-matchattribute determines how expected answers supplied by-result,-output, and-errorOutputare compared. Valid values formodeareregexp,glob,exact, and any value registered by a prior call tocustomMatch. The default value isexact. π―-result expectedValueβ the-resultattribute supplies theexpectedValueagainst which the return value fromscriptwill be compared. The default value is an empty string.-output expectedValueβ the-outputattribute supplies theexpectedValueagainst which any output sent tostdoutoroutputChannelduring evaluation of the script(s) will be compared. Note that only output printed using the globalputscommand is used for comparison π If-outputis not specified, output sent tostdoutandoutputChannelis not processed for comparison.-errorOutput expectedValueβ the-errorOutputattribute supplies theexpectedValueagainst which any output sent tostderrorerrorChannelduring evaluation of the script(s) will be compared. Note that only output printed using the globalputscommand is used for comparison π If-errorOutputis not specified, output sent tostderranderrorChannelis not processed for comparison.-returnCodes expectedCodeListβ the optional-returnCodesattribute suppliesexpectedCodeList, a list of return codes that may be accepted from evaluation of the-bodyscript. If evaluation of the-bodyscript returns a code not in theexpectedCodeList, the test fails. All return codes known toreturn, in both numeric and symbolic form β including extended return codes β are acceptable elements in theexpectedCodeList. Default value is<yellow>ok return</yellow>β¨-errorCodeexpectedErrorCode β okay so this one's β¨optionalβ¨, and it's a glob pattern. It gets matched against the error code that comes back when the-bodyscript 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-returnCodesdoesn't already includeerror, it gets set toerror. 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 valuefalseto 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 valuefalseto 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 valuefalseto cause tests to be skipped unless the user specifies otherwise.userInteractionβ This test requires interaction from the user π. This constraint has valuefalseto 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_interactivevariable is set to1).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 commandscat,echo,sh,wc,rm,sleep,fgrep,ps,chmod, andmkdiravailable.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 ofsprintfwith 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:
-singleprocboolean β controls whetherrunAllTestsspawns 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.-debuglevel β sets the debug level to level, an integer saying how much debug tea should be spilled tostdout. note that debug messages always go tostdout, no matter what you setconfigure -outfileto β 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'suserSpecifiedNonMatch) or matches the tests you specified withconfigure -skip(that'suserSpecifiedSkip). 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
envarray, 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.
-verboselevel β sets the type of output verbosity to level, which is a list of zero or more of:body,pass,skip,start,error,line,msecandusec. default isbody error. here's what each one means:body(b) β display the body of failed testspass(p) β print output when a test passes πskip(s) β print output when a test is skippedstart(t) β print output whenever a test startserror(e) β printerrorInfoanderrorCode, if they exist, when a test's return code does not match its expected return codeline(l) β print source file line info of failed testsmsec(m) β print each test's execution time in milliseconds β±οΈusec(u) β print each test's execution time in microseconds
heads up bestie: themsecandusecverbosity 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 withtimecommands. 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 π
-preservecorelevel β 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
runAllTestsafter 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 πΈ
- 0 β no checking β don't check for core files at the end of each test command, but do check for them in
-limitconstraintsboolean β sets the mode by whichtesthonors constraints, as described in TESTS above. default is false.-constraintslist β sets all the constraints in list to true. also used together withconfigure -limitconstraints trueto control an alternative constraint mode, as described in TESTS above. default is an empty list.-tmpdirdirectory β sets the temporary directory used bymakeFile,makeDirectory,viewFile,removeFile, andremoveDirectoryas the default directory where temporary files and directories created by test files should go. default isworkingDirectory. it's giving designated craft corner π-testdirdirectory β sets the directory thatrunAllTestssearches for test files and subdirectories. default isworkingDirectory.-filepatternList β sets the list of patterns thatrunAllTestsuses to figure out which test files to evaluate. default is*.test.-notfilepatternList β sets the list of patterns thatrunAllTestsuses to figure out which test files to skip. default isl.*.test, so that any SCCS lock files get skipped. bye felicia π-relateddirpatternList β sets the list of patterns thatrunAllTestsuses to figure out which subdirectories to search for anall.tclfile. default is*.-asidefromdirpatternList β sets the list of patterns thatrunAllTestsuses to figure out which subdirectories to skip when searching for anall.tclfile. default is an empty list.-matchpatternList β sets the list of patterns thattestuses to figure out whether a test should be run. default is*.-skippatternList β sets the list of patterns thattestuses to figure out whether a test should be skipped. default is an empty list.-loadscript β sets a script to be evaluated byloadTestedCommands. default is an empty script.-loadfilefilename β sets the filename from which to read a script to be evaluated byloadTestedCommands. this is an alternative to-load. β οΈ the two cannot be used together, pick one bestie.-outfilefilename β 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 ofoutputChannel.-errfilefilename β 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 oferrorChannel. 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. β¨
- a test of a script that returns normally:
test example-1.0 {normal return} {
format %s value
} value
- 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
- a test of a script that raises an error:
test example-1.2 {error return} -body {
error message
} -returnCodes error -result message
- 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.
- recommended system for writing conditional tests, using constraints to guard:
testConstraint X [expr $myRequirement]
test goodConditionalTest {} X {
# body
} result
- discouraged system for writing conditional tests, using
ifto 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.
- 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. π
- 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
- ubuntu stonking: tcl8.6-doc 8.6.18+dfsg-1
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1990-1994 The Regents of the University of California
- Copyright (c) 1994-1997 Sun Microsystems, Inc
- Copyright (c) 1998-1999 Scriptics Corporation
- Copyright (c) 2000 Ajuba Solutions
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms