1 # Copyright (c) 2013-2014 OPEN CASCADE SAS
3 # This file is part of Open CASCADE Technology software library.
5 # This library is free software; you can redistribute it and/or modify it under
6 # the terms of the GNU Lesser General Public License version 2.1 as published
7 # by the Free Software Foundation, with special exception defined in the file
8 # OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
9 # distribution for complete text of the license and disclaimer of any warranty.
11 # Alternatively, this file may be used under the terms of Open CASCADE
12 # commercial license or contractual agreement.
14 ############################################################################
15 # This file defines scripts for execution of OCCT tests.
16 # It should be loaded automatically when DRAW is started, and provides
17 # top-level commands starting with 'test'. Type 'help test' to get their
19 # See OCCT Tests User Guide for description of the test system.
21 # Note: procedures with names starting with underscore are for internal use
22 # inside the test system.
23 ############################################################################
25 # Default verbose level for command _run_test
28 # regexp for parsing test case results in summary log
29 set _test_case_regexp {^CASE\s+([\w.-]+)\s+([\w.-]+)\s+([\w.-]+)\s*:\s*([\w]+)(.*)}
31 # Basic command to run indicated test case in DRAW
33 Run specified test case
34 Use: test group grid casename [echo=0]
35 - If echo is set to 0 (default), log is stored in memory and only summary
36 is output (the log can be obtained with command "dlog get")
37 - If echo is set to 1 or "-echo", all commands and results are echoed
38 immediately, but log is not saved and summary is not produced
40 proc test {group grid casename {echo 0}} {
41 # get test case paths (will raise error if input is invalid)
42 _get_test $group $grid $casename dir gridname casefile
44 # if echo specified as "-echo", convert it to bool
45 if { "$echo" == "-echo" } { set echo t }
48 uplevel _run_test $dir $group $gridname $casefile $echo
52 _check_log $dir $group $gridname $casename [dlog get]
58 # Basic command to run indicated test case in DRAW
60 Run all tests, or specified group, or one grid
61 Use: testgrid [group [grid]] [options...]
63 -parallel N: run N parallel processes (default is number of CPUs, 0 to disable)
64 -refresh N: save summary logs every N seconds (default 600, minimal 1, 0 to disable)
65 -outdir dirname: set log directory (should be empty or non-existing)
66 -overwrite: force writing logs in existing non-empty directory
67 -xml filename: write XML report for Jenkins (in JUnit-like format)
69 proc testgrid {args} {
70 global env tcl_platform _tests_verbose
72 ######################################################
74 ######################################################
76 # check that environment variable defining paths to test scripts is defined
77 if { ! [info exists env(CSF_TestScriptsPath)] ||
78 [llength $env(CSF_TestScriptsPath)] <= 0 } {
79 error "Error: Environment variable CSF_TestScriptsPath is not defined"
83 set parallel [_get_nb_cpus]
88 for {set narg 0} {$narg < [llength $args]} {incr narg} {
89 set arg [lindex $args $narg]
92 if { $arg == "-parallel" } {
94 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
95 set parallel [expr [lindex $args $narg]]
97 error "Option -parallel requires argument"
103 if { $arg == "-refresh" } {
105 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
106 set refresh [expr [lindex $args $narg]]
108 error "Option -refresh requires argument"
114 if { $arg == "-outdir" } {
116 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
117 set logdir [lindex $args $narg]
119 error "Option -outdir requires argument"
124 # allow overwrite logs
125 if { $arg == "-overwrite" } {
131 if { $arg == "-xml" } {
133 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
134 set xmlfile [lindex $args $narg]
136 if { $xmlfile == "" } {
137 set xmlfile TESTS-summary.xml
143 if { [regexp {^-} $arg] } {
144 error "Error: unsupported option \"$arg\""
147 # treat arguments not recognized as options as group and grid names
148 if { ! [info exists groupname] } {
150 } elseif { ! [info exists gridname] } {
153 error "Error: cannot interpret argument $narg ($arg): both group and grid names are already defined by previous args!"
157 # check that target log directory is empty or does not exist
158 set logdir [file normalize [string trim $logdir]]
159 if { $logdir == "" } {
160 # if specified logdir is empty string, generate unique name like
161 # results_<branch>_<timestamp>
163 if { ! [catch {exec git branch} gitout] &&
164 [regexp {[*] ([\w]+)} $gitout res branch] } {
165 set prefix "${prefix}_$branch"
167 set logdir "${prefix}_[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
168 set logdir [file normalize $logdir]
170 if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
171 error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
173 if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
174 error "Error: Cannot create directory \"$logdir\", or it is not writable"
177 ######################################################
178 # prepare list of tests to be performed
179 ######################################################
181 # list of tests, each defined by a list of:
182 # test scripts directory
183 # group (subfolder) name
184 # grid (subfolder) name
186 # path to test case file
189 # iterate by all script paths
190 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
191 # protection against empty paths
192 set dir [string trim $dir]
193 if { $dir == "" } { continue }
195 if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
197 # check that directory exists
198 if { ! [file isdirectory $dir] } {
199 _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
203 # if test group is specified, check that directory with given name exists in this dir
204 # if not, continue to the next test dir
205 if { [info exists groupname] && $groupname != "" } {
206 if { [file isdirectory $dir/$groupname] } {
207 set groups $groupname
212 # else search all directories in the current dir
213 if [catch {glob -directory $dir -tail -types d *} groups] { continue }
217 if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
218 foreach group [lsort -dictionary $groups] {
219 if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
221 # file grids.list must exist: it defines sequence of grids in the group
222 if { ! [file exists $dir/$group/grids.list] } {
223 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
227 # read grids.list file and make a list of grids to be executed
229 set fd [open $dir/$group/grids.list]
231 while { [gets $fd line] >= 0 } {
234 # skip comments and empty lines
235 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
236 if { [string trim $line] == "" } { continue }
238 # get grid id and name
239 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
240 _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
244 # if specific grid is requested, check that it is present; otherwise make complete list
245 if { ! [info exists gridname] || $gridname == "" || $gridname == $gridid || $gridname == $grid } {
246 lappend gridlist $grid
251 # iterate by all grids
252 foreach grid $gridlist {
254 # check if this grid is aliased to another one
255 set griddir $dir/$group/$grid
256 if { [file exists $griddir/cases.list] } {
257 set fd [open $griddir/cases.list]
258 if { [gets $fd line] >= 0 } {
259 set griddir [file normalize $dir/$group/$grid/[string trim $line]]
264 # check if grid directory actually exists
265 if { ! [file isdirectory $griddir] } {
266 _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
270 # create directory for logging test results
271 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
273 # iterate by all tests in the grid directory
274 if { [catch {glob -directory $griddir -type f *} testfiles] } { continue }
275 foreach casefile [lsort -dictionary $testfiles] {
276 # filter out begin and end files
277 set casename [file tail $casefile]
278 if { $casename == "begin" || $casename == "end" } { continue }
280 lappend tests_list [list $dir $group $grid $casename $casefile]
285 if { [llength $tests_list] < 1 } {
286 error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
289 ######################################################
291 ######################################################
293 # log command arguments and environment
294 lappend log "Command: testgrid $args"
295 lappend log "Host: [info hostname]"
296 lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
297 catch {lappend log "DRAW build:\n[dversion]" }
298 lappend log "Environment:"
299 foreach envar [lsort [array names env]] {
300 lappend log "$envar=\"$env($envar)\""
304 set refresh_timer [clock seconds]
305 uplevel dchrono _timer reset
306 uplevel dchrono _timer start
308 # if parallel execution is requested, allocate thread pool
309 if { $parallel > 0 } {
310 if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
311 _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
314 set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
315 # suspend the pool until all jobs are posted, to prevent blocking of the process
316 # of starting / processing jobs by running threads
317 catch {tpool::suspend $worker}
318 if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
319 # limit number of jobs in the queue by reasonable value
320 # to prevent slowdown due to unnecessary queue processing
322 set nbpooled_max [expr 10 * $parallel]
323 set nbpooled_ok [expr 5 * $parallel]
329 foreach test_def $tests_list {
330 # check for user break
331 if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
336 set dir [lindex $test_def 0]
337 set group [lindex $test_def 1]
338 set grid [lindex $test_def 2]
339 set casename [lindex $test_def 3]
340 set casefile [lindex $test_def 4]
342 # command to set tests for generation of image in results directory
344 if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
346 # prepare command file for running test case in separate instance of DRAW
347 set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
348 puts $fd_cmd "$imgdir_cmd"
349 puts $fd_cmd "set test_image $casename"
350 puts $fd_cmd "_run_test $dir $group $grid $casefile t"
352 # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
353 # note: this is not needed if echo is set to 1 in call to _run_test above
354 if { ! [catch {dlog get}] } {
355 puts $fd_cmd "puts \[dlog get\]"
357 # else try to use old-style QA_ variables to get more output...
360 set env(QA_print_command) 1
363 # final 'exit' is needed when running on Linux under VirtualGl
367 # commant to run DRAW with a command file;
368 # note that empty string is passed as standard input to avoid possible
369 # hang-ups due to waiting for stdin of the launching process
370 set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
372 # alternative method to run without temporary file; disabled as it needs too many backslashes
374 # set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
375 # _run_test $dir $group $grid $casefile\\\; \
376 # puts \\\[dlog get\\\]\\\; exit"
379 # run test case, either in parallel or sequentially
380 if { $parallel > 0 } {
382 set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
383 set job_def($job) [list $logdir $dir $group $grid $casename]
385 if { $nbpooled > $nbpooled_max } {
386 _testgrid_process_jobs $worker $nbpooled_ok
389 # sequential execution
390 catch {eval $command} output
391 _log_test_case $output $logdir $dir $group $grid $casename log
393 # update summary log with requested period
394 if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
395 # update and dump summary
396 _log_summarize $logdir $log
397 set refresh_timer [clock seconds]
402 # get results of started threads
403 if { $parallel > 0 } {
404 _testgrid_process_jobs $worker
405 # release thread pool
406 if { $nbpooled > 0 } {
407 tpool::cancel $worker [array names job_def]
409 catch {tpool::resume $worker}
410 tpool::release $worker
413 uplevel dchrono _timer stop
414 set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
417 _log_and_puts log "*********** Stopped by user break ***********"
418 set time "${time} \nNote: the process is not finished, stopped by user break!"
421 ######################################################
422 # output summary logs and exit
423 ######################################################
425 _log_summarize $logdir $log $time
426 if { $logdir != "" } {
427 puts "Detailed logs are saved in $logdir"
429 if { $logdir != "" && $xmlfile != "" } {
430 # XML output file is assumed relative to log dir unless it is absolute
431 if { [ file pathtype $xmlfile] == "relative" } {
432 set xmlfile [file normalize $logdir/$xmlfile]
434 _log_xml_summary $logdir $xmlfile $log 0
435 puts "XML summary is saved to $xmlfile"
441 # Procedure to regenerate summary log from logs of test cases
443 Regenerate summary log in the test directory from logs of test cases.
444 This can be necessary if test grids are executed separately (e.g. on
445 different stations) or some grids have been re-executed.
446 Use: testsummarize dir
448 proc testsummarize {dir} {
449 global _test_case_regexp
451 if { ! [file isdirectory $dir] } {
452 error "Error: \"$dir\" is not a directory"
455 # get summary statements from all test cases in one log
458 # to avoid huge listing of logs, first find all subdirectories and iterate
459 # by them, parsing log files in each subdirectory independently
460 foreach grid [glob -directory $dir -types d -tails */*] {
461 foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
462 set file [file join $dir $grid $caselog]
464 set fd [open $file r]
465 while { [gets $fd line] >= 0 } {
466 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
467 if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } {
468 puts "Error: $file contains status line for another test case ($line)"
476 if { $nbfound != 1 } {
477 puts "Error: $file contains $nbfound status lines, expected 1"
482 _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
486 # Procedure to compare results of two runs of test cases
488 Compare results of two executions of tests (CPU times, ...)
489 Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
490 Where dir1 and dir2 are directories containing logs of two test runs.
492 -save filename: save resulting log in specified file (default name is
493 <dir1>/diff-<dir2>.log); HTML log is saved with same name
495 -status {same|ok|all}: filter cases for comparing by their status:
496 same - only cases with same status are compared (default)
497 ok - only cases with OK status in both logs are compared
498 all - results are compared regardless of status
500 1 - output only differences
501 2 - output also list of logs and directories present in one of dirs only
502 3 - (default) output also progress messages
504 proc testdiff {dir1 dir2 args} {
505 if { "$dir1" == "$dir2" } {
506 error "Input directories are the same"
509 ######################################################
511 ######################################################
514 set logfile [file join $dir1 "diff-[file tail $dir2].log"]
518 for {set narg 0} {$narg < [llength $args]} {incr narg} {
519 set arg [lindex $args $narg]
522 if { $arg == "-save" } {
524 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
525 set logfile [lindex $args $narg]
527 error "Error: Option -save must be followed by log file name"
533 if { $arg == "-status" } {
535 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
536 set status [lindex $args $narg]
537 } else { set status "" }
538 if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
539 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
545 if { $arg == "-verbose" } {
547 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
548 set verbose [expr [lindex $args $narg]]
550 error "Error: Option -verbose must be followed by integer verbose level"
555 if { [regexp {^-} $arg] } {
556 error "Error: unsupported option \"$arg\""
559 # non-option arguments form a subdirectory path
560 set basename [file join $basename $arg]
563 # run diff procedure (recursive)
564 _test_diff $dir1 $dir2 $basename $status $verbose log
566 # save result to log file
567 if { "$logfile" != "" } {
568 _log_save $logfile [join $log "\n"]
569 _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2
570 puts "Log is saved to $logfile (and .html)"
576 # Procedure to check data file before adding it to repository
578 Check data file and prepare it for putting to test data files repository.
579 Use: testfile [filelist]
582 - data file (non-binary) is in DOS encoding (CR/LF)
583 - same data file (with same or another name) already exists in the repository
584 - another file with the same name already exists
585 Note that names are assumed to be case-insensitive (for Windows).
587 Unless the file is already in the repository, tries to load it, reports
588 the recognized file format, file size, number of faces and edges in the
589 loaded shape (if any), and makes snapshot (in the temporary directory).
590 Finally it advises whether the file should be put to public section of the
593 proc testfile {filelist} {
596 # check that CSF_TestDataPath is defined
597 if { ! [info exists env(CSF_TestDataPath)] } {
598 error "Environment variable CSF_TestDataPath must be defined!"
601 # build registry of existing data files (name -> path) and (size -> path)
602 puts "Checking available test data files..."
603 foreach dir [_split_path $env(CSF_TestDataPath)] {
604 while {[llength $dir] != 0} {
605 set curr [lindex $dir 0]
606 set dir [lrange $dir 1 end]
607 eval lappend dir [glob -nocomplain -directory $curr -type d *]
608 foreach file [glob -nocomplain -directory $curr -type f *] {
609 set name [file tail $file]
610 set name_lower [string tolower $name]
612 # check that the file is not in DOS encoding
613 if { [_check_dos_encoding $file] } {
614 puts "Warning: file $file is in DOS encoding; was this intended?"
616 _check_file_format $file
618 # check if file with the same name is present twice or more
619 if { [info exists names($name_lower)] } {
620 puts "Error: more than one file with name $name is present in the repository:"
621 if { [_diff_files $file $names($name_lower)] } {
622 puts "(files are different by content)"
624 puts "(files are same by content)"
627 puts "--> $names($name_lower)"
631 # check if file with the same content exists
632 set size [file size $file]
633 if { [info exists sizes($size)] } {
634 foreach other $sizes($size) {
635 if { ! [_diff_files $file $other] } {
636 puts "Warning: two files with the same content found:"
643 # add the file to the registry
644 set names($name_lower) $file
645 lappend sizes($size) $file
649 if { [llength $filelist] <= 0 } { return }
651 # check the new files
653 puts "Checking new file(s)..."
654 foreach file $filelist {
655 # check for DOS encoding
656 if { [_check_dos_encoding $file] } {
657 puts "$file: Warning: DOS encoding detected"
660 set name [file tail $file]
661 set name_lower [string tolower $name]
663 # check for presence of the file with same name
664 if { [info exists names($name_lower)] } {
665 if { [_diff_files $file $names($name_lower)] } {
666 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
668 puts "$file: OK: already in the repository \n--> $names($name_lower)"
673 # check if file with the same content exists
674 set size [file size $file]
675 if { [info exists sizes($size)] } {
677 foreach other $sizes($size) {
678 if { ! [_diff_files $file $other] } {
679 puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
684 if { $found } { continue }
687 # try to read the file
688 set format [_check_file_format $file]
689 if { [catch {uplevel load_data_file $file $format a}] } {
690 puts "$file: Error: Cannot read as $format file"
694 # get number of faces and edges
697 set nbs [uplevel nbshapes a]
698 regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
699 regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
701 # classify; first check file size and number of faces and edges
702 if { $size < 95000 && $faces < 20 && $edges < 100 } {
706 # check if one of names of that file corresponds to typical name for
707 # MDTV bugs or has extension .rle, this should be old model
708 if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
709 [regexp -nocase {[.]rle\y} $name] } {
715 puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
717 set tmpdir [_get_temp_dir]
718 file mkdir $tmpdir/$dir
725 uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
729 puts "Snapshots are saved in subdirectory [_get_temp_dir]"
733 # Procedure to locate data file for test given its name.
734 # The search is performed assuming that the function is called
735 # from the test case script; the search order is:
736 # - subdirectory "data" of the test script (grid) folder
737 # - subdirectories in environment variable CSF_TestDataPath
738 # - subdirectory set by datadir command
739 # If file is not found, raises Tcl error.
740 proc locate_data_file {filename} {
741 global env groupname gridname casename
743 # check if the file is located in the subdirectory data of the script dir
744 set scriptfile [info script]
745 if { $scriptfile != "" } {
746 set path [file join [file dirname $scriptfile] data $filename]
747 if { [file exists $path] } {
748 return [file normalize $path]
752 # check sub-directories in paths indicated by CSF_TestDataPath
753 if { [info exists env(CSF_TestDataPath)] } {
754 foreach dir [_split_path $env(CSF_TestDataPath)] {
755 while {[llength $dir] != 0} {
756 set name [lindex $dir 0]
757 set dir [lrange $dir 1 end]
758 # skip directories starting with dot
759 if { [regexp {^[.]} $name] } { continue }
760 if { [file exists $name/$filename] } {
761 return [file normalize $name/$filename]
763 eval lappend dir [glob -nocomplain -directory $name -type d *]
768 # check current datadir
769 if { [file exists [uplevel datadir]/$filename] } {
770 return [file normalize [uplevel datadir]/$filename]
774 error [join [list "File $filename could not be found" \
775 "(should be in paths indicated by CSF_TestDataPath environment variable, " \
776 "or in subfolder data in the script directory)"] "\n"]
779 # Internal procedure to find test case indicated by group, grid, and test case names;
781 # - dir: path to the base directory of the tests group
782 # - gridname: actual name of the grid
783 # - casefile: path to the test case script
784 # if no such test is found, raises error with appropriate message
785 proc _get_test {group grid casename _dir _gridname _casefile} {
787 upvar $_gridname gridname
788 upvar $_casefile casefile
792 # check that environment variable defining paths to test scripts is defined
793 if { ! [info exists env(CSF_TestScriptsPath)] ||
794 [llength $env(CSF_TestScriptsPath)] <= 0 } {
795 error "Error: Environment variable CSF_TestScriptsPath is not defined"
798 # iterate by all script paths
799 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
800 # protection against empty paths
801 set dir [string trim $dir]
802 if { $dir == "" } { continue }
804 # check that directory exists
805 if { ! [file isdirectory $dir] } {
806 puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
810 # check if test group with given name exists in this dir
811 # if not, continue to the next test dir
812 if { ! [file isdirectory $dir/$group] } { continue }
814 # check that grid with given name (possibly alias) exists; stop otherwise
816 if { ! [file isdirectory $dir/$group/$gridname] } {
817 # check if grid is named by alias rather than by actual name
818 if { [file exists $dir/$group/grids.list] } {
819 set fd [open $dir/$group/grids.list]
820 while { [gets $fd line] >= 0 } {
821 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
822 if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
829 if { ! [file isdirectory $dir/$group/$gridname] } { continue }
831 # get actual file name of the script; stop if it cannot be found
832 set casefile $dir/$group/$gridname/$casename
833 if { ! [file exists $casefile] } {
834 # check if this grid is aliased to another one
835 if { [file exists $dir/$group/$gridname/cases.list] } {
836 set fd [open $dir/$group/$gridname/cases.list]
837 if { [gets $fd line] >= 0 } {
838 set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
843 if { [file exists $casefile] } {
849 # coming here means specified test is not found; report error
850 error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
851 "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
854 # Internal procedure to run test case indicated by base directory,
855 # grid and grid names, and test case file path.
856 # The log can be obtained by command "dlog get".
857 proc _run_test {scriptsdir group gridname casefile echo} {
861 uplevel dchrono _timer reset
862 uplevel dchrono _timer start
863 catch {uplevel meminfo w} membase
865 # enable commands logging; switch to old-style mode if dlog command is not present
867 if { [catch {dlog reset}] } {
874 rename puts puts-saved
876 global _tests_verbose
878 # log only output to stdout and stderr, not to file!
879 if {[llength $args] > 1} {
880 set optarg [lindex $args end-1]
881 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
882 dlog add [lindex $args end]
884 eval puts-saved $args
887 dlog add [lindex $args end]
894 # set variables identifying test case
895 uplevel set casename [file tail $casefile]
896 uplevel set groupname $group
897 uplevel set gridname $gridname
898 uplevel set dirname $scriptsdir
900 # set path for saving of log and images (if not yet set) to temp dir
901 if { ! [uplevel info exists imagedir] } {
902 uplevel set test_image \$casename
904 # create subdirectory in temp named after group and grid with timestamp
905 set rootlogdir [_get_temp_dir]
907 set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
908 set imagedir [file normalize ${rootlogdir}/$imagedir]
910 if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
911 ! [catch {glob -directory $imagedir *}] } {
912 # puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
913 set imagedir $rootlogdir
916 uplevel set imagedir \"$imagedir\"
919 # execute test scripts
920 if { [file exists $scriptsdir/$group/begin] } {
921 puts "Executing $scriptsdir/$group/begin..."; flush stdout
922 uplevel source $scriptsdir/$group/begin
924 if { [file exists $scriptsdir/$group/$gridname/begin] } {
925 puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
926 uplevel source $scriptsdir/$group/$gridname/begin
929 puts "Executing $casefile..."; flush stdout
930 uplevel source $casefile
932 if { [file exists $scriptsdir/$group/$gridname/end] } {
933 puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
934 uplevel source $scriptsdir/$group/$gridname/end
936 if { [file exists $scriptsdir/$group/end] } {
937 puts "Executing $scriptsdir/$group/end..."; flush stdout
938 uplevel source $scriptsdir/$group/end
941 puts "Tcl Exception: $res"
945 if { $dlog_exists } {
950 rename puts-saved puts
955 # stop cpulimit killer if armed by the test
958 # add memory and timing info
960 if { ! [catch {uplevel meminfo w} memuse] } {
961 set stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
963 uplevel dchrono _timer stop
964 set time [uplevel dchrono _timer show]
965 if [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu] {
966 set stats "${stats}TOTAL CPU TIME: $cpu sec\n"
968 if { $dlog_exists && ! $echo } {
975 # Internal procedure to check log of test execution and decide if it passed or failed
976 proc _check_log {dir group gridname casename log {_summary {}} {_html_log {}}} {
978 if { $_summary != "" } { upvar $_summary summary }
979 if { $_html_log != "" } { upvar $_html_log html_log }
985 # load definition of 'bad words' indicating test failure
986 # note that rules are loaded in the order of decreasing priority (grid - group - common),
987 # thus grid rules will override group ones
989 foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
990 if [catch {set fd [open $rulesfile r]}] { continue }
991 while { [gets $fd line] >= 0 } {
992 # skip comments and empty lines
993 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
994 if { [string trim $line] == "" } { continue }
996 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } {
997 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1000 set status [string trim $status]
1001 if { $comment != "" } { set status "$status ([string trim $comment])" }
1002 set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1003 lappend badwords [list $status $rexp]
1007 if { [llength $badwords] <= 0 } {
1008 puts "Warning: no definition of error indicators found (check files parse.rules)"
1011 # analyse log line-by-line
1014 foreach line [split $log "\n"] {
1015 # check if line defines specific treatment of some messages
1016 set deb_info [dversion]
1017 if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1018 if { [regexp {DEBUG_} $platforms] != 1 } {
1019 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1020 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1021 lappend html_log $line
1022 continue ;# TODO statement is for another platform
1025 # record TODOs that mark unstable cases
1026 if { [regexp {[\?]} $platforms] } {
1027 set todos_unstable([llength $todos]) 1
1030 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1031 lappend html_log [_html_highlight BAD $line]
1035 if { [regexp "Debug mode" $deb_info] != 1 && [regexp {DEBUG_} $platforms] == 1 } {
1039 if { [regexp "Debug mode" $deb_info] == 1 && [regexp {DEBUG_} $platforms] == 1 } {
1040 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1041 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1042 lappend html_log $line
1043 continue ;# TODO statement is for another platform
1046 # record TODOs that mark unstable cases
1047 if { [regexp {[\?]} $platforms] } {
1048 set todos_unstable([llength $todos]) 1
1051 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1052 lappend html_log [_html_highlight BAD $line]
1057 # check for presence of messages indicating test result
1059 foreach bw $badwords {
1060 if { [regexp [lindex $bw 1] $line] } {
1061 # check if this is known bad case
1063 for {set i 0} {$i < [llength $todos]} {incr i} {
1064 if { [regexp [lindex $todos $i] $line] } {
1067 lappend html_log [_html_highlight BAD $line]
1072 # if it is not in todo, define status
1073 if { ! $is_known } {
1074 set stat [lindex $bw 0 0]
1075 lappend html_log [_html_highlight $stat $line]
1076 if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1077 set status [lindex $bw 0]
1084 if { ! $ismarked } {
1085 lappend html_log $line
1089 # check for presence of TEST COMPLETED statement
1090 if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1091 # check whether absence of TEST COMPLETED is known problem
1092 set i [lsearch $todos "TEST INCOMPLETE"]
1096 set status "FAILED (no final message is found)"
1100 # check declared bad cases and diagnose possible improvement
1101 # (bad case declared but not detected).
1102 # Note that absence of the problem marked by TODO with question mark
1103 # (unstable) is not reported as improvement.
1104 if { $status == "" } {
1105 for {set i 0} {$i < [llength $todos]} {incr i} {
1106 if { ! [info exists todos_unstable($i)] &&
1107 (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1108 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1114 # report test as known bad if at least one of expected problems is found
1115 if { $status == "" && [llength [array names todo_count]] > 0 } {
1116 set status "BAD (known problem)"
1120 if { $status == "" } {set status "OK" }
1123 set status "FAILED ($res)"
1127 _log_and_puts summary "CASE $group $gridname $casename: $status"
1128 set summary [join $summary "\n"]
1129 set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1132 # Auxiliary procedure putting message to both cout and log variable (list)
1133 proc _log_and_puts {logvar message} {
1134 if { $logvar != "" } {
1136 lappend log $message
1141 # Auxiliary procedure to log result on single test case
1142 proc _log_test_case {output logdir dir group grid casename logvar} {
1145 # check result and make HTML log
1146 _check_log $dir $group $grid $casename $output summary html_log
1147 lappend log $summary
1150 if { $logdir != "" } {
1151 _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1152 _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1156 # Auxiliary procedure to save log to file
1157 proc _log_save {file log {title {}}} {
1158 # create missing directories as needed
1159 catch {file mkdir [file dirname $file]}
1161 # try to open a file
1162 if [catch {set fd [open $file w]} res] {
1163 error "Error saving log file $file: $res"
1166 # dump log and close
1173 # Auxiliary procedure to make a (relative if possible) URL to a file for
1174 # inclusion a reference in HTML log
1175 proc _make_url {htmldir file} {
1176 set htmlpath [file split [file normalize $htmldir]]
1177 set filepath [file split [file normalize $file]]
1178 for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1179 if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1180 if { $i == 0 } { break }
1181 return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1185 # if relative path could not be made, return full file URL
1186 return "file://[file normalize $file]"
1189 # Auxiliary procedure to save log to file
1190 proc _log_html {file log {title {}}} {
1191 # create missing directories as needed
1192 catch {file mkdir [file dirname $file]}
1194 # try to open a file
1195 if [catch {set fd [open $file w]} res] {
1196 error "Error saving log file $file: $res"
1200 puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1202 # add images if present
1203 set imgbasename [file rootname [file tail $file]]
1204 foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails ${imgbasename}*.gif ${imgbasename}*.png ${imgbasename}*.jpg]] {
1205 puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1208 # print log body, trying to add HTML links to script files on lines like
1209 # "Executing <filename>..."
1211 foreach line [split $log "\n"] {
1212 if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1213 [file exists $script] } {
1214 set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1218 puts $fd "</pre></body></html>"
1224 # Auxiliary method to make text with HTML highlighting according to status
1225 proc _html_color {status} {
1226 # choose a color for the cell according to result
1227 if { $status == "OK" } {
1229 } elseif { [regexp -nocase {^FAIL} $status] } {
1231 } elseif { [regexp -nocase {^BAD} $status] } {
1233 } elseif { [regexp -nocase {^IMP} $status] } {
1235 } elseif { [regexp -nocase {^SKIP} $status] } {
1237 } elseif { [regexp -nocase {^IGNOR} $status] } {
1240 puts "Warning: no color defined for status $status, using red as if FAILED"
1245 # Format text line in HTML to be colored according to the status
1246 proc _html_highlight {status line} {
1247 return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1250 # Internal procedure to generate HTML page presenting log of the tests
1251 # execution in tabular form, with links to reports on individual cases
1252 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1253 global _test_case_regexp
1255 # create missing directories as needed
1258 # try to open a file and start HTML
1259 if [catch {set fd [open $logdir/summary.html w]} res] {
1260 error "Error creating log file: $res"
1263 # write HRML header, including command to refresh log if still in progress
1264 puts $fd "<html><head>"
1265 puts $fd "<title>Tests summary</title>"
1266 if { $total_time == "" } {
1267 puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1269 puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1270 puts $fd "</head><body>"
1273 set legend(OK) "Test passed OK"
1274 set legend(FAILED) "Test failed (regression)"
1275 set legend(BAD) "Known problem"
1276 set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1277 set legend(SKIPPED) "Test skipped due to lack of data file"
1278 puts $fd "<h1>Summary</h1><table>"
1279 foreach nbstat $totals {
1280 set status [lindex $nbstat 1]
1281 if { [info exists legend($status)] } {
1282 set comment $legend($status)
1284 set comment "User-defined status"
1286 puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1290 # time stamp and elapsed time info
1291 if { $total_time != "" } {
1292 puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1293 puts $fd [join [split $total_time "\n"] "<p>"]
1295 puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1298 # print regressions and improvements
1299 foreach featured [list $regressions $improvements] {
1300 if { [llength $featured] <= 1 } { continue }
1301 set status [string trim [lindex $featured 0] { :}]
1302 puts $fd "<h2>$status</h2>"
1305 foreach test [lrange $featured 1 end] {
1306 if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1308 set name "Error building short list; check details"
1310 if { $gg != $groupgrid } {
1311 if { $groupgrid != "" } { puts $fd "</tr>" }
1313 puts $fd "<tr><td>$gg</td>"
1315 puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1317 if { $groupgrid != "" } { puts $fd "</tr>" }
1321 # put detailed log with TOC
1322 puts $fd "<hr><h1>Details</h1>"
1323 puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1325 # process log line-by-line
1329 foreach line [lsort -dictionary $log] {
1330 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1331 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1336 if { $grp != $group } {
1337 if { $letter != "" } { lappend body "</tr></table>" }
1341 puts $fd "<a href=\"#$group\">$group</a><br>"
1342 lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1346 if { $grd != $grid } {
1347 if { $letter != "" } { lappend body "</tr></table>" }
1350 puts $fd " <a href=\"#$group-$grid\">$grid</a><br>"
1351 lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1354 # check if test case name is <letter><digit>;
1355 # if not, set alnum to period "." to recognize non-standard test name
1356 if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1357 ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1361 # start new row when letter changes or for non-standard names
1362 if { $alnum != $letter || $alnum == "." } {
1363 if { $letter != "" } {
1364 lappend body "</tr><tr>"
1366 lappend body "<table><tr>"
1371 lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1373 puts $fd "</div>\n[join $body "\n"]</tr></table>"
1375 # add remaining lines of log as plain text
1376 puts $fd "<h2>Plain text messages</h2>\n<pre>"
1378 if { ! [regexp $_test_case_regexp $line] } {
1384 # close file and exit
1390 # Procedure to dump summary logs of tests
1391 proc _log_summarize {logdir log {total_time {}}} {
1393 # sort log records alphabetically to have the same behavior on Linux and Windows
1394 # (also needed if tests are run in parallel)
1395 set loglist [lsort -dictionary $log]
1397 # classify test cases by status
1398 foreach line $loglist {
1399 if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1400 lappend stat($status) $caseid
1404 set improvements {Improvements:}
1405 set regressions {Failed:}
1406 if { [info exists stat] } {
1407 foreach status [lsort [array names stat]] {
1408 lappend totals [list [llength $stat($status)] $status]
1410 # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1411 if { [regexp -nocase {^IMP} $status] } {
1412 eval lappend improvements $stat($status)
1413 } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1414 eval lappend regressions $stat($status)
1419 # if time is specified, add totals
1420 if { $total_time != "" } {
1421 if { [llength $improvements] > 1 } {
1422 _log_and_puts log [join $improvements "\n "]
1424 if { [llength $regressions] > 1 } {
1425 _log_and_puts log [join $regressions "\n "]
1427 if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1428 _log_and_puts log "No regressions"
1430 _log_and_puts log "Total cases: [join $totals {, }]"
1431 _log_and_puts log $total_time
1435 if { $logdir != "" } {
1436 _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1437 _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1443 # Internal procedure to generate XML log in JUnit style, for further
1444 # consumption by Jenkins or similar systems.
1446 # The output is intended to conform to XML schema supported by Jenkins found at
1447 # https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd
1449 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1450 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1451 proc _log_xml_summary {logdir filename log include_cout} {
1452 global _test_case_regexp
1454 catch {file mkdir [file dirname $filename]}
1456 # try to open a file and start XML
1457 if [catch {set fd [open $filename w]} res] {
1458 error "Error creating XML summary file $filename: $res"
1460 puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1461 puts $fd "<testsuites>"
1463 # prototype for command to generate test suite tag
1464 set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1465 set cmd_testsuite {puts $fd "<testsuite name=\"$group $grid\" tests=\"$nbtests\" failures=\"$nbfail\" errors=\"$nberr\" time=\"$time\" skipped=\"$nbskip\" $time_and_host>\n$testcases\n</testsuite>\n"}
1467 # sort log and process it line-by-line
1469 foreach line [lsort -dictionary $log] {
1470 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1471 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1474 set message [string trim $message " \t\r\n()"]
1476 # start new testsuite for each grid
1477 if { $grp != $group || $grd != $grid } {
1479 # write previous test suite
1480 if [info exists testcases] { eval $cmd_testsuite }
1495 # parse test log and get its CPU time
1498 if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } {
1499 puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1501 while { [gets $fdlog logline] >= 0 } {
1502 if { $include_cout } {
1503 set testout "$testout$logline\n"
1505 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1506 set add_cpu " time=\"$cpu\""
1507 set time [expr $time + $cpu]
1512 if { ! $include_cout } {
1513 set testout "$line\n"
1516 # record test case with its output and status
1517 # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1518 set testcases "$testcases\n <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1519 set testcases "$testcases\n <system-out>\n$testout </system-out>"
1520 if { $result != "OK" } {
1521 if { [regexp -nocase {^SKIP} $result] } {
1523 set testcases "$testcases\n <error name=\"$result\" message=\"$message\"/>"
1524 } elseif { [regexp -nocase {^BAD} $result] } {
1526 set testcases "$testcases\n <skipped>$message</skipped>"
1529 set testcases "$testcases\n <failure name=\"$result\" message=\"$message\"/>"
1532 set testcases "$testcases\n </testcase>"
1535 # write last test suite
1536 if [info exists testcases] { eval $cmd_testsuite }
1539 puts $fd "</testsuites>"
1544 # define custom platform name
1545 proc _tests_platform_def {} {
1546 global env tcl_platform
1548 if [info exists env(os_type)] { return }
1550 set env(os_type) $tcl_platform(platform)
1552 # use detailed mapping for various versions of Lunix
1553 # (note that mapping is rather non-uniform, for historical reasons)
1554 if { $tcl_platform(os) == "Linux" && ! [catch {exec cat /etc/issue} issue] } {
1555 if { [regexp {Mandriva[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1556 set env(os_type) Mandriva$num
1557 } elseif { [regexp {Red Hat[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1558 set env(os_type) RedHat$num
1559 } elseif { [regexp {Debian[ \tA-Za-z/]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1560 set env(os_type) Debian$num$subnum
1561 } elseif { [regexp {CentOS[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1562 set env(os_type) CentOS$num$subnum
1563 } elseif { [regexp {Scientific[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1564 set env(os_type) SL$num$subnum
1565 } elseif { [regexp {Fedora Core[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1566 set env(os_type) FedoraCore$num
1568 if { [exec uname -m] == "x86_64" } {
1569 set env(os_type) "$env(os_type)-64"
1571 } elseif { $tcl_platform(os) == "Darwin" } {
1572 set env(os_type) MacOS
1577 # Auxiliary procedure to split path specification (usually defined by
1578 # environment variable) into list of directories or files
1579 proc _split_path {pathspec} {
1582 # first replace all \ (which might occur on Windows) by /
1583 regsub -all "\\\\" $pathspec "/" pathspec
1585 # split path by platform-specific separator
1586 return [split $pathspec [_path_separator]]
1589 # Auxiliary procedure to define platform-specific separator for directories in
1590 # path specification
1591 proc _path_separator {} {
1594 # split path by platform-specific separator
1595 if { $tcl_platform(platform) == "windows" } {
1602 # Procedure to make a diff and common of two lists
1603 proc _list_diff {list1 list2 _in1 _in2 _common} {
1606 upvar $_common common
1611 foreach item $list1 {
1612 if { [lsearch -exact $list2 $item] >= 0 } {
1613 lappend common $item
1618 foreach item $list2 {
1619 if { [lsearch -exact $common $item] < 0 } {
1626 # procedure to load a file to Tcl string
1627 proc _read_file {filename} {
1628 set fd [open $filename r]
1629 set result [read -nonewline $fd]
1634 # procedure to construct name for the mage diff file
1635 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1636 return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1639 # Procedure to compare results of two runs of test cases
1640 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1643 # make sure to load diffimage command
1644 uplevel pload VISUALIZATION
1646 # prepare variable (array) for collecting statistics
1647 if { "$_statvar" != "" } {
1648 upvar $_statvar stat
1657 # first check subdirectories
1658 set path1 [file join $dir1 $basename]
1659 set path2 [file join $dir2 $basename]
1660 set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1661 set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1662 if { [llength $list1] >0 || [llength $list2] > 0 } {
1663 _list_diff $list1 $list2 in1 in2 common
1664 if { "$verbose" > 1 } {
1665 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1666 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1668 foreach subdir $common {
1669 if { "$verbose" > 2 } {
1670 _log_and_puts log "Checking [file join $basename $subdir]"
1672 _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1675 # check log files (only if directory has no subdirs)
1676 set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1677 set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1678 _list_diff $list1 $list2 in1 in2 common
1679 if { "$verbose" > 1 } {
1680 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1681 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1683 foreach logfile $common {
1685 set log1 [_read_file [file join $dir1 $basename $logfile]]
1686 set log2 [_read_file [file join $dir2 $basename $logfile]]
1687 set casename [file rootname $logfile]
1689 # check execution statuses
1690 set status1 UNDEFINED
1691 set status2 UNDEFINED
1692 if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1693 ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1694 "$status1" != "$status2" } {
1695 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1697 # if test statuses are different, further comparison makes
1698 # no sense unless explicitly requested
1699 if { "$status" != "all" } {
1703 if { "$status" == "ok" && "$status1" != "OK" } {
1710 if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1711 [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1712 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1713 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1715 # compare CPU times with 10% precision (but not less 0.5 sec)
1716 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1717 _log_and_puts log "CPU [split $basename /] $casename: $cpu1 / $cpu2"
1721 # check memory delta
1724 if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1725 [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1726 set stat(mem1) [expr $stat(mem1) + $mem1]
1727 set stat(mem2) [expr $stat(mem2) + $mem2]
1729 # compare memory usage with 10% precision (but not less 16 KiB)
1730 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1731 _log_and_puts log "MEMORY [split $basename /] $casename: $mem1 / $mem2"
1736 set imglist1 [glob -directory $path1 -types f -tails -nocomplain $casename*.{png,gif}]
1737 set imglist2 [glob -directory $path2 -types f -tails -nocomplain $casename*.{png,gif}]
1738 _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1739 if { "$verbose" > 1 } {
1740 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1741 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1743 foreach imgfile $imgcommon {
1744 # if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1745 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1746 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1747 [file join $dir2 $basename $imgfile] \
1748 0 0 0 $diffile} diff] } {
1749 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1750 file delete -force $diffile ;# clean possible previous result of diffimage
1751 } elseif { $diff != 0 } {
1752 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1754 file delete -force $diffile ;# clean useless artifact of diffimage
1760 if { "$_statvar" == "" } {
1761 _log_and_puts log "Total MEMORY difference: $stat(mem1) / $stat(mem2)"
1762 _log_and_puts log "Total CPU difference: $stat(cpu1) / $stat(cpu2)"
1766 # Auxiliary procedure to save log of results comparison to file
1767 proc _log_html_diff {file log dir1 dir2} {
1768 # create missing directories as needed
1769 catch {file mkdir [file dirname $file]}
1771 # try to open a file
1772 if [catch {set fd [open $file w]} res] {
1773 error "Error saving log file $file: $res"
1777 puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1778 puts $fd "<h1>Comparison of test results: $dir1 vs. $dir2</h1>"
1780 # print log body, trying to add HTML links to script files on lines like
1781 # "Executing <filename>..."
1783 set logpath [file split [file normalize $file]]
1787 if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1788 if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1789 # note: special handler for the case if test grid directoried are compared directly
1792 set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1793 set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1795 set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1796 if { [file exists $difffile] } {
1797 set imgd "<img src=\"[_make_url $file $difffile]\">"
1802 puts $fd "<table><tr><th>[file tail $dir1]</th><th>[file tail $dir2]</th><th>Different pixels</th></tr>"
1803 puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1806 puts $fd "</pre></body></html>"
1812 # get number of CPUs on the system
1813 proc _get_nb_cpus {} {
1814 global tcl_platform env
1816 if { "$tcl_platform(platform)" == "windows" } {
1817 # on Windows, take the value of the environment variable
1818 if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1819 ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1820 return $env(NUMBER_OF_PROCESSORS)
1822 } elseif { "$tcl_platform(os)" == "Linux" } {
1823 # on Linux, take number of logical processors listed in /proc/cpuinfo
1824 if { [catch {open "/proc/cpuinfo" r} fd] } {
1825 return 0 ;# should never happen, but...
1828 while { [gets $fd line] >= 0 } {
1829 if { [regexp {^processor[ \t]*:} $line] } {
1835 } elseif { "$tcl_platform(os)" == "Darwin" } {
1836 # on MacOS X, call sysctl command
1837 if { ! [catch {exec sysctl hw.ncpu} ret] &&
1838 [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
1843 # if cannot get good value, return 0 as default
1847 # check two files for difference
1848 proc _diff_files {file1 file2} {
1849 set fd1 [open $file1 "r"]
1850 set fd2 [open $file2 "r"]
1854 set nb1 [gets $fd1 line1]
1855 set nb2 [gets $fd2 line2]
1856 if { $nb1 != $nb2 } { set differ t; break }
1857 if { $nb1 < 0 } { break }
1858 if { [string compare $line1 $line2] } {
1869 # Check if file is in DOS encoding.
1870 # This check is done by presence of \r\n combination at the end of the first
1871 # line (i.e. prior to any other \n symbol).
1872 # Note that presence of non-ascii symbols typically used for recognition
1873 # of binary files is not suitable since some IGES and STEP files contain
1874 # non-ascii symbols.
1875 # Special check is added for PNG files which contain \r\n in the beginning.
1876 proc _check_dos_encoding {file} {
1877 set fd [open $file rb]
1879 if { [gets $fd line] && [regexp {.*\r$} $line] &&
1880 ! [regexp {^.PNG} $line] } {
1887 # procedure to recognize format of a data file by its first symbols (for OCCT
1888 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
1889 proc _check_file_format {file} {
1890 set fd [open $file rb]
1891 set line [read $fd 1024]
1895 set ext [file extension $file]
1897 if { [regexp {^DBRep_DrawableShape} $line] } {
1899 if { "$ext" != ".brep" && "$ext" != ".rle" &&
1900 "$ext" != ".draw" && "$ext" != "" } {
1903 } elseif { [regexp {^DrawTrSurf_} $line] } {
1905 if { "$ext" != ".rle" &&
1906 "$ext" != ".draw" && "$ext" != "" } {
1909 } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
1911 if { "$ext" != ".step" && "$ext" != ".stp" } {
1914 } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
1916 if { "$ext" != ".iges" && "$ext" != ".igs" } {
1919 } elseif { "$ext" == ".igs" } {
1921 } elseif { "$ext" == ".stp" } {
1924 set format [string toupper [string range $ext 1 end]]
1928 puts "$file: Warning: extension ($ext) does not match format ($format)"
1934 # procedure to load file knowing its format
1935 proc load_data_file {file format shape} {
1937 BREP { uplevel restore $file $shape }
1938 DRAW { uplevel restore $file $shape }
1939 IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
1940 STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
1941 STL { pload XSDRAW; uplevel readstl $shape $file }
1942 default { error "Cannot read $format file $file" }
1946 # procedure to get name of temporary directory,
1947 # ensuring it is existing and writeable
1948 proc _get_temp_dir {} {
1949 global env tcl_platform
1951 # check typical environment variables
1952 foreach var {TempDir Temp Tmp} {
1953 # check different case
1954 foreach name [list [string toupper $var] $var [string tolower $var]] {
1955 if { [info exists env($name)] && [file isdirectory $env($name)] &&
1956 [file writable $env($name)] } {
1957 return [regsub -all {\\} $env($name) /]
1962 # check platform-specific locations
1964 if { "$tcl_platform(platform)" == "windows" } {
1965 set paths "c:/TEMP c:/TMP /TEMP /TMP"
1966 if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
1967 set fallback [regsub -all {\\} "$env(HOMEDRIVE)$(HOMEPATH)/tmp" /]
1970 set paths "/tmp /var/tmp /usr/tmp"
1971 if { [info exists env(HOME)] } {
1972 set fallback "$env(HOME)/tmp"
1975 foreach dir $paths {
1976 if { [file isdirectory $dir] && [file writable $dir] } {
1981 # fallback case: use subdir /tmp of home or current dir
1982 file mkdir $fallback
1986 # extract of code from testgrid command used to process jobs running in
1987 # parallel until number of jobs in the queue becomes equal or less than
1989 proc _testgrid_process_jobs {worker {nb_ok 0}} {
1990 # bind local vars to variables of the caller procedure
1993 upvar job_def job_def
1994 upvar nbpooled nbpooled
1995 upvar userbreak userbreak
1996 upvar refresh refresh
1997 upvar refresh_timer refresh_timer
1999 catch {tpool::resume $worker}
2000 while { ! $userbreak && $nbpooled > $nb_ok } {
2001 foreach job [tpool::wait $worker [array names job_def]] {
2002 eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2007 # check for user break
2008 if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2012 # update summary log with requested period
2013 if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2014 _log_summarize $logdir $log
2015 set refresh_timer [clock seconds]
2018 catch {tpool::suspend $worker}