tcltest(n)
π tcltest β the manual, bestie edition π
okay so this is the tcltest page from the Tcl Bundled Packages manual, and it is long, so buckle up. It's giving β¨test harness support code and utilitiesβ¨ and honestly? iconic. π
β¨ NAME β¨
tcltest β test harness support code and utilities. That's it, 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 ?channelID?
tcltest::errorChannel ?channelID?
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 π«Ά
So. The tcltest package hands you a whole lil toolkit of utility commands that are genuinely useful when you're building test suites for code that's instrumented to be run by evaluating Tcl commands. And like, not to be dramatic, but the built-in commands of the Tcl library itself are tested by a test suite that uses the tcltest package. So this thing is the real deal, no cap. π
Every command the tcltest package gives you is defined in β and exported from β the ::tcltest namespace, just like the SYNOPSIS up there shows. In the sections below though, we're gonna refer to all of them by their simple names only, because brevity is a kindness and we're besties. π
The central command of tcltest is test, which defines and runs a test. Testing with test means you evaluate a Tcl script and then compare the result to an expected result β all configured and controlled by a bunch of options. And there's a whole crew of other commands tcltest gives you that govern how test gets configured and how you collect a ton of test commands into test suites. π§
Also: check out CREATING TEST SUITES WITH TCLTEST below for an extended example of how to use all these tcltest commands to produce test suites for your own Tcl-enabled code. You're gonna eat, fr fr. π
π COMMANDS π
test name description ?-option value ...?β Defines and possibly runs a test, with the name name and the description description. The name and description of a test get used in the messages thattestreports during the test, as configured by the options oftcltest. The remaining option value arguments totestare what actually define the test β like the scripts to run, the conditions under which to run them, the expected result, and the means by which expected and actual results get compared. Peep TESTS below for a full description of the valid options and how they define a test. Thetestcommand returns an empty string. (So chill, it's not gonna hand you anything back. π)test name description ?constraints? body resultβ This form oftestexists to support test suites written for version 1 of thetcltestpackage, and also to give you a simpler interface for a common usage. It is the same astest name description -constraints constraints -body body -result result. Every other option totestjust takes its default value. When constraints is omitted, you can tell this form apart from the first one because all options begin with-. π‘loadTestedCommandsβ Evaluates, in the caller's context, the script specified byconfigure -loadorconfigure -loadfile. Returns the result of that script evaluation β including any error the script raises. Use this command plus the related configuration options to hand the commands you're testing over to the interpreter that's running the test suite. π«ΆmakeFile contents name ?directory?β Creates a file named name relative to directory directory and writes contents to that file using the encodingencoding system. If contents doesn't end with a newline, a newline gets 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 ofcleanupTests, unless you remove it first withremoveFile. The default value of directory is the directoryconfigure -tmpdir. Returns the full path of the file it created. Use this one to create any text file a test needs, with whatever contents you need. β¨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 directoryconfigure -tmpdir. Returns an empty string. Use it to delete files thatmakeFilemade. ποΈmakeDirectory name ?directory?β Creates a directory named name relative to directory directory. The directory will be removed by the next evaluation ofcleanupTests, unless you remove it first withremoveDirectory. The default value of directory is the directoryconfigure -tmpdir. Returns the full path of the directory it created. Use this to create any directories a test needs to exist. π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 directoryconfigure -tmpdir. Returns an empty string. Use it to delete any directories thatmakeDirectorycreated. ποΈviewFile file ?directory?β Returns the contents of file, except for any final newline β exactly likeread -nonewlinewould return them. This file name should be relative to directory. The default value of directory is the directoryconfigure -tmpdir. Use this command as the convenient way to turn the contents of a file a test generated into the result of that test, so it can be matched against an expected result. The contents are read using the system encoding, so its usefulness is limited to text files. πcleanupTestsβ Meant to clean up and summarize after several tests have run. Typically you call it once per test file, at the end of the file, after all the tests are done. And for best effectiveness, make surecleanupTestsgets evaluated even if an error happens earlier in the test file evaluation. It prints statistics about the tests that ran, and removes files created bymakeDirectoryandmakeFilesince the lastcleanupTests. Names of files and directories in the directoryconfigure -tmpdirthat were created since the lastcleanupTestsβ but not created bymakeFileormakeDirectoryβ get printed tooutputChannel. This command also restores the original shell environment, as described by the globalenvarray. 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 oftcltest. Peep RUNNING ALL TESTS below for a complete description of the many variations possible withrunAllTests. πβοΈπ¨
π CONFIGURATION COMMANDS π
configureβ Returns the list of configurable options thattcltestsupports. Peep CONFIGURABLE OPTIONS below for the full list of options, their valid values, and their effect ontcltestoperations. π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, in order. Raises an error if an option isn't a supported configurable option, or if value isn't a valid value for the corresponding option, or if a value isn't provided at all. When an error gets raised, the operation ofconfigureis halted, and subsequent option value arguments are not processed. π
Also: if the environment variable::env(TCLTEST_OPTIONS)exists when thetcltestpackage is loaded (viapackage require tcltest), then its value is taken as a list of arguments to pass toconfigure. This is how the default values of the configuration options get set by the environment. π
customMatch mode scriptβ Registers mode as a new legal value of the-matchoption totest. When the-match modeoption gets passed totest, script gets evaluated to compare the actual result of evaluating the body of the test to the expected result. To do 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 saying whether or not the results match. The built-in matching modes oftestareexact,glob, andregexp. π―testConstraint constraint ?boolean?β Sets or returns the boolean value associated with the named constraint. Peep TEST CONSTRAINTS below for more. πinterpreter ?executableName?β Sets or returns the name of the executable to be execed byrunAllTeststo run each test file whenconfigure -singleprocisfalse. The default value forinterpreteris the name of the currently running program, as returned byinfo nameofexecutable. π
errorChannel ?channelID?
Sets or returns the error channel ID. Defaults to stderr, obviously. And the rule is: any test that prints error messages should send that output to errorChannel rather than printing straight to stderr, okay? Like, route it properly. π
β¨ SHORTCUT CONFIGURATION COMMANDS β¨
Bestie these are just lil nickname versions of the big configure flags. Same energy, shorter typing. π
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
Okay so heads up: the remaining commands that tcltest hands you all have better alternatives β either from tcltest itself or from Tcl. They're still here so your existing test suites don't break, but for new code? avoid them, no cap. π«
test name description optionList
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 arguments to test. Sounds cute right? It is not. π
The optionList argument is expected to be a list with an even number of elements, representing option and value arguments to pass to test. BUT β and this is the messy part β these values are not passed directly, like they are in the alternate forms of switch. Nope. Instead, this form makes an unfortunate attempt to overthrow Tcl's substitution rules by performing substitutions on some of the list elements, as an attempt to implement a "do what I mean" interpretation of a brace-enclosed "block".
The result is nearly impossible to document clearly, and for that reason this form is not recommended. Periodt.
See the examples in CREATING TEST SUITES WITH TCLTEST below to see that this form is really not necessary to avoid backslash-quoted newlines. If you insist on using this form, go read 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 for workingDirectory is the directory in which the test suite was launched. Honestly? The Tcl commands cd and pwd are sufficient replacements. That's it, that's the whole thing. π¦
normalizeMsg msg
Returns the result of removing the "extra" newlines from msg β where "extra" is rather imprecise, ngl. Tcl offers plenty of string processing commands to modify strings however you want, and customMatch lets you flexibly match actual and expected results. So like. You have options. π«
normalizePath pathVar
Resolves symlinks in a path, creating a path without internal redirection. It is assumed that pathVar is absolute. pathVar is modified in place. The Tcl command file normalize is a sufficient replacement. Slay. β¨
π§ͺ TESTS π§ͺ
The test command is the heart of the tcltest package, fr fr. Its essential function is to evaluate a Tcl script and compare the result with 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.
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 may be any string. It's conventional to choose a name according to the pattern:
target-majorNum.minorNum
For white-box (regression) tests, the target should be the name of the C function or Tcl procedure being tested. For black-box tests, the 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.
As a test suite evolves, it is best to have the same test name continue to correspond to the same test β that way 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." π
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 will be run only if name matches any of the patterns from configure -match and matches none of the patterns from configure -skip.
The description should be a short textual description of the test. The description is 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. 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 these 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. If the expression evaluates to true, then the test is run.
Note that the expression form of-constraintsmay interfere with the operation ofconfigure -constraintsandconfigure -limitconstraints, and is not recommended.
Appropriate constraints should be added to any tests that should not always be run. That is, conditional evaluation of a test should be accomplished by the -constraints option, not by conditional evaluation of test. In 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 will be run before the script indicated by the -body attribute. If evaluation of script raises an error, the test will fail. 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 will fail (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 will be run after the script indicated by the -body attribute. If evaluation of script raises an error, the test will fail. 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 ok return. π
-errorCodeexpectedErrorCode β this optional attribute hands over expectedErrorCode, a glob pattern that's supposed to match the error code that comes back from evaluating the-bodyscript. If the-bodyscript returns a code that doesn't match expectedErrorCode, boom, the test fails. Default value is*. And heads up: if-returnCodesdoesn't includeerror, it gets set toerror. periodt π
okay so 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 you specified them, the output and error data from the test have to match the expected -output and -errorOutput values. if literally any of those conditions isn't met, the test fails. and bestie, note this: all scripts are evaluated in the context of the caller of test. π«Ά
as long as test is called with valid syntax and legal values for all attributes, it will not raise an error. test failures are instead reported as output written to outputChannel. in default operation, a successful test produces no output β silence is the vibe β¨. the output messages produced by test are controlled by the configure -verbose option as described in CONFIGURABLE OPTIONS below. any output produced by the test scripts themselves should be produced using puts to outputChannel or errorChannel, so that users of the test suite can easily capture output with the configure -outfile and configure -errfile options, and so that the -output and -errorOutput attributes work properly. it's giving teamwork, fr fr.
πΈ TEST CONSTRAINTS πΈ
constraints are how we figure out whether a test should be skipped or not. each constraint has a name β which can be any string β and a boolean value. each test has a -constraints value which is a list of constraint names. there are two modes of constraint control. most of the time you're in the default mode, indicated by a setting of 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 convenient, symbolic way to define any conditions required for the test to be possible or meaningful. for example, a test with -constraints unix will only be run if the constraint unix is true, which indicates the test suite is being run on a Unix platform. iykyk π
each test should include whatever -constraints are required to constrain it to run only where appropriate. several constraints are predefined in the tcltest package, listed below. registering user-defined constraints is done by the testConstraint command. user-defined constraints may appear within a test file, or within the script specified by the configure -load or configure -loadfile options.
here's the list of constraints the tcltest package predefines for you, no cap:
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.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 theeformat of floating-point numbers.stdioβ this test can only be run if interpreter can be opened as a pipe.
the alternative mode of constraint control gets switched on 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. 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. so 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. main character detective energy πβ¨
π 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. the runAllTests command begins by printing a summary of its configuration to outputChannel. like, hi, here's the situation bestie π’
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 will be evaluated in turn. if configure -singleproc is true, then each file will be sourced in the caller's context. if it's 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 β and honestly? iconic that it survives that π. although such an error may terminate a child process evaluating one file, the main process can continue with the rest of the test suite. 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 summary also notes 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 is also printed. 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. leaving temp files behind? not the vibe π
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. whether or not an examined directory contains an all.tcl file, its subdirectories are also scanned against the configure -relateddir and configure -asidefromdir patterns. in this way, many directories in a directory tree can have all their test files evaluated by a single runAllTests command. it goes all the way down, recursively, and that's just the way it is ππ
β¨ CONFIGURABLE OPTIONS β¨
okay so the configure command is literally the remote control for all the configurable options of tcltest. you use it to set them and to query them. here's the whole menu, no skips, bestie:
-singleproc booleanβ controls whetherrunAllTestsspawns a child process for each test file. when boolean is true, there's no spawning. default isfalse. π-debug levelβ sets the debug level to level, an integer that says how much debugging info gets printed tostdout. heads up: debug messages always go tostdout, no matter what you setconfigure -outfileto. default is0. levels are:0β do not display any debug information. π1β display info about whether a test is skipped because it doesn't match any tests specified usingconfigure -match(userSpecifiedNonMatch) or matches any tests specified byconfigure -skip(userSpecifiedSkip). also prints warnings about possible lack of cleanup or balance in test files. also prints warnings about any re-use of test names. π«Ά2β display the flag array parsed by the command line processor, the contents of the globalenvarray, and all user-defined variables that exist in the current namespace as they are used. β¨3β display info about what individual procs in the test harness are doing. π
-verbose levelβ sets the type of output verbosity to level, a list of zero or more of these elements:body,pass,skip,start,error,line,msec, andusec. default isbody error. levels are: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) β printerrorInfoanderrorCode, if they exist, when a test return code does not match its expected return code. πline(l) β print source file line information of failed tests. π₯msec(m) β print each test's execution time in milliseconds. βusec(u) β print each test's execution time in microseconds. π
ngl, the msec and usec verbosity levels are indicative measures only. they do not tackle the problem of repeatability, which should be considered in performance tests or benchmarks. to use these verbosity levels to thoroughly track performance degradations, consider wrapping your test bodies with time commands. β³
the single letter abbreviations noted above are also recognized, so configure -verbose pt is the same as configure -verbose {pass start}. periodt. π
-preservecore levelβ sets the core preservation level to level. this level determines how stringent checks for core files are. default is0. levels are:0β no checking β do not check for core files at the end of each test command, but do check for them inrunAllTestsafter 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 inconfigure -tmpdir. πΎ
-limitconstraints booleanβ sets the mode by whichtesthonors constraints as described in TESTS above. default isfalse. π-constraints listβ sets all the constraints in list to true. also used in combination withconfigure -limitconstraints trueto control an alternative constraint mode as described in TESTS above. default is an empty list. π-tmpdir directoryβ sets the temporary directory to be used bymakeFile,makeDirectory,viewFile,removeFile, andremoveDirectoryas the default directory where temporary files and directories created by test files should be created. default isworkingDirectory. ποΈ-testdir directoryβ sets the directory searched byrunAllTestsfor test files and subdirectories. default isworkingDirectory. π-file patternListβ sets the list of patterns used byrunAllTeststo determine what test files to evaluate. default is*.test. ποΈ-notfile patternListβ sets the list of patterns used byrunAllTeststo determine what test files to skip. default isl.*.test, so that any SCCS lock files are skipped. π«-relateddir patternListβ sets the list of patterns used byrunAllTeststo determine what subdirectories to search for anall.tclfile. default is*. π-asidefromdir patternListβ sets the list of patterns used byrunAllTeststo determine what subdirectories to skip when searching for anall.tclfile. default is an empty list. π-match patternListβ set the list of patterns used bytestto determine whether a test should be run. default is*. β-skip patternListβ set the list of patterns used bytestto determine whether a test should be skipped. default is an empty list. βοΈ-load scriptβ sets a script to be evaluated byloadTestedCommands. default is an empty script. π-loadfile filenameβ sets the filename from which to read a script to be evaluated byloadTestedCommands. this is an alternative to-load. they cannot be used together. β οΈ-outfile filenameβ sets the file to which all output produced bytcltestshould be written. a file named filename will be opened for writing, and the resulting channel will be set as the value ofoutputChannel. π€-errfile filenameβ sets the file to which all error output produced bytcltestshould be written. a file named filename will be opened for writing, and the resulting channel will be set as the value oferrorChannel. π₯
π§ͺ CREATING TEST SUITES WITH TCLTEST π§ͺ
okay so bestie, the fundamental element of a test suite is the individual test command. No cap. We begin with several examples.
[1] Test of a script that returns normally.
test example-1.0 {normal return} {
format %s value
} value
[2] Test of a script that requires context setup and cleanup. Note the bracing and indenting style that avoids any need for line continuation.
test example-1.1 {test file existence} -setup {
set file [makeFile {} test]
} -body {
file exists $file
} -cleanup {
removeFile test
} -result 1
[3] Test of a script that raises an error.
test example-1.2 {error return} -body {
error message
} -returnCodes error -result message
[4] 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)
At the next higher layer of organization, several test commands are gathered together into a single test file. Test files should have names with the β.testβ extension, because that is the default pattern used by runAllTests to find test files. It is a good rule of thumb to have one test file for each source code file of your project. It is good practice to edit the test file and the source code file together, keeping tests synchronized with code changes.
Most of the code in the test file should be the test commands. Use constraints to skip tests, rather than conditional evaluation of test.
[5] Recommended system for writing conditional tests, using constraints to guard:
testConstraint X [expr $myRequirement]
test goodConditionalTest {} X {
# body
} result
[6] 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 context requirements of the test body. Do not make tests depend on prior tests in the file. Those prior tests might be skipped. If several consecutive tests require the same context, the appropriate setup and cleanup scripts may be stored in variable for passing to each tests -setup and -cleanup options. This is a better solution than performing setup outside of test commands, because the setup will only be done if necessary, and any errors during setup will be reported, and not cause the test file to abort.
A test file should be able to be combined with other test files and not interfere with them, even when configure -singleproc 1 causes all files to be evaluated in a common interpreter. A simple way to achieve this is to have your tests define all their commands and variables in a namespace that is deleted when the test file evaluation is complete. A good namespace to use is a child namespace test of the namespace of the module you are testing.
A test file should also be able to be evaluated directly as a script, not depending on being called by a main runAllTests. This means that each test file should process command line arguments to give the tester all the configuration control that tcltest provides.
After all tests in a test file, the command cleanupTests should be called.
[7] Here is a sketch of a sample test file illustrating those points:
package require tcltest 2.5
eval ::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 next level of organization is a full test suite, made up of several test files. One script is used to control the entire suite. The basic function of this script is to call runAllTests after doing any necessary setup. This script is usually named all.tcl because that is the default name used by runAllTests when combining multiple test suites into one testing run.
[8] Here is 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]]]
eval ::tcltest::configure $argv
::tcltest::runAllTests
πΎ COMPATIBILITY πΎ
A number of commands and variables in the ::tcltest namespace provided by earlier releases of tcltest have not been documented here. They are no longer part of the supported public interface of tcltest and should not be used in new test suites. However, to continue to support existing test suites written to the older interface specifications, many of those deprecated commands and variables still work 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 is to support test suites that depend on the old behavior that tcltest was automatically configured from command line arguments. New test files should not depend on this, but should explicitly include
eval ::tcltest::configure $::argv
or
::tcltest::configure {*}$::argv
to establish a configuration from command line arguments.
β οΈ KNOWN ISSUES β οΈ
There are two known issues related to nested evaluations of test. The first issue relates to 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.
In addition, 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 this means is that if you try to access the test results for test level-2.1, it will 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.
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.
π KEYWORDS π
testtest harnesstest suite
k bye bestie π this was tcltest version 2.5, man section tcltest(n) β footer source/version and section, no date on the line, just immaculate vibes. β¨π¦
π¦ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 Β· TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 Β· TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- 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