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 that test reports during the test, as configured by the options of tcltest. The remaining option value arguments to test are 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. The test command returns an empty string. (So chill, it's not gonna hand you anything back. πŸ™ˆ)
  • test name description ?constraints? body result β€” This form of test exists to support test suites written for version 1 of the tcltest package, and also to give you a simpler interface for a common usage. It is the same as test name description -constraints constraints -body body -result result. Every other option to test just 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 by configure -load or configure -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 encoding encoding 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 of cleanupTests, unless you remove it first with removeFile. The default value of directory is the directory configure -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 directory configure -tmpdir. Returns an empty string. Use it to delete files that makeFile made. πŸ—‘οΈ
  • makeDirectory name ?directory? β€” Creates a directory named name relative to directory directory. The directory will be removed by the next evaluation of cleanupTests, unless you remove it first with removeDirectory. The default value of directory is the directory configure -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 directory configure -tmpdir. Returns an empty string. Use it to delete any directories that makeDirectory created. πŸ—‘οΈ
  • viewFile file ?directory? β€” Returns the contents of file, except for any final newline β€” exactly like read -nonewline would return them. This file name should be relative to directory. The default value of directory is the directory configure -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 sure cleanupTests gets evaluated even if an error happens earlier in the test file evaluation. It prints statistics about the tests that ran, and removes files created by makeDirectory and makeFile since the last cleanupTests. Names of files and directories in the directory configure -tmpdir that were created since the last cleanupTests β€” but not created by makeFile or makeDirectory β€” get 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. Peep RUNNING ALL TESTS below for a complete description of the many variations possible with runAllTests. πŸƒβ™€οΈπŸ’¨

πŸŽ€ CONFIGURATION COMMANDS πŸŽ€

  • configure β€” Returns the list of configurable options that tcltest supports. Peep 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, 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 of configure is halted, and subsequent option value arguments are not processed. 😭
Also: if the environment variable ::env(TCLTEST_OPTIONS) exists when the tcltest package is loaded (via package require tcltest), then its value is taken as a list of arguments to pass to configure. 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 -match option to test. When the -match mode option gets passed to test, 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 of test are exact, glob, and regexp. 🎯
  • 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 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. πŸ‘‘

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 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

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 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. 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 -constraints may interfere with the operation of configure -constraints and configure -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. πŸ‘‘

  • -errorCode expectedErrorCode β€” this optional attribute hands over expectedErrorCode, a glob pattern that's supposed to match the error code that comes back from evaluating the -body script. If the -body script returns a code that doesn't match expectedErrorCode, boom, the test fails. Default value is *. And heads up: if -returnCodes doesn't include error, it gets set to error. 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 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.

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 whether runAllTests spawns a child process for each test file. when boolean is true, there's no spawning. default is false. πŸ’…
  • -debug level β€” sets the debug level to level, an integer that says how much debugging info gets printed to stdout. heads up: debug messages always go to stdout, no matter what you set configure -outfile to. default is 0. 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 using configure -match (userSpecifiedNonMatch) or matches any tests specified by configure -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 global env array, 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, and usec. default is body 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) β€” print errorInfo and errorCode, 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 is 0. levels are:
    • 0 β€” no checking β€” do not 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. πŸ’Ύ
  • -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 in combination 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 to be used by makeFile, makeDirectory, viewFile, removeFile, and removeDirectory as the default directory where temporary files and directories created by test files should be created. default is workingDirectory. πŸ—‚οΈ
  • -testdir directory β€” sets the directory searched by runAllTests for test files and subdirectories. default is workingDirectory. πŸ”
  • -file patternList β€” sets the list of patterns used by runAllTests to determine what test files to evaluate. default is *.test. πŸ—ƒοΈ
  • -notfile patternList β€” sets the list of patterns used by runAllTests to determine what test files to skip. default is l.*.test, so that any SCCS lock files are skipped. 🚫
  • -relateddir patternList β€” sets the list of patterns used by runAllTests to determine what subdirectories to search for an all.tcl file. default is *. πŸ“
  • -asidefromdir patternList β€” sets the list of patterns used by runAllTests to determine what subdirectories to skip when searching for an all.tcl file. default is an empty list. πŸ™…
  • -match patternList β€” set the list of patterns used by test to determine whether a test should be run. default is *. βœ…
  • -skip patternList β€” set the list of patterns used by test to determine 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. they cannot be used together. ⚠️
  • -outfile filename β€” sets the file to which all output produced by tcltest should be written. 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 to which all error output produced by tcltest should be written. a file named filename will be opened for writing, and the resulting channel will be set as the value of errorChannel. πŸ“₯

πŸ§ͺ 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 πŸ”‘

  • test
  • test harness
  • test 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