Debian Codegraph @

library/tcltest/tcltest.tcl

raw
1 # tcltest.tcl --
2 #
3 # This file contains support code for the Tcl test suite. It
4 # defines the tcltest namespace and finds and defines the output
5 # directory, constraints available, output and error channels,
6 # etc. used by Tcl tests. See the tcltest man page for more
7 # details.
8 #
9 # This design was based on the Tcl testing approach designed and
10 # initially implemented by Mary Ann May-Pumphrey of Sun
11 # Microsystems.
12 #
13 # Copyright © 1994-1997 Sun Microsystems, Inc.
14 # Copyright © 1998-1999 Scriptics Corporation.
15 # Copyright © 2000 Ajuba Solutions
16 # Contributions from Don Porter, NIST, 2002. (not subject to US copyright)
17 # All rights reserved.
18
19 namespace eval tcltest {
20
21 # When the version number changes, be sure to update the pkgIndex.tcl file,
22 # and the install directory in the Makefiles. When the minor version
23 # changes (new feature) be sure to update the man page as well.
24 variable Version 2.5.11
25
26 # Compatibility support for dumb variables defined in tcltest 1
27 # Do not use these. Call [package require] and [info patchlevel]
28 # yourself. You don't need tcltest to wrap it for you.
29 variable version [package require Tcl 8.5-]
30 variable patchLevel [info patchlevel]
31
32 # Detect if we can use code points >= \U10000
33 variable fullutf [package vsatisfies $version 9.0-]
34
35 ##### Export the public tcltest procs; several categories
36 #
37 # Export the main functional commands that do useful things
38 namespace export cleanupTests loadTestedCommands makeDirectory \
39 makeFile removeDirectory removeFile runAllTests test
40
41 # Export configuration commands that control the functional commands
42 namespace export configure customMatch errorChannel interpreter \
43 outputChannel testConstraint
44
45 # Export commands that are duplication (candidates for deprecation)
46 if {![package vsatisfies [package provide Tcl] 9.0-]} {
47 namespace export bytestring ;# dups [encoding convertfrom identity]
48 }
49 namespace export debug ;# [configure -debug]
50 namespace export errorFile ;# [configure -errfile]
51 namespace export limitConstraints ;# [configure -limitconstraints]
52 namespace export loadFile ;# [configure -loadfile]
53 namespace export loadScript ;# [configure -load]
54 namespace export match ;# [configure -match]
55 namespace export matchFiles ;# [configure -file]
56 namespace export matchDirectories ;# [configure -relateddir]
57 namespace export normalizeMsg ;# application of [customMatch]
58 namespace export normalizePath ;# [file normalize] (8.4)
59 namespace export outputFile ;# [configure -outfile]
60 namespace export preserveCore ;# [configure -preservecore]
61 namespace export singleProcess ;# [configure -singleproc]
62 namespace export skip ;# [configure -skip]
63 namespace export skipFiles ;# [configure -notfile]
64 namespace export skipDirectories ;# [configure -asidefromdir]
65 namespace export temporaryDirectory ;# [configure -tmpdir]
66 namespace export testsDirectory ;# [configure -testdir]
67 namespace export verbose ;# [configure -verbose]
68 namespace export viewFile ;# binary encoding [read]
69 namespace export workingDirectory ;# [cd] [pwd]
70
71 # Export deprecated commands for tcltest 1 compatibility
72 namespace export getMatchingFiles mainThread restoreState saveState \
73 threadReap
74
75 # tcltest::normalizePath --
76 #
77 # This procedure resolves any symlinks in the path thus creating
78 # a path without internal redirection. It assumes that the
79 # incoming path is absolute.
80 #
81 # Arguments
82 # pathVar - name of variable containing path to modify.
83 #
84 # Results
85 # The path is modified in place.
86 #
87 # Side Effects:
88 # None.
89 #
90 proc normalizePath {pathVar} {
91 upvar 1 $pathVar path
92 set oldpwd [pwd]
93 catch {cd $path}
94 set path [pwd]
95 cd $oldpwd
96 return $path
97 }
98
99 ##### Verification commands used to test values of variables and options
100 #
101 # Verification command that accepts everything
102 proc AcceptAll {value} {
103 return $value
104 }
105
106 # Verification command that accepts valid Tcl lists
107 proc AcceptList { list } {
108 return [lrange $list 0 end]
109 }
110
111 # Verification command that accepts a glob pattern
112 proc AcceptPattern { pattern } {
113 return [AcceptAll $pattern]
114 }
115
116 # Verification command that accepts integers
117 proc AcceptInteger { level } {
118 return [incr level 0]
119 }
120
121 # Verification command that accepts boolean values
122 proc AcceptBoolean { boolean } {
123 return [expr {$boolean && $boolean}]
124 }
125
126 # Verification command that accepts (syntactically) valid Tcl scripts
127 proc AcceptScript { script } {
128 if {![info complete $script]} {
129 return -code error "invalid Tcl script: $script"
130 }
131 return $script
132 }
133
134 # Verification command that accepts (converts to) absolute pathnames
135 proc AcceptAbsolutePath { path } {
136 return [file join [pwd] $path]
137 }
138
139 # Verification command that accepts existing readable directories
140 proc AcceptReadable { path } {
141 if {![file readable $path]} {
142 return -code error "\"$path\" is not readable"
143 }
144 return $path
145 }
146 proc AcceptDirectory { directory } {
147 set directory [AcceptAbsolutePath $directory]
148 if {![file exists $directory]} {
149 return -code error "\"$directory\" does not exist"
150 }
151 if {![file isdir $directory]} {
152 return -code error "\"$directory\" is not a directory"
153 }
154 return [AcceptReadable $directory]
155 }
156
157 ##### Initialize internal arrays of tcltest, but only if the caller
158 # has not already preinitialized them. This is done to support
159 # compatibility with older tests that directly access internals
160 # rather than go through command interfaces.
161 #
162 proc ArrayDefault {varName value} {
163 variable $varName
164 if {[array exists $varName]} {
165 return
166 }
167 if {[info exists $varName]} {
168 # Preinitialized value is a scalar: Destroy it!
169 unset $varName
170 }
171 array set $varName $value
172 }
173
174 # save the original environment so that it can be restored later
175 ArrayDefault originalEnv [array get ::env]
176
177 # initialize numTests array to keep track of the number of tests
178 # that pass, fail, and are skipped.
179 ArrayDefault numTests [list Total 0 Passed 0 Skipped 0 Failed 0]
180
181 # createdNewFiles will store test files as indices and the list of
182 # files (that should not have been) left behind by the test files
183 # as values.
184 ArrayDefault createdNewFiles {}
185
186 # initialize skippedBecause array to keep track of constraints that
187 # kept tests from running; a constraint name of "userSpecifiedSkip"
188 # means that the test appeared on the list of tests that matched the
189 # -skip value given to the flag; "userSpecifiedNonMatch" means that
190 # the test didn't match the argument given to the -match flag; both
191 # of these constraints are counted only if tcltest::debug is set to
192 # true.
193 ArrayDefault skippedBecause {}
194
195 # initialize the testConstraints array to keep track of valid
196 # predefined constraints (see the explanation for the
197 # InitConstraints proc for more details).
198 ArrayDefault testConstraints {}
199
200 ##### Initialize internal variables of tcltest, but only if the caller
201 # has not already preinitialized them. This is done to support
202 # compatibility with older tests that directly access internals
203 # rather than go through command interfaces.
204 #
205 proc Default {varName value {verify AcceptAll}} {
206 variable $varName
207 if {![info exists $varName]} {
208 variable $varName [$verify $value]
209 } else {
210 variable $varName [$verify [set $varName]]
211 }
212 }
213
214 # Save any arguments that we might want to pass through to other
215 # programs. This is used by the -args flag.
216 # FINDUSER
217 Default parameters {}
218
219 # Count the number of files tested (0 if runAllTests wasn't called).
220 # runAllTests will set testSingleFile to false, so stats will
221 # not be printed until runAllTests calls the cleanupTests proc.
222 # The currentFailure var stores the boolean value of whether the
223 # current test file has had any failures. The failFiles list
224 # stores the names of test files that had failures.
225 Default numTestFiles 0 AcceptInteger
226 Default testSingleFile true AcceptBoolean
227 Default currentFailure false AcceptBoolean
228 Default failFiles {} AcceptList
229
230 # Tests should remove all files they create. The test suite will
231 # check the current working dir for files created by the tests.
232 # filesMade keeps track of such files created using the makeFile and
233 # makeDirectory procedures. filesExisted stores the names of
234 # preexisting files.
235 #
236 # Note that $filesExisted lists only those files that exist in
237 # the original [temporaryDirectory].
238 Default filesMade {} AcceptList
239 Default filesExisted {} AcceptList
240 proc FillFilesExisted {} {
241 variable filesExisted
242
243 # Save the names of files that already exist in the scratch directory.
244 foreach file [glob -nocomplain -directory [temporaryDirectory] *] {
245 lappend filesExisted [file tail $file]
246 }
247
248 # After successful filling, turn this into a no-op.
249 proc FillFilesExisted args {}
250 }
251
252 # Kept only for compatibility
253 Default constraintsSpecified {} AcceptList
254 trace add variable constraintsSpecified read [namespace code {
255 set constraintsSpecified [array names testConstraints] ;#}]
256
257 # tests that use threads need to know which is the main thread
258 Default mainThread 1
259 variable mainThread
260 if {[info commands thread::id] ne {}} {
261 set mainThread [thread::id]
262 } elseif {[info commands testthread] ne {}} {
263 set mainThread [testthread id]
264 }
265
266 # Set workingDirectory to [pwd]. The default output directory for
267 # Tcl tests is the working directory. Whenever this value changes
268 # change to that directory.
269 variable workingDirectory
270 trace add variable workingDirectory write \
271 [namespace code {cd $workingDirectory ;#}]
272
273 Default workingDirectory [pwd] AcceptAbsolutePath
274 proc workingDirectory { {dir ""} } {
275 variable workingDirectory
276 if {[llength [info level 0]] == 1} {
277 return $workingDirectory
278 }
279 set workingDirectory [AcceptAbsolutePath $dir]
280 }
281
282 # Set the location of the execuatble
283 Default tcltest [info nameofexecutable]
284 trace add variable tcltest write [namespace code {testConstraint stdio \
285 [eval [ConstraintInitializer stdio]] ;#}]
286
287 # save the platform information so it can be restored later
288 Default originalTclPlatform [array get ::tcl_platform]
289
290 # If a core file exists, save its modification time.
291 if {[file exists [file join [workingDirectory] core]]} {
292 Default coreModTime \
293 [file mtime [file join [workingDirectory] core]]
294 }
295
296 # stdout and stderr buffers for use when we want to store them
297 Default outData {}
298 Default errData {}
299
300 # keep track of test level for nested test commands
301 variable testLevel 0
302
303 # the variables and procedures that existed when saveState was called are
304 # stored in a variable of the same name
305 Default saveState {}
306
307 # Internationalization support -- used in [SetIso8859_1_Locale] and
308 # [RestoreLocale]. Those commands are used in cmdIL.test.
309
310 if {![info exists [namespace current]::isoLocale]} {
311 variable isoLocale fr
312 switch -- $::tcl_platform(platform) {
313 "unix" {
314
315 # Try some 'known' values for some platforms:
316
317 switch -exact -- $::tcl_platform(os) {
318 "FreeBSD" {
319 set isoLocale fr_FR.ISO_8859-1
320 }
321 HP-UX {
322 set isoLocale fr_FR.iso88591
323 }
324 Linux -
325 IRIX {
326 set isoLocale fr
327 }
328 default {
329
330 # Works on SunOS 4 and Solaris, and maybe
331 # others... Define it to something else on your
332 # system if you want to test those.
333
334 set isoLocale iso_8859_1
335 }
336 }
337 }
338 "windows" {
339 set isoLocale French
340 }
341 }
342 }
343
344 variable ChannelsWeOpened; array set ChannelsWeOpened {}
345 # output goes to stdout by default
346 Default outputChannel stdout
347 proc outputChannel { {filename ""} } {
348 variable outputChannel
349 variable ChannelsWeOpened
350 variable fullutf
351
352 # This is very subtle and tricky, so let me try to explain.
353 # (Hopefully this longer comment will be clear when I come
354 # back in a few months, unlike its predecessor :) )
355 #
356 # The [outputChannel] command (and underlying variable) have to
357 # be kept in sync with the [configure -outfile] configuration
358 # option ( and underlying variable Option(-outfile) ). This is
359 # accomplished with a write trace on Option(-outfile) that will
360 # update [outputChannel] whenever a new value is written. That
361 # much is easy.
362 #
363 # The trick is that in order to maintain compatibility with
364 # version 1 of tcltest, we must allow every configuration option
365 # to get its initial value from command line arguments. This is
366 # accomplished by setting initial read traces on all the
367 # configuration options to parse the command line option the first
368 # time they are read. These traces are cancelled whenever the
369 # program itself calls [configure].
370 #
371 # OK, then so to support tcltest 1 compatibility, it seems we want
372 # to get the return from [outputFile] to trigger the read traces,
373 # just in case.
374 #
375 # BUT! A little known feature of Tcl variable traces is that
376 # traces are disabled during the handling of other traces. So,
377 # if we trigger read traces on Option(-outfile) and that triggers
378 # command line parsing which turns around and sets an initial
379 # value for Option(-outfile) -- <whew!> -- the write trace that
380 # would keep [outputChannel] in sync with that new initial value
381 # would not fire!
382 #
383 # SO, finally, as a workaround, instead of triggering read traces
384 # by invoking [outputFile], we instead trigger the same set of
385 # read traces by invoking [debug]. Any command that reads a
386 # configuration option would do. [debug] is just a handy one.
387 # The end result is that we support tcltest 1 compatibility and
388 # keep outputChannel and -outfile in sync in all cases.
389 debug
390
391 if {[llength [info level 0]] == 1} {
392 return $outputChannel
393 }
394 if {[info exists ChannelsWeOpened($outputChannel)]} {
395 close $outputChannel
396 unset ChannelsWeOpened($outputChannel)
397 }
398 switch -exact -- $filename {
399 stderr -
400 stdout {
401 set outputChannel $filename
402 }
403 default {
404 set outputChannel [open $filename a]
405 if {$fullutf} {
406 fconfigure $outputChannel -profile tcl8 -encoding utf-8
407 }
408 set ChannelsWeOpened($outputChannel) 1
409
410 # If we created the file in [temporaryDirectory], then
411 # [cleanupTests] will delete it, unless we claim it was
412 # already there.
413 set outdir [normalizePath [file dirname \
414 [file join [pwd] $filename]]]
415 if {$outdir eq [temporaryDirectory]} {
416 variable filesExisted
417 FillFilesExisted
418 set filename [file tail $filename]
419 if {$filename ni $filesExisted} {
420 lappend filesExisted $filename
421 }
422 }
423 }
424 }
425 return $outputChannel
426 }
427
428 # errors go to stderr by default
429 Default errorChannel stderr
430 proc errorChannel { {filename ""} } {
431 variable errorChannel
432 variable ChannelsWeOpened
433 variable fullutf
434
435 # This is subtle and tricky. See the comment above in
436 # [outputChannel] for a detailed explanation.
437 debug
438
439 if {[llength [info level 0]] == 1} {
440 return $errorChannel
441 }
442 if {[info exists ChannelsWeOpened($errorChannel)]} {
443 close $errorChannel
444 unset ChannelsWeOpened($errorChannel)
445 }
446 switch -exact -- $filename {
447 stderr -
448 stdout {
449 set errorChannel $filename
450 }
451 default {
452 set errorChannel [open $filename a]
453 if {$fullutf} {
454 fconfigure $errorChannel -profile tcl8 -encoding utf-8
455 }
456 set ChannelsWeOpened($errorChannel) 1
457
458 # If we created the file in [temporaryDirectory], then
459 # [cleanupTests] will delete it, unless we claim it was
460 # already there.
461 set outdir [normalizePath [file dirname \
462 [file join [pwd] $filename]]]
463 if {$outdir eq [temporaryDirectory]} {
464 variable filesExisted
465 FillFilesExisted
466 set filename [file tail $filename]
467 if {$filename ni $filesExisted} {
468 lappend filesExisted $filename
469 }
470 }
471 }
472 }
473 return $errorChannel
474 }
475
476 ##### Set up the configurable options
477 #
478 # The configurable options of the package
479 variable Option; array set Option {}
480
481 # Usage strings for those options
482 variable Usage; array set Usage {}
483
484 # Verification commands for those options
485 variable Verify; array set Verify {}
486
487 # Initialize the default values of the configurable options that are
488 # historically associated with an exported variable. If that variable
489 # is already set, support compatibility by accepting its preset value.
490 # Use [trace] to establish ongoing connection between the deprecated
491 # exported variable and the modern option kept as a true internal var.
492 # Also set up usage string and value testing for the option.
493 proc Option {option value usage {verify AcceptAll} {varName {}}} {
494 variable Option
495 variable Verify
496 variable Usage
497 variable OptionControlledVariables
498 variable DefaultValue
499 set Usage($option) $usage
500 set Verify($option) $verify
501 set DefaultValue($option) $value
502 if {[catch {$verify $value} msg]} {
503 return -code error $msg
504 } else {
505 set Option($option) $msg
506 }
507 if {[string length $varName]} {
508 variable $varName
509 if {[info exists $varName]} {
510 if {[catch {$verify [set $varName]} msg]} {
511 return -code error $msg
512 } else {
513 set Option($option) $msg
514 }
515 unset $varName
516 }
517 namespace eval [namespace current] \
518 [list upvar 0 Option($option) $varName]
519 # Workaround for Bug (now Feature Request) 572889. Grrrr....
520 # Track all the variables tied to options
521 lappend OptionControlledVariables $varName
522 # Later, set auto-configure read traces on all
523 # of them, since a single trace on Option does not work.
524 proc $varName {{value {}}} [subst -nocommands {
525 if {[llength [info level 0]] == 2} {
526 Configure $option [set value]
527 }
528 return [Configure $option]
529 }]
530 }
531 }
532
533 proc MatchingOption {option} {
534 variable Option
535 set match [array names Option $option*]
536 switch -- [llength $match] {
537 0 {
538 set sorted [lsort [array names Option]]
539 set values [join [lrange $sorted 0 end-1] ", "]
540 append values ", or [lindex $sorted end]"
541 return -code error "unknown option $option: should be\
542 one of $values"
543 }
544 1 {
545 return [lindex $match 0]
546 }
547 default {
548 # Exact match trumps ambiguity
549 if {$option in $match} {
550 return $option
551 }
552 set values [join [lrange $match 0 end-1] ", "]
553 append values ", or [lindex $match end]"
554 return -code error "ambiguous option $option:\
555 could match $values"
556 }
557 }
558 }
559
560 proc EstablishAutoConfigureTraces {} {
561 variable OptionControlledVariables
562 foreach varName [concat $OptionControlledVariables Option] {
563 variable $varName
564 trace add variable $varName read [namespace code {
565 ProcessCmdLineArgs ;#}]
566 }
567 }
568
569 proc RemoveAutoConfigureTraces {} {
570 variable OptionControlledVariables
571 foreach varName [concat $OptionControlledVariables Option] {
572 variable $varName
573 foreach pair [trace info variable $varName] {
574 lassign $pair op cmd
575 if {($op eq "read") &&
576 [string match *ProcessCmdLineArgs* $cmd]} {
577 trace remove variable $varName $op $cmd
578 }
579 }
580 }
581 # Once the traces are removed, this can become a no-op
582 proc RemoveAutoConfigureTraces {} {}
583 }
584
585 proc Configure args {
586 variable Option
587 variable Verify
588 set n [llength $args]
589 if {$n == 0} {
590 return [lsort [array names Option]]
591 }
592 if {$n == 1} {
593 if {[catch {MatchingOption [lindex $args 0]} option]} {
594 return -code error $option
595 }
596 return $Option($option)
597 }
598 while {[llength $args] > 1} {
599 if {[catch {MatchingOption [lindex $args 0]} option]} {
600 return -code error $option
601 }
602 if {[catch {$Verify($option) [lindex $args 1]} value]} {
603 return -code error "invalid $option\
604 value \"[lindex $args 1]\": $value"
605 }
606 set Option($option) $value
607 set args [lrange $args 2 end]
608 }
609 if {[llength $args]} {
610 if {[catch {MatchingOption [lindex $args 0]} option]} {
611 return -code error $option
612 }
613 return -code error "missing value for option $option"
614 }
615 }
616 proc configure args {
617 if {[llength $args] > 1} {
618 RemoveAutoConfigureTraces
619 }
620 set code [catch {Configure {*}$args} msg]
621 return -code $code $msg
622 }
623
624 proc AcceptVerbose { level } {
625 set level [AcceptList $level]
626 set levelMap {
627 l list
628 p pass
629 b body
630 s skip
631 t start
632 e error
633 l line
634 m msec
635 u usec
636 }
637 set levelRegexp "^([join [dict values $levelMap] |])\$"
638 if {[llength $level] == 1} {
639 if {![regexp $levelRegexp $level]} {
640 # translate single characters abbreviations to expanded list
641 set level [string map $levelMap [split $level {}]]
642 }
643 }
644 set valid [list]
645 foreach v $level {
646 if {[regexp $levelRegexp $v]} {
647 lappend valid $v
648 }
649 }
650 return $valid
651 }
652
653 proc IsVerbose {level} {
654 variable Option
655 return [expr {$level in $Option(-verbose)}]
656 }
657
658 # Default verbosity is to show bodies of failed tests
659 Option -verbose {body error} {
660 Takes any combination of the values 'p', 's', 'b', 't', 'e' and 'l'.
661 Test suite will display all passed tests if 'p' is specified, all
662 skipped tests if 's' is specified, the bodies of failed tests if
663 'b' is specified, and when tests start if 't' is specified.
664 ErrorInfo is displayed if 'e' is specified. Source file line
665 information of failed tests is displayed if 'l' is specified.
666 } AcceptVerbose verbose
667
668 # Match and skip patterns default to the empty list, except for
669 # matchFiles, which defaults to all .test files in the
670 # testsDirectory and matchDirectories, which defaults to all
671 # directories.
672 Option -match * {
673 Run all tests within the specified files that match one of the
674 list of glob patterns given.
675 } AcceptList match
676
677 Option -skip {} {
678 Skip all tests within the specified tests (via -match) and files
679 that match one of the list of glob patterns given.
680 } AcceptList skip
681
682 Option -file *.test {
683 Run tests in all test files that match the glob pattern given.
684 } AcceptPattern matchFiles
685
686 # By default, skip files that appear to be SCCS lock files.
687 Option -notfile l.*.test {
688 Skip all test files that match the glob pattern given.
689 } AcceptPattern skipFiles
690
691 Option -relateddir * {
692 Run tests in directories that match the glob pattern given.
693 } AcceptPattern matchDirectories
694
695 Option -asidefromdir {} {
696 Skip tests in directories that match the glob pattern given.
697 } AcceptPattern skipDirectories
698
699 # By default, don't save core files
700 Option -preservecore 0 {
701 If 2, save any core files produced during testing in the directory
702 specified by -tmpdir. If 1, notify the user if core files are
703 created.
704 } AcceptInteger preserveCore
705
706 # debug output doesn't get printed by default; debug level 1 spits
707 # up only the tests that were skipped because they didn't match or
708 # were specifically skipped. A debug level of 2 would spit up the
709 # tcltest variables and flags provided; a debug level of 3 causes
710 # some additional output regarding operations of the test harness.
711 # The tcltest package currently implements only up to debug level 3.
712 Option -debug 0 {
713 Internal debug level
714 } AcceptInteger debug
715
716 proc SetSelectedConstraints args {
717 variable Option
718 foreach c $Option(-constraints) {
719 testConstraint $c 1
720 }
721 }
722 Option -constraints {} {
723 Do not skip the listed constraints listed in -constraints.
724 } AcceptList
725 trace add variable Option(-constraints) write \
726 [namespace code {SetSelectedConstraints ;#}]
727
728 # Don't run only the "-constraint" specified tests by default
729 proc ClearUnselectedConstraints args {
730 variable Option
731 variable testConstraints
732 if {!$Option(-limitconstraints)} {return}
733 foreach c [array names testConstraints] {
734 if {$c ni $Option(-constraints)} {
735 testConstraint $c 0
736 }
737 }
738 }
739 Option -limitconstraints 0 {
740 whether to run only tests with the constraints
741 } AcceptBoolean limitConstraints
742 trace add variable Option(-limitconstraints) write \
743 [namespace code {ClearUnselectedConstraints ;#}]
744
745 # A test application has to know how to load the tested commands
746 # into the interpreter.
747 Option -load {} {
748 Specifies the script to load the tested commands.
749 } AcceptScript loadScript
750
751 # Default is to run each test file in a separate process
752 Option -singleproc 0 {
753 whether to run all tests in one process
754 } AcceptBoolean singleProcess
755
756 proc AcceptTemporaryDirectory { directory } {
757 set directory [AcceptAbsolutePath $directory]
758 if {![file exists $directory]} {
759 file mkdir $directory
760 }
761 set directory [AcceptDirectory $directory]
762 if {![file writable $directory]} {
763 if {[workingDirectory] eq $directory} {
764 # Special exception: accept the default value
765 # even if the directory is not writable
766 return $directory
767 }
768 return -code error "\"$directory\" is not writable"
769 }
770 return $directory
771 }
772
773 # Directory where files should be created
774 Option -tmpdir [workingDirectory] {
775 Save temporary files in the specified directory.
776 } AcceptTemporaryDirectory temporaryDirectory
777 trace add variable Option(-tmpdir) write \
778 [namespace code {normalizePath Option(-tmpdir) ;#}]
779
780 # Tests should not rely on the current working directory.
781 # Files that are part of the test suite should be accessed relative
782 # to [testsDirectory]
783 Option -testdir [workingDirectory] {
784 Search tests in the specified directory.
785 } AcceptDirectory testsDirectory
786 trace add variable Option(-testdir) write \
787 [namespace code {normalizePath Option(-testdir) ;#}]
788
789 proc AcceptLoadFile { file } {
790 if {$file eq {}} {return $file}
791 set file [file join [temporaryDirectory] $file]
792 return [AcceptReadable $file]
793 }
794 proc ReadLoadScript {args} {
795 variable Option
796 variable fullutf
797
798 if {$Option(-loadfile) eq {}} {return}
799 set tmp [open $Option(-loadfile) r]
800 if {$fullutf} {
801 fconfigure $tmp -profile tcl8 -encoding utf-8
802 }
803 loadScript [read $tmp]
804 close $tmp
805 }
806 Option -loadfile {} {
807 Read the script to load the tested commands from the specified file.
808 } AcceptLoadFile loadFile
809 trace add variable Option(-loadfile) write [namespace code ReadLoadScript]
810
811 proc AcceptOutFile { file } {
812 if {[string equal stderr $file]} {return $file}
813 if {[string equal stdout $file]} {return $file}
814 return [file join [temporaryDirectory] $file]
815 }
816
817 # output goes to stdout by default
818 Option -outfile stdout {
819 Send output from test runs to the specified file.
820 } AcceptOutFile outputFile
821 trace add variable Option(-outfile) write \
822 [namespace code {outputChannel $Option(-outfile) ;#}]
823
824 # errors go to stderr by default
825 Option -errfile stderr {
826 Send errors from test runs to the specified file.
827 } AcceptOutFile errorFile
828 trace add variable Option(-errfile) write \
829 [namespace code {errorChannel $Option(-errfile) ;#}]
830
831 proc loadIntoChildInterpreter {child args} {
832 variable Version
833 interp eval $child [package ifneeded tcltest $Version]
834 interp eval $child "tcltest::configure {*}{$args}"
835 interp alias $child ::tcltest::ReportToParent \
836 {} ::tcltest::ReportedFromChild
837 }
838 proc ReportedFromChild {total passed skipped failed because newfiles} {
839 variable numTests
840 variable skippedBecause
841 variable createdNewFiles
842 incr numTests(Total) $total
843 incr numTests(Passed) $passed
844 incr numTests(Skipped) $skipped
845 incr numTests(Failed) $failed
846 foreach {constraint count} $because {
847 incr skippedBecause($constraint) $count
848 }
849 foreach {testfile created} $newfiles {
850 lappend createdNewFiles($testfile) {*}$created
851 }
852 return
853 }
854 }
855
856 #####################################################################
857
858 # tcltest::Debug* --
859 #
860 # Internal helper procedures to write out debug information
861 # dependent on the chosen level. A test shell may override
862 # them, f.e. to redirect the output into a different
863 # channel, or even into a GUI.
864
865 # tcltest::DebugPuts --
866 #
867 # Prints the specified string if the current debug level is
868 # higher than the provided level argument.
869 #
870 # Arguments:
871 # level The lowest debug level triggering the output
872 # string The string to print out.
873 #
874 # Results:
875 # Prints the string. Nothing else is allowed.
876 #
877 # Side Effects:
878 # None.
879 #
880
881 proc tcltest::DebugPuts {level string} {
882 variable debug
883 if {$debug >= $level} {
884 puts $string
885 }
886 return
887 }
888
889 # tcltest::DebugPArray --
890 #
891 # Prints the contents of the specified array if the current
892 # debug level is higher than the provided level argument
893 #
894 # Arguments:
895 # level The lowest debug level triggering the output
896 # arrayvar The name of the array to print out.
897 #
898 # Results:
899 # Prints the contents of the array. Nothing else is allowed.
900 #
901 # Side Effects:
902 # None.
903 #
904
905 proc tcltest::DebugPArray {level arrayvar} {
906 variable debug
907
908 if {$debug >= $level} {
909 catch {upvar 1 $arrayvar $arrayvar}
910 parray $arrayvar
911 }
912 return
913 }
914
915 # Define our own [parray] in ::tcltest that will inherit use of the [puts]
916 # defined in ::tcltest. NOTE: Ought to construct with [info args] and
917 # [info default], but can't be bothered now. If [parray] changes, then
918 # this will need changing too.
919 auto_load ::parray
920 proc tcltest::parray {a {pattern *}} [info body ::parray]
921
922 # tcltest::DebugDo --
923 #
924 # Executes the script if the current debug level is greater than
925 # the provided level argument
926 #
927 # Arguments:
928 # level The lowest debug level triggering the execution.
929 # script The tcl script executed upon a debug level high enough.
930 #
931 # Results:
932 # Arbitrary side effects, dependent on the executed script.
933 #
934 # Side Effects:
935 # None.
936 #
937
938 proc tcltest::DebugDo {level script} {
939 variable debug
940
941 if {$debug >= $level} {
942 uplevel 1 $script
943 }
944 return
945 }
946
947 #####################################################################
948
949 proc tcltest::Warn {msg} {
950 puts [outputChannel] "WARNING: $msg"
951 }
952
953 # tcltest::mainThread
954 #
955 # Accessor command for tcltest variable mainThread.
956 #
957 proc tcltest::mainThread { {new ""} } {
958 variable mainThread
959 if {[llength [info level 0]] == 1} {
960 return $mainThread
961 }
962 set mainThread $new
963 }
964
965 # tcltest::testConstraint --
966 #
967 # sets a test constraint to a value; to do multiple constraints,
968 # call this proc multiple times. also returns the value of the
969 # named constraint if no value was supplied.
970 #
971 # Arguments:
972 # constraint - name of the constraint
973 # value - new value for constraint (should be boolean) - if not
974 # supplied, this is a query
975 #
976 # Results:
977 # content of tcltest::testConstraints($constraint)
978 #
979 # Side effects:
980 # none
981
982 proc tcltest::testConstraint {constraint {value ""}} {
983 variable testConstraints
984 variable Option
985 DebugPuts 3 "entering testConstraint $constraint $value"
986 if {[llength [info level 0]] == 2} {
987 return $testConstraints($constraint)
988 }
989 # Check for boolean values
990 if {[catch {expr {$value && 1}} msg]} {
991 return -code error $msg
992 }
993 if {[limitConstraints] && ($constraint ni $Option(-constraints))} {
994 set value 0
995 }
996 set testConstraints($constraint) $value
997 }
998
999 # tcltest::interpreter --
1000 #
1001 # the interpreter name stored in tcltest::tcltest
1002 #
1003 # Arguments:
1004 # executable name
1005 #
1006 # Results:
1007 # content of tcltest::tcltest
1008 #
1009 # Side effects:
1010 # None.
1011
1012 proc tcltest::interpreter { {interp ""} } {
1013 variable tcltest
1014 if {[llength [info level 0]] == 1} {
1015 return $tcltest
1016 }
1017 set tcltest $interp
1018 }
1019
1020 #####################################################################
1021
1022 # tcltest::AddToSkippedBecause --
1023 #
1024 # Increments the variable used to track how many tests were
1025 # skipped because of a particular constraint.
1026 #
1027 # Arguments:
1028 # constraint The name of the constraint to be modified
1029 #
1030 # Results:
1031 # Modifies tcltest::skippedBecause; sets the variable to 1 if
1032 # didn't previously exist - otherwise, it just increments it.
1033 #
1034 # Side effects:
1035 # None.
1036
1037 proc tcltest::AddToSkippedBecause { constraint {value 1}} {
1038 # add the constraint to the list of constraints that kept tests
1039 # from running
1040 variable skippedBecause
1041
1042 if {[info exists skippedBecause($constraint)]} {
1043 incr skippedBecause($constraint) $value
1044 } else {
1045 set skippedBecause($constraint) $value
1046 }
1047 return
1048 }
1049
1050 # tcltest::PrintError --
1051 #
1052 # Prints errors to tcltest::errorChannel and then flushes that
1053 # channel, making sure that all messages are < 80 characters per
1054 # line.
1055 #
1056 # Arguments:
1057 # errorMsg String containing the error to be printed
1058 #
1059 # Results:
1060 # None.
1061 #
1062 # Side effects:
1063 # None.
1064
1065 proc tcltest::PrintError {errorMsg} {
1066 set InitialMessage "Error: "
1067 set InitialMsgLen [string length $InitialMessage]
1068 puts -nonewline [errorChannel] $InitialMessage
1069
1070 # Keep track of where the end of the string is.
1071 set endingIndex [string length $errorMsg]
1072
1073 if {$endingIndex < (80 - $InitialMsgLen)} {
1074 puts [errorChannel] $errorMsg
1075 } else {
1076 # Print up to 80 characters on the first line, including the
1077 # InitialMessage.
1078 set beginningIndex [string last " " [string range $errorMsg 0 \
1079 [expr {80 - $InitialMsgLen}]]]
1080 puts [errorChannel] [string range $errorMsg 0 $beginningIndex]
1081
1082 while {$beginningIndex ne "end"} {
1083 puts -nonewline [errorChannel] \
1084 [string repeat " " $InitialMsgLen]
1085 if {($endingIndex - $beginningIndex)
1086 < (80 - $InitialMsgLen)} {
1087 puts [errorChannel] [string trim \
1088 [string range $errorMsg $beginningIndex end]]
1089 break
1090 } else {
1091 set newEndingIndex [expr {[string last " " \
1092 [string range $errorMsg $beginningIndex \
1093 [expr {$beginningIndex
1094 + (80 - $InitialMsgLen)}]
1095 ]] + $beginningIndex}]
1096 if {($newEndingIndex <= 0)
1097 || ($newEndingIndex <= $beginningIndex)} {
1098 set newEndingIndex end
1099 }
1100 puts [errorChannel] [string trim \
1101 [string range $errorMsg \
1102 $beginningIndex $newEndingIndex]]
1103 set beginningIndex $newEndingIndex
1104 }
1105 }
1106 }
1107 flush [errorChannel]
1108 return
1109 }
1110
1111 # tcltest::SafeFetch --
1112 #
1113 # The following trace procedure makes it so that we can safely
1114 # refer to non-existent members of the testConstraints array
1115 # without causing an error. Instead, reading a non-existent
1116 # member will return 0. This is necessary because tests are
1117 # allowed to use constraint "X" without ensuring that
1118 # testConstraints("X") is defined.
1119 #
1120 # Arguments:
1121 # n1 - name of the array (testConstraints)
1122 # n2 - array key value (constraint name)
1123 # op - operation performed on testConstraints (generally r)
1124 #
1125 # Results:
1126 # none
1127 #
1128 # Side effects:
1129 # sets testConstraints($n2) to 0 if it's referenced but never
1130 # before used
1131
1132 proc tcltest::SafeFetch {n1 n2 op} {
1133 variable testConstraints
1134 DebugPuts 3 "entering SafeFetch $n1 $n2 $op"
1135 if {$n2 eq {}} {return}
1136 if {![info exists testConstraints($n2)]} {
1137 if {[catch {testConstraint $n2 [eval [ConstraintInitializer $n2]]}]} {
1138 testConstraint $n2 0
1139 }
1140 }
1141 }
1142
1143 # tcltest::Asciify --
1144 #
1145 # Transforms the passed string to contain only printable ascii characters.
1146 # Useful for printing to terminals. Non-printables are mapped to
1147 # \x, \u or \U sequences, except \n.
1148 #
1149 # Arguments:
1150 # s - string to transform
1151 #
1152 # Results:
1153 # The transformed strings
1154 #
1155 # Side effects:
1156 # None.
1157
1158 proc tcltest::Asciify {s} {
1159 set print ""
1160 foreach c [split $s ""] {
1161 if {(($c < "\x7F") && [string is print $c]) || ($c eq "\n")} {
1162 append print $c
1163 } elseif {$c < "\u0100"} {
1164 append print \\x[format %02X [scan $c %c]]
1165 } elseif {$c > "\uFFFF"} {
1166 append print \\U[format %08X [scan $c %c]]
1167 } else {
1168 append print \\u[format %04X [scan $c %c]]
1169 }
1170 }
1171 return $print
1172 }
1173
1174 # tcltest::ConstraintInitializer --
1175 #
1176 # Get or set a script that when evaluated in the tcltest namespace
1177 # will return a boolean value with which to initialize the
1178 # associated constraint.
1179 #
1180 # Arguments:
1181 # constraint - name of the constraint initialized by the script
1182 # script - the initializer script
1183 #
1184 # Results
1185 # boolean value of the constraint - enabled or disabled
1186 #
1187 # Side effects:
1188 # Constraint is initialized for future reference by [test]
1189 proc tcltest::ConstraintInitializer {constraint {script ""}} {
1190 variable ConstraintInitializer
1191 DebugPuts 3 "entering ConstraintInitializer $constraint $script"
1192 if {[llength [info level 0]] == 2} {
1193 return $ConstraintInitializer($constraint)
1194 }
1195 # Check for boolean values
1196 if {![info complete $script]} {
1197 return -code error "ConstraintInitializer must be complete script"
1198 }
1199 set ConstraintInitializer($constraint) $script
1200 }
1201
1202 # tcltest::InitConstraints --
1203 #
1204 # Call all registered constraint initializers to force initialization
1205 # of all known constraints.
1206 # See the tcltest man page for the list of built-in constraints defined
1207 # in this procedure.
1208 #
1209 # Arguments:
1210 # none
1211 #
1212 # Results:
1213 # The testConstraints array is reset to have an index for each
1214 # built-in test constraint.
1215 #
1216 # Side Effects:
1217 # None.
1218 #
1219
1220 proc tcltest::InitConstraints {} {
1221 variable ConstraintInitializer
1222 initConstraintsHook
1223 foreach constraint [array names ConstraintInitializer] {
1224 testConstraint $constraint
1225 }
1226 }
1227
1228 proc tcltest::DefineConstraintInitializers {} {
1229 ConstraintInitializer singleTestInterp {singleProcess}
1230
1231 # All the 'pc' constraints are here for backward compatibility and
1232 # are not documented. They have been replaced with equivalent 'win'
1233 # constraints.
1234
1235 ConstraintInitializer unixOnly \
1236 {string equal $::tcl_platform(platform) unix}
1237 ConstraintInitializer macOnly \
1238 {string equal $::tcl_platform(platform) macintosh}
1239 ConstraintInitializer pcOnly \
1240 {string equal $::tcl_platform(platform) windows}
1241 ConstraintInitializer winOnly \
1242 {string equal $::tcl_platform(platform) windows}
1243
1244 ConstraintInitializer unix {testConstraint unixOnly}
1245 ConstraintInitializer mac {testConstraint macOnly}
1246 ConstraintInitializer pc {testConstraint pcOnly}
1247 ConstraintInitializer win {testConstraint winOnly}
1248
1249 ConstraintInitializer unixOrPc \
1250 {expr {[testConstraint unix] || [testConstraint pc]}}
1251 ConstraintInitializer macOrPc \
1252 {expr {[testConstraint mac] || [testConstraint pc]}}
1253 ConstraintInitializer unixOrWin \
1254 {expr {[testConstraint unix] || [testConstraint win]}}
1255 ConstraintInitializer macOrWin \
1256 {expr {[testConstraint mac] || [testConstraint win]}}
1257 ConstraintInitializer macOrUnix \
1258 {expr {[testConstraint mac] || [testConstraint unix]}}
1259
1260 ConstraintInitializer nt {string equal $::tcl_platform(os) "Windows NT"}
1261 ConstraintInitializer 95 {string equal $::tcl_platform(os) "Windows 95"}
1262 ConstraintInitializer 98 {string equal $::tcl_platform(os) "Windows 98"}
1263
1264 # The following Constraints switches are used to mark tests that
1265 # should work, but have been temporarily disabled on certain
1266 # platforms because they don't and we haven't gotten around to
1267 # fixing the underlying problem.
1268
1269 ConstraintInitializer tempNotPc {expr {![testConstraint pc]}}
1270 ConstraintInitializer tempNotWin {expr {![testConstraint win]}}
1271 ConstraintInitializer tempNotMac {expr {![testConstraint mac]}}
1272 ConstraintInitializer tempNotUnix {expr {![testConstraint unix]}}
1273
1274 # The following Constraints switches are used to mark tests that
1275 # crash on certain platforms, so that they can be reactivated again
1276 # when the underlying problem is fixed.
1277
1278 ConstraintInitializer pcCrash {expr {![testConstraint pc]}}
1279 ConstraintInitializer winCrash {expr {![testConstraint win]}}
1280 ConstraintInitializer macCrash {expr {![testConstraint mac]}}
1281 ConstraintInitializer unixCrash {expr {![testConstraint unix]}}
1282
1283 # Skip empty tests
1284
1285 ConstraintInitializer emptyTest {expr 0}
1286
1287 # By default, tests that expose known bugs are skipped.
1288
1289 ConstraintInitializer knownBug {expr 0}
1290
1291 # By default, non-portable tests are skipped.
1292
1293 ConstraintInitializer nonPortable {expr 0}
1294
1295 # By default, extremely slow, extensive or IO-aggressive tests are skipped.
1296
1297 ConstraintInitializer extensive {expr 0}
1298
1299 # Some tests require user interaction.
1300
1301 ConstraintInitializer userInteraction {expr 0}
1302
1303 # Some tests must be skipped if the interpreter is not in
1304 # interactive mode
1305
1306 ConstraintInitializer interactive \
1307 {expr {[info exists ::tcl_interactive] && $::tcl_interactive}}
1308
1309 # Some tests can only be run if the installation came from a CD
1310 # image instead of a web image. Some tests must be skipped if you
1311 # are running as root on Unix. Other tests can only be run if you
1312 # are running as root on Unix.
1313
1314 ConstraintInitializer root {expr \
1315 {($::tcl_platform(platform) eq "unix") &&
1316 ($::tcl_platform(user) in {root {}})}}
1317 ConstraintInitializer notRoot {expr {![testConstraint root]}}
1318
1319 # Set nonBlockFiles constraint: 1 means this platform supports
1320 # setting files into nonblocking mode.
1321
1322 ConstraintInitializer nonBlockFiles {
1323 set code [expr {[catch {set f [open defs r]}]
1324 || [catch {fconfigure $f -blocking off}]}]
1325 catch {close $f}
1326 set code
1327 }
1328
1329 # Set asyncPipeClose constraint: 1 means this platform supports
1330 # async flush and async close on a pipe.
1331 #
1332 # Test for SCO Unix - cannot run async flushing tests because a
1333 # potential problem with select is apparently interfering.
1334 # (Mark Diekhans).
1335
1336 ConstraintInitializer asyncPipeClose {expr {
1337 !([string equal unix $::tcl_platform(platform)]
1338 && ([catch {exec uname -X | fgrep {Release = 3.2v}}] == 0))}}
1339
1340 # Test to see if we have a broken version of sprintf with respect
1341 # to the "e" format of floating-point numbers.
1342
1343 ConstraintInitializer eformat {string equal [format %g 5e-5] 5e-05}
1344
1345 # Test to see if execed commands such as cat, echo, rm and so forth
1346 # are present on this machine.
1347
1348 ConstraintInitializer unixExecs {
1349 set code 1
1350 if {$::tcl_platform(platform) eq "macintosh"} {
1351 set code 0
1352 }
1353 if {$::tcl_platform(platform) eq "windows"} {
1354 if {[catch {
1355 set file _tcl_test_remove_me.txt
1356 makeFile {hello} $file
1357 }]} {
1358 set code 0
1359 } elseif {
1360 [catch {exec cat $file}] ||
1361 [catch {exec echo hello}] ||
1362 [catch {exec sh -c echo hello}] ||
1363 [catch {exec wc $file}] ||
1364 [catch {exec sleep 1}] ||
1365 [catch {exec echo abc > $file}] ||
1366 [catch {exec chmod 644 $file}] ||
1367 [catch {exec rm $file}] ||
1368 [llength [auto_execok mkdir]] == 0 ||
1369 [llength [auto_execok fgrep]] == 0 ||
1370 [llength [auto_execok grep]] == 0 ||
1371 [llength [auto_execok ps]] == 0
1372 } {
1373 set code 0
1374 }
1375 removeFile $file
1376 }
1377 set code
1378 }
1379
1380 ConstraintInitializer stdio {
1381 variable fullutf
1382
1383 set code 0
1384 if {![catch {set f [open "|[list [interpreter]]" w]}]} {
1385 if {$fullutf} {
1386 fconfigure $f -profile tcl8 -encoding utf-8
1387 }
1388 if {![catch {puts $f exit}]} {
1389 if {![catch {close $f}]} {
1390 set code 1
1391 }
1392 }
1393 }
1394 set code
1395 }
1396
1397 # Deliberately call socket with the wrong number of arguments. The
1398 # error message you get will indicate whether sockets are available
1399 # on this system.
1400
1401 ConstraintInitializer socket {
1402 catch {socket} msg
1403 string compare $msg "sockets are not available on this system"
1404 }
1405
1406 # Check for internationalization
1407 ConstraintInitializer hasIsoLocale {
1408 if {[llength [info commands testlocale]] == 0} {
1409 set code 0
1410 } else {
1411 set code [string length [SetIso8859_1_Locale]]
1412 RestoreLocale
1413 }
1414 set code
1415 }
1416
1417 }
1418 #####################################################################
1419
1420 # Usage and command line arguments processing.
1421
1422 # tcltest::PrintUsageInfo
1423 #
1424 # Prints out the usage information for package tcltest. This can
1425 # be customized with the redefinition of [PrintUsageInfoHook].
1426 #
1427 # Arguments:
1428 # none
1429 #
1430 # Results:
1431 # none
1432 #
1433 # Side Effects:
1434 # none
1435 proc tcltest::PrintUsageInfo {} {
1436 puts [Usage]
1437 PrintUsageInfoHook
1438 }
1439
1440 proc tcltest::Usage { {option ""} } {
1441 variable Usage
1442 variable Verify
1443 if {[llength [info level 0]] == 1} {
1444 set msg "Usage: [file tail [info nameofexecutable]] script "
1445 append msg "?-help? ?flag value? ... \n"
1446 append msg "Available flags (and valid input values) are:"
1447
1448 set max 0
1449 set allOpts [concat -help [Configure]]
1450 foreach opt $allOpts {
1451 set foo [Usage $opt]
1452 lassign $foo x type($opt) usage($opt)
1453 set line($opt) " $opt $type($opt) "
1454 set length($opt) [string length $line($opt)]
1455 if {$length($opt) > $max} {set max $length($opt)}
1456 }
1457 set rest [expr {72 - $max}]
1458 foreach opt $allOpts {
1459 append msg \n$line($opt)
1460 append msg [string repeat " " [expr {$max - $length($opt)}]]
1461 set u [string trim $usage($opt)]
1462 catch {append u " (default: \[[Configure $opt]])"}
1463 regsub -all {\s*\n\s*} $u " " u
1464 while {[string length $u] > $rest} {
1465 set break [string wordstart $u $rest]
1466 if {$break == 0} {
1467 set break [string wordend $u 0]
1468 }
1469 append msg [string range $u 0 [expr {$break - 1}]]
1470 set u [string trim [string range $u $break end]]
1471 append msg \n[string repeat " " $max]
1472 }
1473 append msg $u
1474 }
1475 return $msg\n
1476 } elseif {$option eq "-help"} {
1477 return [list -help "" "Display this usage information."]
1478 } else {
1479 set type [lindex [info args $Verify($option)] 0]
1480 return [list $option $type $Usage($option)]
1481 }
1482 }
1483
1484 # tcltest::ProcessFlags --
1485 #
1486 # process command line arguments supplied in the flagArray - this
1487 # is called by processCmdLineArgs. Modifies tcltest variables
1488 # according to the content of the flagArray.
1489 #
1490 # Arguments:
1491 # flagArray - array containing name/value pairs of flags
1492 #
1493 # Results:
1494 # sets tcltest variables according to their values as defined by
1495 # flagArray
1496 #
1497 # Side effects:
1498 # None.
1499
1500 proc tcltest::ProcessFlags {flagArray} {
1501 # Process -help first
1502 if {"-help" in $flagArray} {
1503 PrintUsageInfo
1504 exit 1
1505 }
1506
1507 if {[llength $flagArray] == 0} {
1508 RemoveAutoConfigureTraces
1509 } else {
1510 set args $flagArray
1511 while {[llength $args] > 1 && [catch {configure {*}$args} msg]} {
1512
1513 # Something went wrong parsing $args for tcltest options
1514 # Check whether the problem is "unknown option"
1515 if {[regexp {^unknown option (\S+):} $msg -> option]} {
1516 # Could be this is an option the Hook knows about
1517 set moreOptions [processCmdLineArgsAddFlagsHook]
1518 if {$option ni $moreOptions} {
1519 # Nope. Report the error, including additional options,
1520 # but keep going
1521 if {[llength $moreOptions]} {
1522 append msg ", "
1523 append msg [join [lrange $moreOptions 0 end-1] ", "]
1524 append msg "or [lindex $moreOptions end]"
1525 }
1526 Warn $msg
1527 }
1528 } else {
1529 # error is something other than "unknown option"
1530 # notify user of the error; and exit
1531 puts [errorChannel] $msg
1532 exit 1
1533 }
1534
1535 # To recover, find that unknown option and remove up to it.
1536 # then retry
1537 while {[lindex $args 0] ne $option} {
1538 set args [lrange $args 2 end]
1539 }
1540 set args [lrange $args 2 end]
1541 }
1542 if {[llength $args] == 1} {
1543 puts [errorChannel] \
1544 "missing value for option [lindex $args 0]"
1545 exit 1
1546 }
1547 }
1548
1549 # Call the hook
1550 catch {
1551 array set flag $flagArray
1552 processCmdLineArgsHook [array get flag]
1553 }
1554 return
1555 }
1556
1557 # tcltest::ProcessCmdLineArgs --
1558 #
1559 # This procedure must be run after constraint initialization is
1560 # set up (by [DefineConstraintInitializers]) because some constraints
1561 # can be overridden.
1562 #
1563 # Perform configuration according to the command-line options.
1564 #
1565 # Arguments:
1566 # none
1567 #
1568 # Results:
1569 # Sets the above-named variables in the tcltest namespace.
1570 #
1571 # Side Effects:
1572 # None.
1573 #
1574
1575 proc tcltest::ProcessCmdLineArgs {} {
1576 variable originalEnv
1577 variable testConstraints
1578
1579 # The "argv" var doesn't exist in some cases, so use {}.
1580 if {![info exists ::argv]} {
1581 ProcessFlags {}
1582 } else {
1583 ProcessFlags $::argv
1584 }
1585
1586 # Spit out everything you know if we're at a debug level 2 or
1587 # greater
1588 DebugPuts 2 "Flags passed into tcltest:"
1589 if {[info exists ::env(TCLTEST_OPTIONS)]} {
1590 DebugPuts 2 \
1591 " ::env(TCLTEST_OPTIONS): $::env(TCLTEST_OPTIONS)"
1592 }
1593 if {[info exists ::argv]} {
1594 DebugPuts 2 " argv: $::argv"
1595 }
1596 DebugPuts 2 "tcltest::debug = [debug]"
1597 DebugPuts 2 "tcltest::testsDirectory = [testsDirectory]"
1598 DebugPuts 2 "tcltest::workingDirectory = [workingDirectory]"
1599 DebugPuts 2 "tcltest::temporaryDirectory = [temporaryDirectory]"
1600 DebugPuts 2 "tcltest::outputChannel = [outputChannel]"
1601 DebugPuts 2 "tcltest::errorChannel = [errorChannel]"
1602 DebugPuts 2 "Original environment (tcltest::originalEnv):"
1603 DebugPArray 2 originalEnv
1604 DebugPuts 2 "Constraints:"
1605 DebugPArray 2 testConstraints
1606 }
1607
1608 #####################################################################
1609
1610 # Code to run the tests goes here.
1611
1612 # tcltest::TestPuts --
1613 #
1614 # Used to redefine puts in test environment. Stores whatever goes
1615 # out on stdout in tcltest::outData and stderr in errData before
1616 # sending it on to the regular puts.
1617 #
1618 # Arguments:
1619 # same as standard puts
1620 #
1621 # Results:
1622 # none
1623 #
1624 # Side effects:
1625 # Intercepts puts; data that would otherwise go to stdout, stderr,
1626 # or file channels specified in outputChannel and errorChannel
1627 # does not get sent to the normal puts function.
1628 namespace eval tcltest::Replace {
1629 namespace export puts
1630 }
1631 proc tcltest::Replace::puts {args} {
1632 variable [namespace parent]::outData
1633 variable [namespace parent]::errData
1634 switch [llength $args] {
1635 1 {
1636 # Only the string to be printed is specified
1637 append outData [lindex $args 0]\n
1638 return
1639 # return [Puts [lindex $args 0]]
1640 }
1641 2 {
1642 # Either -nonewline or channel has been specified
1643 if {[lindex $args 0] eq "-nonewline"} {
1644 append outData [lindex $args end]
1645 return
1646 # return [Puts -nonewline [lindex $args end]]
1647 } else {
1648 set channel [lindex $args 0]
1649 set newline \n
1650 }
1651 }
1652 3 {
1653 if {[lindex $args 0] eq "-nonewline"} {
1654 # Both -nonewline and channel are specified, unless
1655 # it's an error. -nonewline is supposed to be argv[0].
1656 set channel [lindex $args 1]
1657 set newline ""
1658 }
1659 }
1660 }
1661
1662 if {[info exists channel]} {
1663 if {$channel in [list [[namespace parent]::outputChannel] stdout]} {
1664 append outData [lindex $args end]$newline
1665 return
1666 } elseif {$channel in [list [[namespace parent]::errorChannel] stderr]} {
1667 append errData [lindex $args end]$newline
1668 return
1669 }
1670 }
1671
1672 # If we haven't returned by now, we don't know how to handle the
1673 # input. Let puts handle it.
1674 return [Puts {*}$args]
1675 }
1676
1677 # tcltest::Eval --
1678 #
1679 # Evaluate the script in the test environment. If ignoreOutput is
1680 # false, store data sent to stderr and stdout in outData and
1681 # errData. Otherwise, ignore this output altogether.
1682 #
1683 # Arguments:
1684 # script Script to evaluate
1685 # ?ignoreOutput? Indicates whether or not to ignore output
1686 # sent to stdout & stderr
1687 #
1688 # Results:
1689 # result from running the script
1690 #
1691 # Side effects:
1692 # Empties the contents of outData and errData before running a
1693 # test if ignoreOutput is set to 0.
1694
1695 proc tcltest::Eval {script {ignoreOutput 1}} {
1696 variable outData
1697 variable errData
1698 DebugPuts 3 "[lindex [info level 0] 0] called"
1699 if {!$ignoreOutput} {
1700 set outData {}
1701 set errData {}
1702 rename ::puts [namespace current]::Replace::Puts
1703 namespace eval :: [list namespace import [namespace origin Replace::puts]]
1704 namespace import Replace::puts
1705 }
1706 set result [uplevel 1 $script]
1707 if {!$ignoreOutput} {
1708 namespace forget puts
1709 namespace eval :: namespace forget puts
1710 rename [namespace current]::Replace::Puts ::puts
1711 }
1712 return $result
1713 }
1714
1715 # tcltest::CompareStrings --
1716 #
1717 # compares the expected answer to the actual answer, depending on
1718 # the mode provided. Mode determines whether a regexp, exact,
1719 # glob or custom comparison is done.
1720 #
1721 # Arguments:
1722 # actual - string containing the actual result
1723 # expected - pattern to be matched against
1724 # mode - type of comparison to be done
1725 #
1726 # Results:
1727 # result of the match
1728 #
1729 # Side effects:
1730 # None.
1731
1732 proc tcltest::CompareStrings {actual expected mode} {
1733 variable CustomMatch
1734 if {![info exists CustomMatch($mode)]} {
1735 return -code error "No matching command registered for `-match $mode'"
1736 }
1737 set match [namespace eval :: $CustomMatch($mode) [list $expected $actual]]
1738 if {[catch {expr {$match && $match}} result]} {
1739 return -code error "Invalid result from `-match $mode' command: $result"
1740 }
1741 return $match
1742 }
1743
1744 # tcltest::customMatch --
1745 #
1746 # registers a command to be called when a particular type of
1747 # matching is required.
1748 #
1749 # Arguments:
1750 # nickname - Keyword for the type of matching
1751 # cmd - Incomplete command that implements that type of matching
1752 # when completed with expected string and actual string
1753 # and then evaluated.
1754 #
1755 # Results:
1756 # None.
1757 #
1758 # Side effects:
1759 # Sets the variable tcltest::CustomMatch
1760
1761 proc tcltest::customMatch {mode script} {
1762 variable CustomMatch
1763 if {![info complete $script]} {
1764 return -code error \
1765 "invalid customMatch script; can't evaluate after completion"
1766 }
1767 set CustomMatch($mode) $script
1768 }
1769
1770 # tcltest::SubstArguments list
1771 #
1772 # This helper function takes in a list of words, then perform a
1773 # substitution on the list as though each word in the list is a separate
1774 # argument to the Tcl function. For example, if this function is
1775 # invoked as:
1776 #
1777 # SubstArguments {$a {$a}}
1778 #
1779 # Then it is as though the function is invoked as:
1780 #
1781 # SubstArguments $a {$a}
1782 #
1783 # This code is adapted from Paul Duffin's function "SplitIntoWords".
1784 # The original function can be found on:
1785 #
1786 # http://purl.org/thecliff/tcl/wiki/858.html
1787 #
1788 # Results:
1789 # a list containing the result of the substitution
1790 #
1791 # Exceptions:
1792 # An error may occur if the list containing unbalanced quote or
1793 # unknown variable.
1794 #
1795 # Side Effects:
1796 # None.
1797 #
1798
1799 proc tcltest::SubstArguments {argList} {
1800
1801 # We need to split the argList up into tokens but cannot use list
1802 # operations as they throw away some significant quoting, and
1803 # [split] ignores braces as it should. Therefore what we do is
1804 # gradually build up a string out of whitespace-separated strings.
1805 # We cannot use [split] to split the argList into whitespace
1806 # separated strings as it throws away the whitespace which maybe
1807 # important so we have to do it all by hand.
1808
1809 set result {}
1810 set token ""
1811
1812 while {[string length $argList]} {
1813 # Look for the next word containing a quote: " { }
1814 if {[regexp -indices {[^ \t\n]*[\"\{\}]+[^ \t\n]*} \
1815 $argList all]} {
1816 # Get the text leading up to this word, but not including
1817 # this word, from the argList.
1818 set text [string range $argList 0 \
1819 [expr {[lindex $all 0] - 1}]]
1820 # Get the word with the quote
1821 set word [string range $argList \
1822 [lindex $all 0] [lindex $all 1]]
1823
1824 # Remove all text up to and including the word from the
1825 # argList.
1826 set argList [string range $argList \
1827 [expr {[lindex $all 1] + 1}] end]
1828 } else {
1829 # Take everything up to the end of the argList.
1830 set text $argList
1831 set word {}
1832 set argList {}
1833 }
1834
1835 if {$token ne {}} {
1836 # If we saw a word with quote before, then there is a
1837 # multi-word token starting with that word. In this case,
1838 # add the text and the current word to this token.
1839 append token $text $word
1840 } else {
1841 # Add the text to the result. There is no need to parse
1842 # the text because it couldn't be a part of any multi-word
1843 # token. Then start a new multi-word token with the word
1844 # because we need to pass this token to the Tcl parser to
1845 # check for balancing quotes
1846 append result $text
1847 set token $word
1848 }
1849
1850 if { [catch {llength $token} length] == 0 && $length == 1} {
1851 # The token is a valid list so add it to the result.
1852 # lappend result [string trim $token]
1853 append result \{$token\}
1854 set token {}
1855 }
1856 }
1857
1858 # If the last token has not been added to the list then there
1859 # is a problem.
1860 if { [string length $token] } {
1861 error "incomplete token \"$token\""
1862 }
1863
1864 return $result
1865 }
1866
1867
1868 # tcltest::test --
1869 #
1870 # This procedure runs a test and prints an error message if the test
1871 # fails. If verbose has been set, it also prints a message even if the
1872 # test succeeds. The test will be skipped if it doesn't match the
1873 # match variable, if it matches an element in skip, or if one of the
1874 # elements of "constraints" turns out not to be true.
1875 #
1876 # If testLevel is 1, then this is a top level test, and we record
1877 # pass/fail information; otherwise, this information is not logged and
1878 # is not added to running totals.
1879 #
1880 # Attributes:
1881 # Only description is a required attribute. All others are optional.
1882 # Default values are indicated.
1883 #
1884 # constraints - A list of one or more keywords, each of which
1885 # must be the name of an element in the array
1886 # "testConstraints". If any of these elements is
1887 # zero, the test is skipped. This attribute is
1888 # optional; default is {}
1889 # body - Script to run to carry out the test. It must
1890 # return a result that can be checked for
1891 # correctness. This attribute is optional;
1892 # default is {}
1893 # result - Expected result from script. This attribute is
1894 # optional; default is {}.
1895 # output - Expected output sent to stdout. This attribute
1896 # is optional; default is {}.
1897 # errorOutput - Expected output sent to stderr. This attribute
1898 # is optional; default is {}.
1899 # returnCodes - Expected return codes. This attribute is
1900 # optional; default is {0 2}.
1901 # errorCode - Expected error code. This attribute is
1902 # optional; default is {*}. It is a glob pattern.
1903 # If given, returnCodes defaults to {1}.
1904 # setup - Code to run before $script (above). This
1905 # attribute is optional; default is {}.
1906 # cleanup - Code to run after $script (above). This
1907 # attribute is optional; default is {}.
1908 # match - specifies type of matching to do on result,
1909 # output, errorOutput; this must be a string
1910 # previously registered by a call to [customMatch].
1911 # The strings exact, glob, and regexp are preregistered
1912 # by the tcltest package. Default value is exact.
1913 #
1914 # Arguments:
1915 # name - Name of test, in the form foo-1.2.
1916 # description - Short textual description of the test, to
1917 # help humans understand what it does.
1918 #
1919 # Results:
1920 # None.
1921 #
1922 # Side effects:
1923 # Just about anything is possible depending on the test.
1924 #
1925
1926 proc tcltest::test {name description args} {
1927 global tcl_platform
1928 variable testLevel
1929 variable coreModTime
1930 variable fullutf
1931
1932 DebugPuts 3 "test $name $args"
1933 DebugDo 1 {
1934 variable TestNames
1935 catch {
1936 puts "test name '$name' re-used; prior use in $TestNames($name)"
1937 }
1938 set TestNames($name) [info script]
1939 }
1940
1941 FillFilesExisted
1942 incr testLevel
1943
1944 # Predefine everything to null except output and errorOutput. We
1945 # determine whether or not to trap output based on whether or not
1946 # these variables (output & errorOutput) are defined.
1947 lassign {} constraints setup cleanup body result returnCodes errorCode match
1948
1949 # Set the default match mode
1950 set match exact
1951
1952 # Set the default match values for return codes (0 is the standard
1953 # expected return value if everything went well; 2 represents
1954 # 'return' being used in the test script).
1955 set returnCodes [list 0 2]
1956
1957 # Set the default error code pattern
1958 set errorCode "*"
1959
1960 # The old test format can't have a 3rd argument (constraints or
1961 # script) that starts with '-'.
1962 if {[string match -* [lindex $args 0]] || ([llength $args] <= 1)} {
1963 if {[llength $args] == 1} {
1964 set list [SubstArguments [lindex $args 0]]
1965 foreach {element value} $list {
1966 set testAttributes($element) $value
1967 }
1968 foreach item {constraints match setup body cleanup \
1969 result returnCodes errorCode output errorOutput} {
1970 if {[info exists testAttributes(-$item)]} {
1971 set testAttributes(-$item) [uplevel 1 \
1972 ::concat $testAttributes(-$item)]
1973 }
1974 }
1975 } else {
1976 array set testAttributes $args
1977 }
1978
1979 set validFlags {-setup -cleanup -body -result -returnCodes \
1980 -errorCode -match -output -errorOutput -constraints}
1981
1982 foreach flag [array names testAttributes] {
1983 if {$flag ni $validFlags} {
1984 incr testLevel -1
1985 set sorted [lsort $validFlags]
1986 set options [join [lrange $sorted 0 end-1] ", "]
1987 append options ", or [lindex $sorted end]"
1988 return -code error "bad option \"$flag\": must be $options"
1989 }
1990 }
1991
1992 # store whatever the user gave us
1993 foreach item [array names testAttributes] {
1994 set [string trimleft $item "-"] $testAttributes($item)
1995 }
1996
1997 # Check the values supplied for -match
1998 variable CustomMatch
1999 if {$match ni [array names CustomMatch]} {
2000 incr testLevel -1
2001 set sorted [lsort [array names CustomMatch]]
2002 set values [join [lrange $sorted 0 end-1] ", "]
2003 append values ", or [lindex $sorted end]"
2004 return -code error "bad -match value \"$match\":\
2005 must be $values"
2006 }
2007
2008 # Replace symbolic valies supplied for -returnCodes
2009 foreach {strcode numcode} {ok 0 normal 0 error 1 return 2 break 3 continue 4} {
2010 set returnCodes [string map -nocase [list $strcode $numcode] $returnCodes]
2011 }
2012 # errorCode without returnCode 1 is meaningless
2013 if {$errorCode ne "*" && 1 ni $returnCodes} {
2014 set returnCodes 1
2015 }
2016 } else {
2017 # This is parsing for the old test command format; it is here
2018 # for backward compatibility.
2019 set result [lindex $args end]
2020 if {[llength $args] == 2} {
2021 set body [lindex $args 0]
2022 } elseif {[llength $args] == 3} {
2023 set constraints [lindex $args 0]
2024 set body [lindex $args 1]
2025 } else {
2026 incr testLevel -1
2027 return -code error "wrong # args:\
2028 should be \"test name desc ?options?\""
2029 }
2030 }
2031
2032 if {[Skipped $name $constraints]} {
2033 incr testLevel -1
2034 return
2035 }
2036
2037 # Save information about the core file.
2038 if {[preserveCore]} {
2039 if {[file exists [file join [workingDirectory] core]]} {
2040 set coreModTime [file mtime [file join [workingDirectory] core]]
2041 }
2042 }
2043
2044 # First, run the setup script (or a hook if it presents):
2045 if {[set cmd [namespace which -command [namespace current]::SetupTest]] ne ""} {
2046 set setup [list $cmd $setup]
2047 }
2048 set processTest 1
2049 set code [catch {uplevel 1 $setup} setupMsg]
2050 if {$code == 1} {
2051 set errorInfo(setup) $::errorInfo
2052 set errorCodeRes(setup) $::errorCode
2053 if {$errorCodeRes(setup) eq "BYPASS-SKIPPED-TEST"} {
2054 _noticeSkipped $name $setupMsg
2055 set processTest [set code 0]
2056 }
2057 }
2058 set setupFailure [expr {$code != 0}]
2059
2060 # Only run the test body if the setup was successful
2061 if {$processTest && !$setupFailure} {
2062
2063 # Register startup time
2064 if {[IsVerbose msec] || [IsVerbose usec]} {
2065 set timeStart [clock microseconds]
2066 }
2067
2068 # Verbose notification of $body start
2069 if {[IsVerbose start]} {
2070 puts [outputChannel] "---- $name start"
2071 flush [outputChannel]
2072 }
2073
2074 set command [list [namespace origin RunTest] $name $body]
2075 if {[info exists output] || [info exists errorOutput]} {
2076 set testResult [uplevel 1 [list [namespace origin Eval] $command 0]]
2077 } else {
2078 set testResult [uplevel 1 [list [namespace origin Eval] $command 1]]
2079 }
2080 lassign $testResult actualAnswer returnCode
2081 if {$returnCode == 1} {
2082 set errorInfo(body) $::errorInfo
2083 set errorCodeRes(body) $::errorCode
2084 if {$errorCodeRes(body) eq "BYPASS-SKIPPED-TEST"} {
2085 _noticeSkipped $name $actualAnswer
2086 set processTest [set returnCode 0]
2087 }
2088 }
2089 }
2090
2091 # check if the return code matched the expected return code
2092 set codeFailure 0
2093 if {$processTest && !$setupFailure && ($returnCode ni $returnCodes)} {
2094 set codeFailure 1
2095 }
2096 set errorCodeFailure 0
2097 if {$processTest && !$setupFailure && !$codeFailure && $returnCode == 1 && \
2098 ![string match $errorCode $errorCodeRes(body)]} {
2099 set errorCodeFailure 1
2100 }
2101
2102 # If expected output/error strings exist, we have to compare
2103 # them. If the comparison fails, then so did the test.
2104 set outputFailure 0
2105 variable outData
2106 if {$processTest && [info exists output] && !$codeFailure} {
2107 if {[set outputCompare [catch {
2108 CompareStrings $outData $output $match
2109 } outputMatch]] == 0} {
2110 set outputFailure [expr {!$outputMatch}]
2111 } else {
2112 set outputFailure 1
2113 }
2114 }
2115
2116 set errorFailure 0
2117 variable errData
2118 if {$processTest && [info exists errorOutput] && !$codeFailure} {
2119 if {[set errorCompare [catch {
2120 CompareStrings $errData $errorOutput $match
2121 } errorMatch]] == 0} {
2122 set errorFailure [expr {!$errorMatch}]
2123 } else {
2124 set errorFailure 1
2125 }
2126 }
2127
2128 # check if the answer matched the expected answer
2129 # Only check if we ran the body of the test (no setup failure)
2130 if {!$processTest} {
2131 set scriptFailure 0
2132 } elseif {$setupFailure || $codeFailure} {
2133 set scriptFailure 0
2134 } elseif {[set scriptCompare [catch {
2135 CompareStrings $actualAnswer $result $match
2136 } scriptMatch]] == 0} {
2137 set scriptFailure [expr {!$scriptMatch}]
2138 } else {
2139 set scriptFailure 1
2140 }
2141
2142 # Always run the cleanup script (or a hook if it presents):
2143 if {[set cmd [namespace which -command [namespace current]::CleanupTest]] ne ""} {
2144 set cleanup [list $cmd $cleanup]
2145 }
2146 set code [catch {uplevel 1 $cleanup} cleanupMsg]
2147 if {$code == 1} {
2148 set errorInfo(cleanup) $::errorInfo
2149 set errorCodeRes(cleanup) $::errorCode
2150 }
2151 set cleanupFailure [expr {$code != 0}]
2152
2153 set coreFailure 0
2154 set coreMsg ""
2155 # check for a core file first - if one was created by the test,
2156 # then the test failed
2157 if {[preserveCore]} {
2158 if {[file exists [file join [workingDirectory] core]]} {
2159 # There's only a test failure if there is a core file
2160 # and (1) there previously wasn't one or (2) the new
2161 # one is different from the old one.
2162 if {[info exists coreModTime]} {
2163 if {$coreModTime != [file mtime \
2164 [file join [workingDirectory] core]]} {
2165 set coreFailure 1
2166 }
2167 } else {
2168 set coreFailure 1
2169 }
2170
2171 if {([preserveCore] > 1) && ($coreFailure)} {
2172 append coreMsg "\nMoving file to:\
2173 [file join [temporaryDirectory] core-$name]"
2174 catch {file rename -force -- \
2175 [file join [workingDirectory] core] \
2176 [file join [temporaryDirectory] core-$name]
2177 } msg
2178 if {$msg ne {}} {
2179 append coreMsg "\nError:\
2180 Problem renaming core file: $msg"
2181 }
2182 }
2183 }
2184 }
2185
2186 if {[IsVerbose msec] || [IsVerbose usec]} {
2187 set t [expr {[clock microseconds] - $timeStart}]
2188 if {[IsVerbose usec]} {
2189 puts [outputChannel] "++++ $name took $t \xB5s"
2190 }
2191 if {[IsVerbose msec]} {
2192 puts [outputChannel] "++++ $name took [expr {round($t/1000.)}] ms"
2193 }
2194 }
2195
2196 # if skipped, it is safe to return here
2197 if {!$processTest} {
2198 incr testLevel -1
2199 return
2200 }
2201
2202 # if we didn't experience any failures, then we passed
2203 variable numTests
2204 if {!($setupFailure || $cleanupFailure || $coreFailure
2205 || $outputFailure || $errorFailure || $codeFailure
2206 || $errorCodeFailure || $scriptFailure)} {
2207 if {$testLevel == 1} {
2208 incr numTests(Passed)
2209 if {[IsVerbose pass]} {
2210 puts [outputChannel] "++++ $name PASSED"
2211 }
2212 }
2213 incr testLevel -1
2214 return
2215 }
2216
2217 # We know the test failed, tally it...
2218 if {$testLevel == 1} {
2219 incr numTests(Failed)
2220 }
2221
2222 # ... then report according to the type of failure
2223 variable currentFailure true
2224 if {![IsVerbose body]} {
2225 set body ""
2226 }
2227 puts [outputChannel] "\n"
2228 if {[IsVerbose line]} {
2229 if {![catch {set testFrame [info frame -1]}] &&
2230 [dict get $testFrame type] eq "source"} {
2231 set testFile [dict get $testFrame file]
2232 set testLine [dict get $testFrame line]
2233 } else {
2234 set testFile [file normalize [uplevel 1 {info script}]]
2235 if {[file readable $testFile]} {
2236 set testFd [open $testFile r]
2237 if {$fullutf} {
2238 fconfigure $testFd -profile tcl8 -encoding utf-8
2239 }
2240 set testLine [expr {[lsearch -regexp \
2241 [split [read $testFd] "\n"] \
2242 "^\[ \t\]*test [string map {. \\.} $name] "] + 1}]
2243 close $testFd
2244 }
2245 }
2246 if {[info exists testLine]} {
2247 puts [outputChannel] "$testFile:$testLine: error: test failed:\
2248 $name [string trim $description]"
2249 }
2250 }
2251 puts [outputChannel] "==== $name\
2252 [string trim $description] FAILED"
2253 if {[string length $body]} {
2254 puts [outputChannel] "==== Contents of test case:"
2255 puts [outputChannel] $body
2256 }
2257 if {$setupFailure} {
2258 puts [outputChannel] "---- Test setup\
2259 failed:\n$setupMsg"
2260 if {[info exists errorInfo(setup)]} {
2261 puts [outputChannel] "---- errorInfo(setup): $errorInfo(setup)"
2262 puts [outputChannel] "---- errorCode(setup): $errorCodeRes(setup)"
2263 }
2264 }
2265 if {$processTest && $scriptFailure} {
2266 if {$scriptCompare} {
2267 puts [outputChannel] "---- Error testing result: $scriptMatch"
2268 } else {
2269 if {[string length $actualAnswer] > 1000} {
2270 set actualAnswer [string cat \
2271 [string range $actualAnswer 0 499] \
2272 "(long output elided)" \
2273 [string range $actualAnswer end-499 end]]
2274 }
2275 if {[string length $result] > 1000} {
2276 set result [string cat \
2277 [string range $result 0 499] \
2278 "(long output elided)" \
2279 [string range $result end-499 end]]
2280 }
2281 if {[catch {
2282 puts [outputChannel] "---- Result was:\n[Asciify $actualAnswer]"
2283 } errMsg]} {
2284 puts [outputChannel] "\n---- Result was:\n<error printing result: $errMsg>"
2285 }
2286 puts [outputChannel] "---- Result should have been\
2287 ($match matching):\n[Asciify $result]"
2288 }
2289 }
2290 if {$errorCodeFailure} {
2291 puts [outputChannel] "---- Error code was: '$errorCodeRes(body)'"
2292 puts [outputChannel] "---- Error code should have been: '$errorCode'"
2293 }
2294 if {$codeFailure} {
2295 switch -- $returnCode {
2296 0 { set msg "Test completed normally" }
2297 1 { set msg "Test generated error" }
2298 2 { set msg "Test generated return exception" }
2299 3 { set msg "Test generated break exception" }
2300 4 { set msg "Test generated continue exception" }
2301 default { set msg "Test generated exception" }
2302 }
2303 puts [outputChannel] "---- $msg; Return code was: $returnCode"
2304 puts [outputChannel] "---- Return code should have been\
2305 one of: $returnCodes"
2306 if {[IsVerbose error]} {
2307 if {[info exists errorInfo(body)] && (1 ni $returnCodes)} {
2308 puts [outputChannel] "---- errorInfo: $errorInfo(body)"
2309 puts [outputChannel] "---- errorCode: $errorCodeRes(body)"
2310 }
2311 }
2312 }
2313 if {$outputFailure} {
2314 if {$outputCompare} {
2315 puts [outputChannel] "---- Error testing output: $outputMatch"
2316 } else {
2317 puts [outputChannel] "---- Output was:\n$outData"
2318 puts [outputChannel] "---- Output should have been\
2319 ($match matching):\n$output"
2320 }
2321 }
2322 if {$errorFailure} {
2323 if {$errorCompare} {
2324 puts [outputChannel] "---- Error testing errorOutput: $errorMatch"
2325 } else {
2326 puts [outputChannel] "---- Error output was:\n$errData"
2327 puts [outputChannel] "---- Error output should have\
2328 been ($match matching):\n$errorOutput"
2329 }
2330 }
2331 if {$cleanupFailure} {
2332 puts [outputChannel] "---- Test cleanup failed:\n$cleanupMsg"
2333 if {[info exists errorInfo(cleanup)]} {
2334 puts [outputChannel] "---- errorInfo(cleanup): $errorInfo(cleanup)"
2335 puts [outputChannel] "---- errorCode(cleanup): $errorCodeRes(cleanup)"
2336 }
2337 }
2338 if {$coreFailure} {
2339 puts [outputChannel] "---- Core file produced while running\
2340 test! $coreMsg"
2341 }
2342 puts [outputChannel] "==== $name FAILED\n"
2343
2344 incr testLevel -1
2345 return
2346 }
2347
2348 # Skip --
2349 #
2350 # Skips a running test and add a reason to skipped "constraints". Can be used
2351 # to conditional intended abort of the test.
2352 #
2353 # Side Effects: Maintains tally of total tests seen and tests skipped.
2354 #
2355 proc tcltest::Skip {reason} {
2356 return -code error -errorcode BYPASS-SKIPPED-TEST $reason
2357 }
2358
2359 proc tcltest::_noticeSkipped {name reason} {
2360 variable testLevel
2361 variable numTests
2362
2363 if {[IsVerbose skip]} {
2364 puts [outputChannel] "++++ $name SKIPPED: $reason"
2365 }
2366
2367 if {$testLevel == 1} {
2368 incr numTests(Skipped)
2369 AddToSkippedBecause $reason
2370 }
2371 }
2372
2373
2374 # Skipped --
2375 #
2376 # Given a test name and it constraints, returns a boolean indicating
2377 # whether the current configuration says the test should be skipped.
2378 #
2379 # Side Effects: Maintains tally of total tests seen and tests skipped.
2380 #
2381 proc tcltest::Skipped {name constraints} {
2382 variable testLevel
2383 variable numTests
2384 variable testConstraints
2385
2386 if {$testLevel == 1} {
2387 incr numTests(Total)
2388 }
2389 # skip the test if it's name matches an element of skip
2390 foreach pattern [skip] {
2391 if {[string match $pattern $name]} {
2392 if {$testLevel == 1} {
2393 incr numTests(Skipped)
2394 DebugDo 1 {AddToSkippedBecause userSpecifiedSkip}
2395 }
2396 return 1
2397 }
2398 }
2399 # skip the test if it's name doesn't match any element of match
2400 set ok 0
2401 foreach pattern [match] {
2402 if {[string match $pattern $name]} {
2403 set ok 1
2404 break
2405 }
2406 }
2407 if {!$ok} {
2408 if {$testLevel == 1} {
2409 incr numTests(Skipped)
2410 DebugDo 1 {AddToSkippedBecause userSpecifiedNonMatch}
2411 }
2412 return 1
2413 }
2414 if {$constraints eq {}} {
2415 # If we're limited to the listed constraints and there aren't
2416 # any listed, then we shouldn't run the test.
2417 if {[limitConstraints]} {
2418 AddToSkippedBecause userSpecifiedLimitConstraint
2419 if {$testLevel == 1} {
2420 incr numTests(Skipped)
2421 }
2422 return 1
2423 }
2424 } else {
2425 # "constraints" argument exists;
2426 # make sure that the constraints are satisfied.
2427
2428 set doTest 0
2429 set constraints [string trim $constraints]
2430 if {[string match {*[$\[]*} $constraints] != 0} {
2431 # full expression, e.g. {$foo > [info tclversion]}
2432 catch {set doTest [uplevel #0 [list expr $constraints]]}
2433 } elseif {[regexp {[^.:_a-zA-Z0-9 \n\r\t]+} $constraints] != 0} {
2434 # something like {a || b} should be turned into
2435 # $testConstraints(a) || $testConstraints(b).
2436 regsub -all {[.\w]+} $constraints {$testConstraints(&)} c
2437 catch {set doTest [eval [list expr $c]]}
2438 } elseif {![catch {llength $constraints}]} {
2439 # just simple constraints such as {unixOnly fonts}.
2440 set doTest 1
2441 foreach constraint $constraints {
2442 if {(![info exists testConstraints($constraint)]) \
2443 || (!$testConstraints($constraint))} {
2444 set doTest 0
2445
2446 # store the constraint that kept the test from
2447 # running
2448 set constraints $constraint
2449 break
2450 }
2451 }
2452 }
2453
2454 if {!$doTest} {
2455 _noticeSkipped $name $constraints
2456 return 1
2457 }
2458 }
2459 return 0
2460 }
2461
2462 # RunTest --
2463 #
2464 # This is where the body of a test is evaluated. The combination of
2465 # [RunTest] and [Eval] allows the output and error output of the test
2466 # body to be captured for comparison against the expected values.
2467
2468 proc tcltest::RunTest {name script} {
2469 DebugPuts 3 "Running $name {$script}"
2470
2471 # If there is no "memory" command (because memory debugging isn't
2472 # enabled), then don't attempt to use the command.
2473
2474 if {[llength [info commands memory]] == 1} {
2475 memory tag $name
2476 }
2477
2478 # run the test script (or a hook if it presents):
2479 if {[set cmd [namespace which -command [namespace current]::EvalTest]] ne ""} {
2480 set script [list $cmd $script]
2481 }
2482 set code [catch {uplevel 1 $script} actualAnswer]
2483
2484 return [list $actualAnswer $code]
2485 }
2486
2487 #####################################################################
2488
2489 # tcltest::cleanupTestsHook --
2490 #
2491 # This hook allows a harness that builds upon tcltest to specify
2492 # additional things that should be done at cleanup.
2493 #
2494
2495 if {[llength [info commands tcltest::cleanupTestsHook]] == 0} {
2496 proc tcltest::cleanupTestsHook {} {}
2497 }
2498
2499 # tcltest::cleanupTests --
2500 #
2501 # Remove files and dirs created using the makeFile and makeDirectory
2502 # commands since the last time this proc was invoked.
2503 #
2504 # Print the names of the files created without the makeFile command
2505 # since the tests were invoked.
2506 #
2507 # Print the number tests (total, passed, failed, and skipped) since the
2508 # tests were invoked.
2509 #
2510 # Restore original environment (as reported by special variable env).
2511 #
2512 # Arguments:
2513 # calledFromAllFile - if 0, behave as if we are running a single
2514 # test file within an entire suite of tests. if we aren't running
2515 # a single test file, then don't report status. check for new
2516 # files created during the test run and report on them. if 1,
2517 # report collated status from all the test file runs.
2518 #
2519 # Results:
2520 # None.
2521 #
2522 # Side Effects:
2523 # None
2524 #
2525
2526 proc tcltest::cleanupTests {{calledFromAllFile 0}} {
2527 variable filesMade
2528 variable filesExisted
2529 variable createdNewFiles
2530 variable testSingleFile
2531 variable numTests
2532 variable numTestFiles
2533 variable failFiles
2534 variable skippedBecause
2535 variable currentFailure
2536 variable originalEnv
2537 variable originalTclPlatform
2538 variable coreModTime
2539
2540 FillFilesExisted
2541 set testFileName [file tail [info script]]
2542
2543 # Hook to handle reporting to a parent interpreter
2544 if {[llength [info commands [namespace current]::ReportToParent]]} {
2545 ReportToParent $numTests(Total) $numTests(Passed) $numTests(Skipped) \
2546 $numTests(Failed) [array get skippedBecause] \
2547 [array get createdNewFiles]
2548 set testSingleFile false
2549 }
2550
2551 # Call the cleanup hook
2552 cleanupTestsHook
2553
2554 # Remove files and directories created by the makeFile and
2555 # makeDirectory procedures. Record the names of files in
2556 # workingDirectory that were not preexisting, and associate them
2557 # with the test file that created them.
2558
2559 if {!$calledFromAllFile} {
2560 foreach file $filesMade {
2561 if {[file exists $file]} {
2562 DebugDo 1 {Warn "cleanupTests deleting $file..."}
2563 catch {file delete -force -- $file}
2564 }
2565 }
2566 set currentFiles {}
2567 foreach file [glob -nocomplain \
2568 -directory [temporaryDirectory] *] {
2569 lappend currentFiles [file tail $file]
2570 }
2571 set newFiles {}
2572 foreach file $currentFiles {
2573 if {$file ni $filesExisted} {
2574 lappend newFiles $file
2575 }
2576 }
2577 set filesExisted $currentFiles
2578 if {[llength $newFiles] > 0} {
2579 set createdNewFiles($testFileName) $newFiles
2580 }
2581 }
2582
2583 if {$calledFromAllFile || $testSingleFile} {
2584
2585 # print stats
2586
2587 puts -nonewline [outputChannel] "$testFileName:"
2588 foreach index [list "Total" "Passed" "Skipped" "Failed"] {
2589 puts -nonewline [outputChannel] \
2590 "\t$index\t$numTests($index)"
2591 }
2592 puts [outputChannel] ""
2593
2594 # print number test files sourced
2595 # print names of files that ran tests which failed
2596
2597 if {$calledFromAllFile} {
2598 puts [outputChannel] \
2599 "Sourced $numTestFiles Test Files."
2600 set numTestFiles 0
2601 if {[llength $failFiles] > 0} {
2602 puts [outputChannel] \
2603 "Files with failing tests: $failFiles"
2604 set failFiles {}
2605 }
2606 }
2607
2608 # if any tests were skipped, print the constraints that kept
2609 # them from running.
2610
2611 set constraintList [array names skippedBecause]
2612 if {[llength $constraintList] > 0} {
2613 puts [outputChannel] \
2614 "Number of tests skipped for each constraint:"
2615 foreach constraint [lsort $constraintList] {
2616 puts [outputChannel] \
2617 "\t$skippedBecause($constraint)\t$constraint"
2618 unset skippedBecause($constraint)
2619 }
2620 }
2621
2622 # report the names of test files in createdNewFiles, and reset
2623 # the array to be empty.
2624
2625 set testFilesThatTurded [lsort [array names createdNewFiles]]
2626 if {[llength $testFilesThatTurded] > 0} {
2627 puts [outputChannel] "Warning: files left behind:"
2628 foreach testFile $testFilesThatTurded {
2629 puts [outputChannel] \
2630 "\t$testFile:\t$createdNewFiles($testFile)"
2631 unset createdNewFiles($testFile)
2632 }
2633 }
2634
2635 # reset filesMade, filesExisted, and numTests
2636
2637 set filesMade {}
2638 foreach index [list "Total" "Passed" "Skipped" "Failed"] {
2639 set numTests($index) 0
2640 }
2641
2642 # exit only if running Tk in non-interactive mode
2643 # This should be changed to determine if an event
2644 # loop is running, which is the real issue.
2645 # Actually, this doesn't belong here at all. A package
2646 # really has no business [exit]-ing an application.
2647 if {[info exists ::tk_version] && ![testConstraint interactive]} {
2648 exit
2649 }
2650 } else {
2651
2652 # if we're deferring stat-reporting until all files are sourced,
2653 # then add current file to failFile list if any tests in this
2654 # file failed
2655
2656 if {$currentFailure && ($testFileName ni $failFiles)} {
2657 lappend failFiles $testFileName
2658 }
2659 set currentFailure false
2660
2661 # restore the environment to the state it was in before this package
2662 # was loaded
2663
2664 set newEnv {}
2665 set changedEnv {}
2666 set removedEnv {}
2667 foreach index [array names ::env] {
2668 if {![info exists originalEnv($index)]} {
2669 lappend newEnv $index
2670 unset ::env($index)
2671 }
2672 }
2673 foreach index [array names originalEnv] {
2674 if {![info exists ::env($index)]} {
2675 lappend removedEnv $index
2676 set ::env($index) $originalEnv($index)
2677 } elseif {$::env($index) ne $originalEnv($index)} {
2678 lappend changedEnv $index
2679 set ::env($index) $originalEnv($index)
2680 }
2681 }
2682 if {[llength $newEnv] > 0} {
2683 puts [outputChannel] \
2684 "env array elements created:\t$newEnv"
2685 }
2686 if {[llength $changedEnv] > 0} {
2687 puts [outputChannel] \
2688 "env array elements changed:\t$changedEnv"
2689 }
2690 if {[llength $removedEnv] > 0} {
2691 puts [outputChannel] \
2692 "env array elements removed:\t$removedEnv"
2693 }
2694
2695 set changedTclPlatform {}
2696 foreach index [array names originalTclPlatform] {
2697 if {$::tcl_platform($index) \
2698 != $originalTclPlatform($index)} {
2699 lappend changedTclPlatform $index
2700 set ::tcl_platform($index) $originalTclPlatform($index)
2701 }
2702 }
2703 if {[llength $changedTclPlatform] > 0} {
2704 puts [outputChannel] "tcl_platform array elements\
2705 changed:\t$changedTclPlatform"
2706 }
2707
2708 if {[file exists [file join [workingDirectory] core]]} {
2709 if {[preserveCore] > 1} {
2710 puts "rename core file (> 1)"
2711 puts [outputChannel] "produced core file! \
2712 Moving file to: \
2713 [file join [temporaryDirectory] core-$testFileName]"
2714 catch {file rename -force -- \
2715 [file join [workingDirectory] core] \
2716 [file join [temporaryDirectory] core-$testFileName]
2717 } msg
2718 if {$msg ne {}} {
2719 PrintError "Problem renaming file: $msg"
2720 }
2721 } else {
2722 # Print a message if there is a core file and (1) there
2723 # previously wasn't one or (2) the new one is different
2724 # from the old one.
2725
2726 if {[info exists coreModTime]} {
2727 if {$coreModTime != [file mtime \
2728 [file join [workingDirectory] core]]} {
2729 puts [outputChannel] "A core file was created!"
2730 }
2731 } else {
2732 puts [outputChannel] "A core file was created!"
2733 }
2734 }
2735 }
2736 }
2737 flush [outputChannel]
2738 flush [errorChannel]
2739 return
2740 }
2741
2742 #####################################################################
2743
2744 # Procs that determine which tests/test files to run
2745
2746 # tcltest::GetMatchingFiles
2747 #
2748 # Looks at the patterns given to match and skip files and uses
2749 # them to put together a list of the tests that will be run.
2750 #
2751 # Arguments:
2752 # directory to search
2753 #
2754 # Results:
2755 # The constructed list is returned to the user. This will
2756 # primarily be used in 'all.tcl' files. It is used in
2757 # runAllTests.
2758 #
2759 # Side Effects:
2760 # None
2761
2762 # a lower case version is needed for compatibility with tcltest 1.0
2763 proc tcltest::getMatchingFiles args {GetMatchingFiles {*}$args}
2764
2765 proc tcltest::GetMatchingFiles { args } {
2766 if {[llength $args]} {
2767 set dirList $args
2768 } else {
2769 # Finding tests only in [testsDirectory] is normal operation.
2770 # This procedure is written to accept multiple directory arguments
2771 # only to satisfy version 1 compatibility.
2772 set dirList [list [testsDirectory]]
2773 }
2774
2775 set matchingFiles [list]
2776 foreach directory $dirList {
2777
2778 # List files in $directory that match patterns to run.
2779 set matchFileList [list]
2780 foreach match [matchFiles] {
2781 set matchFileList [concat $matchFileList \
2782 [glob -directory $directory -types {b c f p s} \
2783 -nocomplain -- $match]]
2784 }
2785
2786 # List files in $directory that match patterns to skip.
2787 set skipFileList [list]
2788 foreach skip [skipFiles] {
2789 set skipFileList [concat $skipFileList \
2790 [glob -directory $directory -types {b c f p s} \
2791 -nocomplain -- $skip]]
2792 }
2793
2794 # Add to result list all files in match list and not in skip list
2795 foreach file $matchFileList {
2796 if {$file ni $skipFileList} {
2797 lappend matchingFiles $file
2798 }
2799 }
2800 }
2801
2802 if {[llength $matchingFiles] == 0} {
2803 PrintError "No test files remain after applying your match and\
2804 skip patterns!"
2805 }
2806 return $matchingFiles
2807 }
2808
2809 # tcltest::GetMatchingDirectories --
2810 #
2811 # Looks at the patterns given to match and skip directories and
2812 # uses them to put together a list of the test directories that we
2813 # should attempt to run. (Only subdirectories containing an
2814 # "all.tcl" file are put into the list.)
2815 #
2816 # Arguments:
2817 # root directory from which to search
2818 #
2819 # Results:
2820 # The constructed list is returned to the user. This is used in
2821 # the primary all.tcl file.
2822 #
2823 # Side Effects:
2824 # None.
2825
2826 proc tcltest::GetMatchingDirectories {rootdir} {
2827
2828 # Determine the skip list first, to avoid [glob]-ing over subdirectories
2829 # we're going to throw away anyway. Be sure we skip the $rootdir if it
2830 # comes up to avoid infinite loops.
2831 set skipDirs [list $rootdir]
2832 foreach pattern [skipDirectories] {
2833 set skipDirs [concat $skipDirs [glob -directory $rootdir -types d \
2834 -nocomplain -- $pattern]]
2835 }
2836
2837 # Now step through the matching directories, prune out the skipped ones
2838 # as you go.
2839 set matchDirs [list]
2840 foreach pattern [matchDirectories] {
2841 foreach path [glob -directory $rootdir -types d -nocomplain -- \
2842 $pattern] {
2843 if {$path ni $skipDirs && [file readable $path]} {
2844 set matchDirs [concat $matchDirs [GetMatchingDirectories $path]]
2845 if {[file exists [file join $path all.tcl]]} {
2846 lappend matchDirs $path
2847 }
2848 }
2849 }
2850 }
2851
2852 if {[llength $matchDirs] == 0} {
2853 DebugPuts 1 "No test directories remain after applying match\
2854 and skip patterns!"
2855 }
2856 return [lsort $matchDirs]
2857 }
2858
2859 # tcltest::runAllTests --
2860 #
2861 # prints output and sources test files according to the match and
2862 # skip patterns provided. after sourcing test files, it goes on
2863 # to source all.tcl files in matching test subdirectories.
2864 #
2865 # Arguments:
2866 # shell being tested
2867 #
2868 # Results:
2869 # Whether there were any failures.
2870 #
2871 # Side effects:
2872 # None.
2873
2874 proc tcltest::runAllTests { {shell ""} } {
2875 variable testSingleFile
2876 variable numTestFiles
2877 variable numTests
2878 variable failFiles
2879 variable DefaultValue
2880 variable fullutf
2881
2882 FillFilesExisted
2883 if {[llength [info level 0]] == 1} {
2884 set shell [interpreter]
2885 }
2886
2887 set testSingleFile false
2888
2889 puts [outputChannel] "Tests running in interp: $shell"
2890 puts [outputChannel] "Tests located in: [testsDirectory]"
2891 puts [outputChannel] "Tests running in: [workingDirectory]"
2892 puts [outputChannel] "Temporary files stored in\
2893 [temporaryDirectory]"
2894
2895 # [file system] first available in Tcl 8.4
2896 if {![catch {file system [testsDirectory]} result]
2897 && ([lindex $result 0] ne "native")} {
2898 # If we aren't running in the native filesystem, then we must
2899 # run the tests in a single process (via 'source'), because
2900 # trying to run then via a pipe will fail since the files don't
2901 # really exist.
2902 singleProcess 1
2903 }
2904
2905 if {[singleProcess]} {
2906 puts [outputChannel] \
2907 "Test files sourced into current interpreter"
2908 } else {
2909 puts [outputChannel] \
2910 "Test files run in separate interpreters"
2911 }
2912 if {[llength [skip]] > 0} {
2913 puts [outputChannel] "Skipping tests that match: [skip]"
2914 }
2915 puts [outputChannel] "Running tests that match: [match]"
2916
2917 if {[llength [skipFiles]] > 0} {
2918 puts [outputChannel] \
2919 "Skipping test files that match: [skipFiles]"
2920 }
2921 if {[llength [matchFiles]] > 0} {
2922 puts [outputChannel] \
2923 "Only running test files that match: [matchFiles]"
2924 }
2925
2926 set timeCmd {clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S %Z" -locale en}
2927 puts [outputChannel] "Tests began at [eval $timeCmd]"
2928
2929 # Run each of the specified tests
2930 foreach file [lsort [GetMatchingFiles]] {
2931 set tail [file tail $file]
2932 puts [outputChannel] $tail
2933 flush [outputChannel]
2934
2935 if {[singleProcess]} {
2936 if {[catch {
2937 incr numTestFiles
2938 uplevel 1 [list ::source -encoding utf-8 $file]
2939 } msg]} {
2940 puts [outputChannel] "Test file error: $msg"
2941 # append the name of the test to a list to be reported
2942 # later
2943 lappend testFileFailures $file
2944 }
2945 if {$numTests(Failed) > 0} {
2946 set failFilesSet 1
2947 }
2948 } else {
2949 # Pass along our configuration to the child processes.
2950 # EXCEPT for the -outfile, because the parent process
2951 # needs to read and process output of children.
2952 set childargv [list]
2953 foreach opt [Configure] {
2954 if {$opt eq "-outfile"} {continue}
2955 set value [Configure $opt]
2956 # Don't bother passing default configuration options
2957 if {$value eq $DefaultValue($opt)} {
2958 continue
2959 }
2960 lappend childargv $opt $value
2961 }
2962 set cmd [linsert $childargv 0 | $shell $file]
2963 if {[catch {
2964 incr numTestFiles
2965 set pipeFd [open $cmd "r"]
2966 if {$fullutf} {
2967 fconfigure $pipeFd -profile tcl8 -encoding utf-8
2968 }
2969 while {[gets $pipeFd line] >= 0} {
2970 if {[regexp [join {
2971 {^([^:]+):\t}
2972 {Total\t([0-9]+)\t}
2973 {Passed\t([0-9]+)\t}
2974 {Skipped\t([0-9]+)\t}
2975 {Failed\t([0-9]+)}
2976 } ""] $line null testFile \
2977 Total Passed Skipped Failed]} {
2978 foreach index {Total Passed Skipped Failed} {
2979 incr numTests($index) [set $index]
2980 }
2981 if {$Failed > 0} {
2982 lappend failFiles $testFile
2983 set failFilesSet 1
2984 }
2985 } elseif {[regexp [join {
2986 {^Number of tests skipped }
2987 {for each constraint:}
2988 {|^\t(\d+)\t(.+)$}
2989 } ""] $line match skipped constraint]} {
2990 if {[string match \t* $match]} {
2991 AddToSkippedBecause $constraint $skipped
2992 }
2993 } else {
2994 puts [outputChannel] $line
2995 }
2996 }
2997 close $pipeFd
2998 } msg]} {
2999 puts [outputChannel] "Test file error: $msg"
3000 # append the name of the test to a list to be reported
3001 # later
3002 lappend testFileFailures $file
3003 }
3004 }
3005 }
3006
3007 # cleanup
3008 puts [outputChannel] "\nTests ended at [eval $timeCmd]"
3009 cleanupTests 1
3010 if {[info exists testFileFailures]} {
3011 puts [outputChannel] "\nTest files exiting with errors: \n"
3012 foreach file $testFileFailures {
3013 puts [outputChannel] " [file tail $file]\n"
3014 }
3015 }
3016
3017 # Checking for subdirectories in which to run tests
3018 foreach directory [GetMatchingDirectories [testsDirectory]] {
3019 set dir [file tail $directory]
3020 puts [outputChannel] [string repeat ~ 44]
3021 puts [outputChannel] "$dir test began at [eval $timeCmd]\n"
3022
3023 uplevel 1 [list ::source -encoding utf-8 [file join $directory all.tcl]]
3024
3025 set endTime [eval $timeCmd]
3026 puts [outputChannel] "\n$dir test ended at $endTime"
3027 puts [outputChannel] ""
3028 puts [outputChannel] [string repeat ~ 44]
3029 }
3030 return [expr {[info exists testFileFailures] || [info exists failFilesSet]}]
3031 }
3032
3033 #####################################################################
3034
3035 # Test utility procs - not used in tcltest, but may be useful for
3036 # testing.
3037
3038 # tcltest::loadTestedCommands --
3039 #
3040 # Uses the specified script to load the commands to test. Allowed to
3041 # be empty, as the tested commands could have been compiled into the
3042 # interpreter.
3043 #
3044 # Arguments
3045 # none
3046 #
3047 # Results
3048 # none
3049 #
3050 # Side Effects:
3051 # none.
3052
3053 proc tcltest::loadTestedCommands {} {
3054 return [uplevel 1 [loadScript]]
3055 }
3056
3057 # tcltest::saveState --
3058 #
3059 # Save information regarding what procs and variables exist.
3060 #
3061 # Arguments:
3062 # none
3063 #
3064 # Results:
3065 # Modifies the variable saveState
3066 #
3067 # Side effects:
3068 # None.
3069
3070 proc tcltest::saveState {} {
3071 variable saveState
3072 uplevel 1 [list ::set [namespace which -variable saveState]] \
3073 {[::list [::info procs] [::info vars]]}
3074 DebugPuts 2 "[lindex [info level 0] 0]: $saveState"
3075 return
3076 }
3077
3078 # tcltest::restoreState --
3079 #
3080 # Remove procs and variables that didn't exist before the call to
3081 # [saveState].
3082 #
3083 # Arguments:
3084 # none
3085 #
3086 # Results:
3087 # Removes procs and variables from your environment if they don't
3088 # exist in the saveState variable.
3089 #
3090 # Side effects:
3091 # None.
3092
3093 proc tcltest::restoreState {} {
3094 variable saveState
3095 foreach p [uplevel 1 {::info procs}] {
3096 if {($p ni [lindex $saveState 0]) && ("[namespace current]::$p" ne
3097 [uplevel 1 [list ::namespace origin $p]])} {
3098
3099 DebugPuts 2 "[lindex [info level 0] 0]: Removing proc $p"
3100 uplevel 1 [list ::catch [list ::rename $p {}]]
3101 }
3102 }
3103 foreach p [uplevel 1 {::info vars}] {
3104 if {$p ni [lindex $saveState 1]} {
3105 DebugPuts 2 "[lindex [info level 0] 0]:\
3106 Removing variable $p"
3107 uplevel 1 [list ::catch [list ::unset $p]]
3108 }
3109 }
3110 return
3111 }
3112
3113 # tcltest::normalizeMsg --
3114 #
3115 # Removes "extra" newlines from a string.
3116 #
3117 # Arguments:
3118 # msg String to be modified
3119 #
3120 # Results:
3121 # string with extra newlines removed
3122 #
3123 # Side effects:
3124 # None.
3125
3126 proc tcltest::normalizeMsg {msg} {
3127 regsub "\n$" [string tolower $msg] "" msg
3128 set msg [string map [list "\n\n" "\n"] $msg]
3129 return [string map [list "\n\}" "\}"] $msg]
3130 }
3131
3132 # tcltest::makeFile --
3133 #
3134 # Create a new file with the name <name>, and write <contents> to it.
3135 #
3136 # If this file hasn't been created via makeFile since the last time
3137 # cleanupTests was called, add it to the $filesMade list, so it will be
3138 # removed by the next call to cleanupTests.
3139 #
3140 # Arguments:
3141 # contents content of the new file
3142 # name name of the new file
3143 # directory directory name for new file
3144 #
3145 # Results:
3146 # absolute path to the file created
3147 #
3148 # Side effects:
3149 # None.
3150
3151 proc tcltest::makeFile {contents name {directory ""}} {
3152 variable filesMade
3153 variable fullutf
3154
3155 FillFilesExisted
3156
3157 if {[llength [info level 0]] == 3} {
3158 set directory [temporaryDirectory]
3159 }
3160
3161 set fullName [file join $directory $name]
3162
3163 DebugPuts 3 "[lindex [info level 0] 0]:\
3164 putting ``$contents'' into $fullName"
3165
3166 set fd [open $fullName w]
3167 fconfigure $fd -translation lf
3168 if {$fullutf} {
3169 fconfigure $fd -profile tcl8 -encoding utf-8
3170 }
3171 if {[string index $contents end] eq "\n"} {
3172 puts -nonewline $fd $contents
3173 } else {
3174 puts $fd $contents
3175 }
3176 close $fd
3177
3178 if {$fullName ni $filesMade} {
3179 lappend filesMade $fullName
3180 }
3181 return $fullName
3182 }
3183
3184 # tcltest::removeFile --
3185 #
3186 # Removes the named file from the filesystem
3187 #
3188 # Arguments:
3189 # name file to be removed
3190 # directory directory from which to remove file
3191 #
3192 # Results:
3193 # return value from [file delete]
3194 #
3195 # Side effects:
3196 # None.
3197
3198 proc tcltest::removeFile {name {directory ""}} {
3199 variable filesMade
3200 FillFilesExisted
3201 if {[llength [info level 0]] == 2} {
3202 set directory [temporaryDirectory]
3203 }
3204 set fullName [file join $directory $name]
3205 DebugPuts 3 "[lindex [info level 0] 0]: removing $fullName"
3206 set idx [lsearch -exact $filesMade $fullName]
3207 if {$idx < 0} {
3208 DebugDo 1 {
3209 Warn "removeFile removing \"$fullName\":\n not created by makeFile"
3210 }
3211 } else {
3212 set filesMade [lreplace $filesMade $idx $idx]
3213 }
3214 if {![file isfile $fullName]} {
3215 DebugDo 1 {
3216 Warn "removeFile removing \"$fullName\":\n not a file"
3217 }
3218 }
3219 if {[catch {file delete -- $fullName} msg ]} {
3220 DebugDo 1 {
3221 Warn "removeFile removing \"$fullName\":\n failed: $msg"
3222 }
3223 }
3224 return
3225 }
3226
3227 # tcltest::makeDirectory --
3228 #
3229 # Create a new dir with the name <name>.
3230 #
3231 # If this dir hasn't been created via makeDirectory since the last time
3232 # cleanupTests was called, add it to the $directoriesMade list, so it
3233 # will be removed by the next call to cleanupTests.
3234 #
3235 # Arguments:
3236 # name name of the new directory
3237 # directory directory in which to create new dir
3238 #
3239 # Results:
3240 # absolute path to the directory created
3241 #
3242 # Side effects:
3243 # None.
3244
3245 proc tcltest::makeDirectory {name {directory ""}} {
3246 variable filesMade
3247 FillFilesExisted
3248 if {[llength [info level 0]] == 2} {
3249 set directory [temporaryDirectory]
3250 }
3251 set fullName [file join $directory $name]
3252 DebugPuts 3 "[lindex [info level 0] 0]: creating $fullName"
3253 file mkdir $fullName
3254 if {$fullName ni $filesMade} {
3255 lappend filesMade $fullName
3256 }
3257 return $fullName
3258 }
3259
3260 # tcltest::removeDirectory --
3261 #
3262 # Removes a named directory from the file system.
3263 #
3264 # Arguments:
3265 # name Name of the directory to remove
3266 # directory Directory from which to remove
3267 #
3268 # Results:
3269 # return value from [file delete]
3270 #
3271 # Side effects:
3272 # None
3273
3274 proc tcltest::removeDirectory {name {directory ""}} {
3275 variable filesMade
3276 FillFilesExisted
3277 if {[llength [info level 0]] == 2} {
3278 set directory [temporaryDirectory]
3279 }
3280 set fullName [file join $directory $name]
3281 DebugPuts 3 "[lindex [info level 0] 0]: deleting $fullName"
3282 set idx [lsearch -exact $filesMade $fullName]
3283 set filesMade [lreplace $filesMade $idx $idx]
3284 if {$idx < 0} {
3285 DebugDo 1 {
3286 Warn "removeDirectory removing \"$fullName\":\n not created\
3287 by makeDirectory"
3288 }
3289 }
3290 if {![file isdirectory $fullName]} {
3291 DebugDo 1 {
3292 Warn "removeDirectory removing \"$fullName\":\n not a directory"
3293 }
3294 }
3295 return [file delete -force -- $fullName]
3296 }
3297
3298 # tcltest::viewFile --
3299 #
3300 # reads the content of a file and returns it
3301 #
3302 # Arguments:
3303 # name of the file to read
3304 # directory in which file is located
3305 #
3306 # Results:
3307 # content of the named file
3308 #
3309 # Side effects:
3310 # None.
3311
3312 proc tcltest::viewFile {name {directory ""}} {
3313 variable fullutf
3314
3315 FillFilesExisted
3316 if {[llength [info level 0]] == 2} {
3317 set directory [temporaryDirectory]
3318 }
3319 set fullName [file join $directory $name]
3320 set f [open $fullName]
3321 if {$fullutf} {
3322 fconfigure $f -profile tcl8 -encoding utf-8
3323 }
3324 set data [read -nonewline $f]
3325 close $f
3326 return $data
3327 }
3328
3329 # tcltest::bytestring --
3330 #
3331 # Construct a string that consists of the requested sequence of bytes,
3332 # as opposed to a string of properly formed UTF-8 characters.
3333 # This allows the tester to
3334 # 1. Create denormalized or improperly formed strings to pass to C
3335 # procedures that are supposed to accept strings with embedded NULL
3336 # bytes.
3337 # 2. Confirm that a string result has a certain pattern of bytes, for
3338 # instance to confirm that "\xE0\0" in a Tcl script is stored
3339 # internally in UTF-8 as the sequence of bytes "\xC3\xA0\xC0\x80".
3340 #
3341 # Generally, it's a bad idea to examine the bytes in a Tcl string or to
3342 # construct improperly formed strings in this manner, because it involves
3343 # exposing that Tcl uses UTF-8 internally.
3344 #
3345 # This function doesn't work any more in Tcl 9.0, since the 'identity'
3346 # is gone (TIP #345)
3347 #
3348 # Arguments:
3349 # string being converted
3350 #
3351 # Results:
3352 # result fom encoding
3353 #
3354 # Side effects:
3355 # None
3356
3357 if {![package vsatisfies [package provide Tcl] 9.0-]} {
3358 proc tcltest::bytestring {string} {
3359 return [encoding convertfrom identity $string]
3360 }
3361 }
3362
3363 # tcltest::OpenFiles --
3364 #
3365 # used in io tests, uses testchannel
3366 #
3367 # Arguments:
3368 # None.
3369 #
3370 # Results:
3371 # ???
3372 #
3373 # Side effects:
3374 # None.
3375
3376 proc tcltest::OpenFiles {} {
3377 if {[catch {testchannel open} result]} {
3378 return {}
3379 }
3380 return $result
3381 }
3382
3383 # tcltest::LeakFiles --
3384 #
3385 # used in io tests, uses testchannel
3386 #
3387 # Arguments:
3388 # None.
3389 #
3390 # Results:
3391 # ???
3392 #
3393 # Side effects:
3394 # None.
3395
3396 proc tcltest::LeakFiles {old} {
3397 if {[catch {testchannel open} new]} {
3398 return {}
3399 }
3400 set leak {}
3401 foreach p $new {
3402 if {$p ni $old} {
3403 lappend leak $p
3404 }
3405 }
3406 return $leak
3407 }
3408
3409 #
3410 # Internationalization / ISO support procs -- dl
3411 #
3412
3413 # tcltest::SetIso8859_1_Locale --
3414 #
3415 # used in cmdIL.test, uses testlocale
3416 #
3417 # Arguments:
3418 # None.
3419 #
3420 # Results:
3421 # None.
3422 #
3423 # Side effects:
3424 # None.
3425
3426 proc tcltest::SetIso8859_1_Locale {} {
3427 variable previousLocale
3428 variable isoLocale
3429 if {[info commands testlocale] != ""} {
3430 set previousLocale [testlocale ctype]
3431 testlocale ctype $isoLocale
3432 }
3433 return
3434 }
3435
3436 # tcltest::RestoreLocale --
3437 #
3438 # used in cmdIL.test, uses testlocale
3439 #
3440 # Arguments:
3441 # None.
3442 #
3443 # Results:
3444 # None.
3445 #
3446 # Side effects:
3447 # None.
3448
3449 proc tcltest::RestoreLocale {} {
3450 variable previousLocale
3451 if {[info commands testlocale] != ""} {
3452 testlocale ctype $previousLocale
3453 }
3454 return
3455 }
3456
3457 # tcltest::threadReap --
3458 #
3459 # Kill all threads except for the main thread.
3460 # Do nothing if testthread is not defined.
3461 #
3462 # Arguments:
3463 # none.
3464 #
3465 # Results:
3466 # Returns the number of existing threads.
3467 #
3468 # Side Effects:
3469 # none.
3470 #
3471
3472 proc tcltest::threadReap {} {
3473 if {[info commands testthread] ne {}} {
3474
3475 # testthread built into tcltest
3476
3477 testthread errorproc ThreadNullError
3478 while {[llength [testthread names]] > 1} {
3479 foreach tid [testthread names] {
3480 if {$tid != [mainThread]} {
3481 catch {
3482 testthread send -async $tid {testthread exit}
3483 }
3484 }
3485 }
3486 ## Enter a bit a sleep to give the threads enough breathing
3487 ## room to kill themselves off, otherwise the end up with a
3488 ## massive queue of repeated events
3489 after 1
3490 }
3491 testthread errorproc ThreadError
3492 return [llength [testthread names]]
3493 } elseif {[info commands thread::id] ne {}} {
3494
3495 # Thread extension
3496
3497 thread::errorproc ThreadNullError
3498 while {[llength [thread::names]] > 1} {
3499 foreach tid [thread::names] {
3500 if {$tid != [mainThread]} {
3501 catch {thread::send -async $tid {thread::exit}}
3502 }
3503 }
3504 ## Enter a bit a sleep to give the threads enough breathing
3505 ## room to kill themselves off, otherwise the end up with a
3506 ## massive queue of repeated events
3507 after 1
3508 }
3509 thread::errorproc ThreadError
3510 return [llength [thread::names]]
3511 } else {
3512 return 1
3513 }
3514 return 0
3515 }
3516
3517 # Initialize the constraints and set up command line arguments
3518 namespace eval tcltest {
3519 # Define initializers for all the built-in constraint definitions
3520 DefineConstraintInitializers
3521
3522 # Set up the constraints in the testConstraints array to be lazily
3523 # initialized by a registered initializer, or by "false" if no
3524 # initializer is registered.
3525 trace add variable testConstraints read [namespace code SafeFetch]
3526
3527 # Only initialize constraints at package load time if an
3528 # [initConstraintsHook] has been predefined. This is only
3529 # for compatibility support. The modern way to add a custom
3530 # test constraint is to just call the [testConstraint] command
3531 # straight away, without all this "hook" nonsense.
3532 if {[namespace current] eq
3533 [namespace qualifiers [namespace which initConstraintsHook]]} {
3534 InitConstraints
3535 } else {
3536 proc initConstraintsHook {} {}
3537 }
3538
3539 # Define the standard match commands
3540 customMatch exact [list string equal]
3541 customMatch glob [list string match]
3542 customMatch regexp [list regexp --]
3543
3544 # If the TCLTEST_OPTIONS environment variable exists, configure
3545 # tcltest according to the option values it specifies. This has
3546 # the effect of resetting tcltest's default configuration.
3547 proc ConfigureFromEnvironment {} {
3548 upvar #0 env(TCLTEST_OPTIONS) options
3549 if {[catch {llength $options} msg]} {
3550 Warn "invalid TCLTEST_OPTIONS \"$options\":\n invalid\
3551 Tcl list: $msg"
3552 return
3553 }
3554 if {[llength $options] % 2} {
3555 Warn "invalid TCLTEST_OPTIONS: \"$options\":\n should be\
3556 -option value ?-option value ...?"
3557 return
3558 }
3559 if {[catch {Configure {*}$options} msg]} {
3560 Warn "invalid TCLTEST_OPTIONS: \"$options\":\n $msg"
3561 return
3562 }
3563 }
3564 if {[info exists ::env(TCLTEST_OPTIONS)]} {
3565 ConfigureFromEnvironment
3566 }
3567
3568 proc LoadTimeCmdLineArgParsingRequired {} {
3569 set required false
3570 if {[info exists ::argv] && ("-help" in $::argv)} {
3571 # The command line asks for -help, so give it (and exit)
3572 # right now. ([configure] does not process -help)
3573 set required true
3574 }
3575 foreach hook { PrintUsageInfoHook processCmdLineArgsHook
3576 processCmdLineArgsAddFlagsHook } {
3577 if {[namespace current] eq
3578 [namespace qualifiers [namespace which $hook]]} {
3579 set required true
3580 } else {
3581 proc $hook args {}
3582 }
3583 }
3584 return $required
3585 }
3586
3587 # Only initialize configurable options from the command line arguments
3588 # at package load time if necessary for backward compatibility. This
3589 # lets the tcltest user call [configure] for themselves if they wish.
3590 # Traces are established for auto-configuration from the command line
3591 # if any configurable options are accessed before the user calls
3592 # [configure].
3593 if {[LoadTimeCmdLineArgParsingRequired]} {
3594 ProcessCmdLineArgs
3595 } else {
3596 EstablishAutoConfigureTraces
3597 }
3598
3599 package provide [namespace tail [namespace current]] $Version
3600 }