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 [options...]
36 -echo: all commands and results are echoed immediately,
37 but log is not saved and summary is not produced
38 It is also possible to use "1" instead of "-echo"
39 If echo is OFF, log is stored in memory and only summary
40 is output (the log can be obtained with command "dlog get")
41 -outfile filename: set log file (should be non-existing),
42 it is possible to save log file in text file or
43 in html file(with snapshot), for that "filename"
44 should have ".html" extension
45 -overwrite: force writing log in existing file
46 -beep: play sound signal at the end of the test
47 -errors: show all lines from the log report that are recognized as errors
48 This key will be ignored if the "-echo" key is already set.
50 proc test {group grid casename {args {}}} {
51 # set default values of arguments
58 # get test case paths (will raise error if input is invalid)
59 _get_test $group $grid $casename dir gridname casefile
62 for {set narg 0} {$narg < [llength $args]} {incr narg} {
63 set arg [lindex $args $narg]
64 # if echo specified as "-echo", convert it to bool
65 if { $arg == "-echo" || $arg == "1" } {
71 if { $arg == "-outfile" } {
73 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
74 set logfile [lindex $args $narg]
76 error "Option -outfile requires argument"
81 # allow overwrite existing log
82 if { $arg == "-overwrite" } {
87 # sound signal at the end of the test
88 if { $arg == "-beep" } {
93 # if errors specified as "-errors", convert it to bool
94 if { $arg == "-errors" } {
100 error "Error: unsupported option \"$arg\""
103 uplevel _run_test $dir $group $gridname $casefile $echo
107 _check_log $dir $group $gridname $casename $errors [dlog get] summary html_log
110 if { ! $overwrite && [file isfile $logfile] } {
111 error "Error: Specified log file \"$logfile\" exists; please remove it before running test or use -overwrite option"
113 if {$logfile != ""} {
114 if {[file extension $logfile] == ".html"} {
115 if {[regexp {vdump ([^\s\n]+)} $html_log dump snapshot]} {
116 catch {file copy -force $snapshot [file rootname $logfile][file extension $snapshot]}
118 _log_html $logfile $html_log "Test $group $grid $casename"
120 _log_save $logfile "[dlog get]\n$summary" "Test $group $grid $casename"
125 # play sound signal at the end of test
132 # Basic command to run indicated test case in DRAW
134 Run all tests, or specified group, or one grid
135 Use: testgrid [groupmask [gridmask [casemask]]] [options...]
137 -parallel N: run N parallel processes (default is number of CPUs, 0 to disable)
138 -refresh N: save summary logs every N seconds (default 600, minimal 1, 0 to disable)
139 -outdir dirname: set log directory (should be empty or non-existing)
140 -overwrite: force writing logs in existing non-empty directory
141 -xml filename: write XML report for Jenkins (in JUnit-like format)
142 -beep: play sound signal at the end of the tests
143 Groups, grids, and test cases to be executed can be specified by list of file
144 masks, separated by spaces or comma; default is all (*).
146 proc testgrid {args} {
147 global env tcl_platform _tests_verbose
149 ######################################################
151 ######################################################
153 # check that environment variable defining paths to test scripts is defined
154 if { ! [info exists env(CSF_TestScriptsPath)] ||
155 [llength $env(CSF_TestScriptsPath)] <= 0 } {
156 error "Error: Environment variable CSF_TestScriptsPath is not defined"
160 set parallel [_get_nb_cpus]
166 for {set narg 0} {$narg < [llength $args]} {incr narg} {
167 set arg [lindex $args $narg]
170 if { $arg == "-parallel" } {
172 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
173 set parallel [expr [lindex $args $narg]]
175 error "Option -parallel requires argument"
181 if { $arg == "-refresh" } {
183 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
184 set refresh [expr [lindex $args $narg]]
186 error "Option -refresh requires argument"
192 if { $arg == "-outdir" } {
194 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
195 set logdir [lindex $args $narg]
197 error "Option -outdir requires argument"
202 # allow overwrite logs
203 if { $arg == "-overwrite" } {
209 if { $arg == "-xml" } {
211 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
212 set xmlfile [lindex $args $narg]
214 if { $xmlfile == "" } {
215 set xmlfile TESTS-summary.xml
220 # sound signal at the end of the test
221 if { $arg == "-beep" } {
227 if { [regexp {^-} $arg] } {
228 error "Error: unsupported option \"$arg\""
231 # treat arguments not recognized as options as group and grid names
232 if { ! [info exists groupmask] } {
233 set groupmask [split $arg ,]
234 } elseif { ! [info exists gridmask] } {
235 set gridmask [split $arg ,]
236 } elseif { ! [info exists casemask] } {
237 set casemask [split $arg ,]
239 error "Error: cannot interpret argument $narg ($arg)"
243 # check that target log directory is empty or does not exist
244 set logdir [file normalize [string trim $logdir]]
245 if { $logdir == "" } {
246 # if specified logdir is empty string, generate unique name like
247 # results/<branch>_<timestamp>
249 if { ! [catch {exec git branch} gitout] &&
250 [regexp {[*] ([\w]+)} $gitout res branch] } {
251 set prefix "${branch}_"
253 set logdir "results/${prefix}[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
254 set logdir [file normalize $logdir]
256 if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
257 error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
259 if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
260 error "Error: Cannot create directory \"$logdir\", or it is not writable"
263 # masks for search of test groups, grids, and cases
264 if { ! [info exists groupmask] } { set groupmask * }
265 if { ! [info exists gridmask ] } { set gridmask * }
266 if { ! [info exists casemask ] } { set casemask * }
268 ######################################################
269 # prepare list of tests to be performed
270 ######################################################
272 # list of tests, each defined by a list of:
273 # test scripts directory
274 # group (subfolder) name
275 # grid (subfolder) name
277 # path to test case file
280 # iterate by all script paths
281 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
282 # protection against empty paths
283 set dir [string trim $dir]
284 if { $dir == "" } { continue }
286 if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
288 # check that directory exists
289 if { ! [file isdirectory $dir] } {
290 _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
294 # search all directories in the current dir with specified mask
295 if [catch {glob -directory $dir -tail -types d {*}$groupmask} groups] { continue }
298 if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
299 foreach group [lsort -dictionary $groups] {
300 if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
302 # file grids.list must exist: it defines sequence of grids in the group
303 if { ! [file exists $dir/$group/grids.list] } {
304 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
308 # read grids.list file and make a list of grids to be executed
310 set fd [open $dir/$group/grids.list]
312 while { [gets $fd line] >= 0 } {
315 # skip comments and empty lines
316 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
317 if { [string trim $line] == "" } { continue }
319 # get grid id and name
320 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
321 _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
325 # check that grid fits into the specified mask
326 foreach mask $gridmask {
327 if { $mask == $gridid || [string match $mask $grid] } {
328 lappend gridlist $grid
334 # iterate by all grids
335 foreach grid $gridlist {
337 # check if this grid is aliased to another one
338 set griddir $dir/$group/$grid
339 if { [file exists $griddir/cases.list] } {
340 set fd [open $griddir/cases.list]
341 if { [gets $fd line] >= 0 } {
342 set griddir [file normalize $dir/$group/$grid/[string trim $line]]
347 # check if grid directory actually exists
348 if { ! [file isdirectory $griddir] } {
349 _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
353 # create directory for logging test results
354 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
356 # iterate by all tests in the grid directory
357 if { [catch {glob -directory $griddir -type f {*}$casemask} testfiles] } { continue }
358 foreach casefile [lsort -dictionary $testfiles] {
359 # filter out files with reserved names
360 set casename [file tail $casefile]
361 if { $casename == "begin" || $casename == "end" ||
362 $casename == "parse.rules" } {
366 lappend tests_list [list $dir $group $grid $casename $casefile]
371 if { [llength $tests_list] < 1 } {
372 error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
374 puts "Running tests (total [llength $tests_list] test cases)..."
377 ######################################################
379 ######################################################
381 # log command arguments and environment
382 lappend log "Command: testgrid $args"
383 lappend log "Host: [info hostname]"
384 lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
385 catch {lappend log "DRAW build:\n[dversion]" }
386 lappend log "Environment:"
387 foreach envar [lsort [array names env]] {
388 lappend log "$envar=\"$env($envar)\""
392 set refresh_timer [clock seconds]
393 uplevel dchrono _timer reset
394 uplevel dchrono _timer start
396 # if parallel execution is requested, allocate thread pool
397 if { $parallel > 0 } {
398 if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
399 _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
402 set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
403 # suspend the pool until all jobs are posted, to prevent blocking of the process
404 # of starting / processing jobs by running threads
405 catch {tpool::suspend $worker}
406 if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
407 # limit number of jobs in the queue by reasonable value
408 # to prevent slowdown due to unnecessary queue processing
410 set nbpooled_max [expr 10 * $parallel]
411 set nbpooled_ok [expr 5 * $parallel]
417 foreach test_def $tests_list {
418 # check for user break
419 if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
424 set dir [lindex $test_def 0]
425 set group [lindex $test_def 1]
426 set grid [lindex $test_def 2]
427 set casename [lindex $test_def 3]
428 set casefile [lindex $test_def 4]
430 # command to set tests for generation of image in results directory
432 if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
434 # prepare command file for running test case in separate instance of DRAW
435 set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
436 puts $fd_cmd "$imgdir_cmd"
437 puts $fd_cmd "set test_image $casename"
438 puts $fd_cmd "_run_test $dir $group $grid $casefile t"
440 # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
441 # note: this is not needed if echo is set to 1 in call to _run_test above
442 if { ! [catch {dlog get}] } {
443 puts $fd_cmd "puts \[dlog get\]"
445 # else try to use old-style QA_ variables to get more output...
448 set env(QA_print_command) 1
451 # final 'exit' is needed when running on Linux under VirtualGl
455 # commant to run DRAW with a command file;
456 # note that empty string is passed as standard input to avoid possible
457 # hang-ups due to waiting for stdin of the launching process
458 set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
460 # alternative method to run without temporary file; disabled as it needs too many backslashes
462 # set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
463 # _run_test $dir $group $grid $casefile\\\; \
464 # puts \\\[dlog get\\\]\\\; exit"
467 # run test case, either in parallel or sequentially
468 if { $parallel > 0 } {
470 set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
471 set job_def($job) [list $logdir $dir $group $grid $casename]
473 if { $nbpooled > $nbpooled_max } {
474 _testgrid_process_jobs $worker $nbpooled_ok
477 # sequential execution
478 catch {eval $command} output
479 _log_test_case $output $logdir $dir $group $grid $casename log
481 # update summary log with requested period
482 if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
483 # update and dump summary
484 _log_summarize $logdir $log
485 set refresh_timer [clock seconds]
490 # get results of started threads
491 if { $parallel > 0 } {
492 _testgrid_process_jobs $worker
493 # release thread pool
494 if { $nbpooled > 0 } {
495 tpool::cancel $worker [array names job_def]
497 catch {tpool::resume $worker}
498 tpool::release $worker
501 uplevel dchrono _timer stop
502 set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
505 _log_and_puts log "*********** Stopped by user break ***********"
506 set time "${time} \nNote: the process is not finished, stopped by user break!"
509 ######################################################
510 # output summary logs and exit
511 ######################################################
513 _log_summarize $logdir $log $time
514 if { $logdir != "" } {
515 puts "Detailed logs are saved in $logdir"
517 if { $logdir != "" && $xmlfile != "" } {
518 # XML output file is assumed relative to log dir unless it is absolute
519 if { [ file pathtype $xmlfile] == "relative" } {
520 set xmlfile [file normalize $logdir/$xmlfile]
522 _log_xml_summary $logdir $xmlfile $log 0
523 puts "XML summary is saved to $xmlfile"
525 # play sound signal at the end of test
532 # Procedure to regenerate summary log from logs of test cases
534 Regenerate summary log in the test directory from logs of test cases.
535 This can be necessary if test grids are executed separately (e.g. on
536 different stations) or some grids have been re-executed.
537 Use: testsummarize dir
539 proc testsummarize {dir} {
540 global _test_case_regexp
542 if { ! [file isdirectory $dir] } {
543 error "Error: \"$dir\" is not a directory"
546 # get summary statements from all test cases in one log
549 # to avoid huge listing of logs, first find all subdirectories and iterate
550 # by them, parsing log files in each subdirectory independently
551 foreach grid [glob -directory $dir -types d -tails */*] {
552 foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
553 set file [file join $dir $grid $caselog]
555 set fd [open $file r]
556 while { [gets $fd line] >= 0 } {
557 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
558 if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } {
559 puts "Error: $file contains status line for another test case ($line)"
567 if { $nbfound != 1 } {
568 puts "Error: $file contains $nbfound status lines, expected 1"
573 _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
577 # Procedure to compare results of two runs of test cases
579 Compare results of two executions of tests (CPU times, ...)
580 Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
581 Where dir1 and dir2 are directories containing logs of two test runs.
583 -save filename: save resulting log in specified file (default name is
584 <dir1>/diff-<dir2>.log); HTML log is saved with same name
586 -status {same|ok|all}: filter cases for comparing by their status:
587 same - only cases with same status are compared (default)
588 ok - only cases with OK status in both logs are compared
589 all - results are compared regardless of status
591 1 - output only differences
592 2 - output also list of logs and directories present in one of dirs only
593 3 - (default) output also progress messages
595 proc testdiff {dir1 dir2 args} {
596 if { "$dir1" == "$dir2" } {
597 error "Input directories are the same"
600 ######################################################
602 ######################################################
605 set logfile [file join $dir1 "diff-[file tail $dir2].log"]
609 for {set narg 0} {$narg < [llength $args]} {incr narg} {
610 set arg [lindex $args $narg]
613 if { $arg == "-save" } {
615 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
616 set logfile [lindex $args $narg]
618 error "Error: Option -save must be followed by log file name"
624 if { $arg == "-status" } {
626 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
627 set status [lindex $args $narg]
628 } else { set status "" }
629 if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
630 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
636 if { $arg == "-verbose" } {
638 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
639 set verbose [expr [lindex $args $narg]]
641 error "Error: Option -verbose must be followed by integer verbose level"
646 if { [regexp {^-} $arg] } {
647 error "Error: unsupported option \"$arg\""
650 # non-option arguments form a subdirectory path
651 set basename [file join $basename $arg]
654 # run diff procedure (recursive)
655 _test_diff $dir1 $dir2 $basename $status $verbose log
657 # save result to log file
658 if { "$logfile" != "" } {
659 _log_save $logfile [join $log "\n"]
660 _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2
661 puts "Log is saved to $logfile (and .html)"
667 # Procedure to check data file before adding it to repository
669 Check data file and prepare it for putting to test data files repository.
670 Use: testfile [filelist]
673 - data file (non-binary) is in DOS encoding (CR/LF)
674 - same data file (with same or another name) already exists in the repository
675 - another file with the same name already exists
676 Note that names are assumed to be case-insensitive (for Windows).
678 Unless the file is already in the repository, tries to load it, reports
679 the recognized file format, file size, number of faces and edges in the
680 loaded shape (if any), and makes snapshot (in the temporary directory).
681 Finally it advises whether the file should be put to public section of the
684 proc testfile {filelist} {
687 # check that CSF_TestDataPath is defined
688 if { ! [info exists env(CSF_TestDataPath)] } {
689 error "Environment variable CSF_TestDataPath must be defined!"
692 # build registry of existing data files (name -> path) and (size -> path)
693 puts "Checking available test data files..."
694 foreach dir [_split_path $env(CSF_TestDataPath)] {
695 while {[llength $dir] != 0} {
696 set curr [lindex $dir 0]
697 set dir [lrange $dir 1 end]
698 eval lappend dir [glob -nocomplain -directory $curr -type d *]
699 foreach file [glob -nocomplain -directory $curr -type f *] {
700 set name [file tail $file]
701 set name_lower [string tolower $name]
703 # check that the file is not in DOS encoding
704 if { [_check_dos_encoding $file] } {
705 puts "Warning: file $file is in DOS encoding; was this intended?"
707 _check_file_format $file
709 # check if file with the same name is present twice or more
710 if { [info exists names($name_lower)] } {
711 puts "Error: more than one file with name $name is present in the repository:"
712 if { [_diff_files $file $names($name_lower)] } {
713 puts "(files are different by content)"
715 puts "(files are same by content)"
718 puts "--> $names($name_lower)"
722 # check if file with the same content exists
723 set size [file size $file]
724 if { [info exists sizes($size)] } {
725 foreach other $sizes($size) {
726 if { ! [_diff_files $file $other] } {
727 puts "Warning: two files with the same content found:"
734 # add the file to the registry
735 set names($name_lower) $file
736 lappend sizes($size) $file
740 if { [llength $filelist] <= 0 } { return }
742 # check the new files
744 puts "Checking new file(s)..."
745 foreach file $filelist {
746 # check for DOS encoding
747 if { [_check_dos_encoding $file] } {
748 puts "$file: Warning: DOS encoding detected"
751 set name [file tail $file]
752 set name_lower [string tolower $name]
754 # check for presence of the file with same name
755 if { [info exists names($name_lower)] } {
756 if { [_diff_files $file $names($name_lower)] } {
757 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
759 puts "$file: OK: already in the repository \n--> $names($name_lower)"
764 # check if file with the same content exists
765 set size [file size $file]
766 if { [info exists sizes($size)] } {
768 foreach other $sizes($size) {
769 if { ! [_diff_files $file $other] } {
770 puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
775 if { $found } { continue }
778 # try to read the file
779 set format [_check_file_format $file]
780 if { [catch {uplevel load_data_file $file $format a}] } {
781 puts "$file: Error: Cannot read as $format file"
785 # get number of faces and edges
788 set nbs [uplevel nbshapes a]
789 regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
790 regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
792 # classify; first check file size and number of faces and edges
793 if { $size < 95000 && $faces < 20 && $edges < 100 } {
797 # check if one of names of that file corresponds to typical name for
798 # MDTV bugs or has extension .rle, this should be old model
799 if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
800 [regexp -nocase {[.]rle\y} $name] } {
806 puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
808 set tmpdir [_get_temp_dir]
809 file mkdir $tmpdir/$dir
816 uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
820 puts "Snapshots are saved in subdirectory [_get_temp_dir]"
824 # Procedure to locate data file for test given its name.
825 # The search is performed assuming that the function is called
826 # from the test case script; the search order is:
827 # - subdirectory "data" of the test script (grid) folder
828 # - subdirectories in environment variable CSF_TestDataPath
829 # - subdirectory set by datadir command
830 # If file is not found, raises Tcl error.
831 proc locate_data_file {filename} {
832 global env groupname gridname casename
834 # check if the file is located in the subdirectory data of the script dir
835 set scriptfile [info script]
836 if { $scriptfile != "" } {
837 set path [file join [file dirname $scriptfile] data $filename]
838 if { [file exists $path] } {
839 return [file normalize $path]
843 # check sub-directories in paths indicated by CSF_TestDataPath
844 if { [info exists env(CSF_TestDataPath)] } {
845 foreach dir [_split_path $env(CSF_TestDataPath)] {
846 while {[llength $dir] != 0} {
847 set name [lindex $dir 0]
848 set dir [lrange $dir 1 end]
849 # skip directories starting with dot
850 if { [regexp {^[.]} $name] } { continue }
851 if { [file exists $name/$filename] } {
852 return [file normalize $name/$filename]
854 eval lappend dir [glob -nocomplain -directory $name -type d *]
859 # check current datadir
860 if { [file exists [uplevel datadir]/$filename] } {
861 return [file normalize [uplevel datadir]/$filename]
865 error [join [list "File $filename could not be found" \
866 "(should be in paths indicated by CSF_TestDataPath environment variable, " \
867 "or in subfolder data in the script directory)"] "\n"]
870 # Internal procedure to find test case indicated by group, grid, and test case names;
872 # - dir: path to the base directory of the tests group
873 # - gridname: actual name of the grid
874 # - casefile: path to the test case script
875 # if no such test is found, raises error with appropriate message
876 proc _get_test {group grid casename _dir _gridname _casefile} {
878 upvar $_gridname gridname
879 upvar $_casefile casefile
883 # check that environment variable defining paths to test scripts is defined
884 if { ! [info exists env(CSF_TestScriptsPath)] ||
885 [llength $env(CSF_TestScriptsPath)] <= 0 } {
886 error "Error: Environment variable CSF_TestScriptsPath is not defined"
889 # iterate by all script paths
890 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
891 # protection against empty paths
892 set dir [string trim $dir]
893 if { $dir == "" } { continue }
895 # check that directory exists
896 if { ! [file isdirectory $dir] } {
897 puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
901 # check if test group with given name exists in this dir
902 # if not, continue to the next test dir
903 if { ! [file isdirectory $dir/$group] } { continue }
905 # check that grid with given name (possibly alias) exists; stop otherwise
907 if { ! [file isdirectory $dir/$group/$gridname] } {
908 # check if grid is named by alias rather than by actual name
909 if { [file exists $dir/$group/grids.list] } {
910 set fd [open $dir/$group/grids.list]
911 while { [gets $fd line] >= 0 } {
912 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
913 if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
920 if { ! [file isdirectory $dir/$group/$gridname] } { continue }
922 # get actual file name of the script; stop if it cannot be found
923 set casefile $dir/$group/$gridname/$casename
924 if { ! [file exists $casefile] } {
925 # check if this grid is aliased to another one
926 if { [file exists $dir/$group/$gridname/cases.list] } {
927 set fd [open $dir/$group/$gridname/cases.list]
928 if { [gets $fd line] >= 0 } {
929 set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
934 if { [file exists $casefile] } {
940 # coming here means specified test is not found; report error
941 error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
942 "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
945 # Internal procedure to run test case indicated by base directory,
946 # grid and grid names, and test case file path.
947 # The log can be obtained by command "dlog get".
948 proc _run_test {scriptsdir group gridname casefile echo} {
952 uplevel dchrono _timer reset
953 uplevel dchrono _timer start
954 catch {uplevel meminfo h} membase
956 # enable commands logging; switch to old-style mode if dlog command is not present
958 if { [catch {dlog reset}] } {
965 rename puts puts-saved
967 global _tests_verbose
969 # log only output to stdout and stderr, not to file!
970 if {[llength $args] > 1} {
971 set optarg [lindex $args end-1]
972 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
973 dlog add [lindex $args end]
975 eval puts-saved $args
978 dlog add [lindex $args end]
985 # set variables identifying test case
986 uplevel set casename [file tail $casefile]
987 uplevel set groupname $group
988 uplevel set gridname $gridname
989 uplevel set dirname $scriptsdir
991 # set path for saving of log and images (if not yet set) to temp dir
992 if { ! [uplevel info exists imagedir] } {
993 uplevel set test_image \$casename
995 # create subdirectory in temp named after group and grid with timestamp
996 set rootlogdir [_get_temp_dir]
998 set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
999 set imagedir [file normalize ${rootlogdir}/$imagedir]
1001 if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1002 ! [catch {glob -directory $imagedir *}] } {
1003 # puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
1004 set imagedir $rootlogdir
1007 uplevel set imagedir \"$imagedir\"
1010 # execute test scripts
1011 if { [file exists $scriptsdir/$group/begin] } {
1012 puts "Executing $scriptsdir/$group/begin..."; flush stdout
1013 uplevel source $scriptsdir/$group/begin
1015 if { [file exists $scriptsdir/$group/$gridname/begin] } {
1016 puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1017 uplevel source $scriptsdir/$group/$gridname/begin
1020 puts "Executing $casefile..."; flush stdout
1021 uplevel source $casefile
1023 if { [file exists $scriptsdir/$group/$gridname/end] } {
1024 puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1025 uplevel source $scriptsdir/$group/$gridname/end
1027 if { [file exists $scriptsdir/$group/end] } {
1028 puts "Executing $scriptsdir/$group/end..."; flush stdout
1029 uplevel source $scriptsdir/$group/end
1032 puts "Tcl Exception: $res"
1036 if { $dlog_exists } {
1041 rename puts-saved puts
1046 # stop cpulimit killer if armed by the test
1049 # add memory and timing info
1051 if { ! [catch {uplevel meminfo h} memuse] } {
1052 set stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
1054 uplevel dchrono _timer stop
1055 set time [uplevel dchrono _timer show]
1056 if [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu] {
1057 set stats "${stats}TOTAL CPU TIME: $cpu sec\n"
1059 if { $dlog_exists && ! $echo } {
1066 # Internal procedure to check log of test execution and decide if it passed or failed
1067 proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
1069 if { $_summary != "" } { upvar $_summary summary }
1070 if { $_html_log != "" } { upvar $_html_log html_log }
1077 # load definition of 'bad words' indicating test failure
1078 # note that rules are loaded in the order of decreasing priority (grid - group - common),
1079 # thus grid rules will override group ones
1081 foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
1082 if [catch {set fd [open $rulesfile r]}] { continue }
1083 while { [gets $fd line] >= 0 } {
1084 # skip comments and empty lines
1085 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
1086 if { [string trim $line] == "" } { continue }
1088 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } {
1089 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1092 set status [string trim $status]
1093 if { $comment != "" } { set status "$status ([string trim $comment])" }
1094 set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1095 lappend badwords [list $status $rexp]
1099 if { [llength $badwords] <= 0 } {
1100 puts "Warning: no definition of error indicators found (check files parse.rules)"
1103 # analyse log line-by-line
1106 foreach line [split $log "\n"] {
1107 # check if line defines specific treatment of some messages
1108 set deb_info [dversion]
1109 if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1110 if { [regexp {DEBUG_} $platforms] != 1 } {
1111 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1112 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1113 lappend html_log $line
1114 continue ;# TODO statement is for another platform
1117 # record TODOs that mark unstable cases
1118 if { [regexp {[\?]} $platforms] } {
1119 set todos_unstable([llength $todos]) 1
1122 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1123 lappend html_log [_html_highlight BAD $line]
1127 if { [regexp "Debug mode" $deb_info] != 1 && [regexp {DEBUG_} $platforms] == 1 } {
1131 if { [regexp "Debug mode" $deb_info] == 1 && [regexp {DEBUG_} $platforms] == 1 } {
1132 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1133 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1134 lappend html_log $line
1135 continue ;# TODO statement is for another platform
1138 # record TODOs that mark unstable cases
1139 if { [regexp {[\?]} $platforms] } {
1140 set todos_unstable([llength $todos]) 1
1143 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1144 lappend html_log [_html_highlight BAD $line]
1149 # check for presence of messages indicating test result
1151 foreach bw $badwords {
1152 if { [regexp [lindex $bw 1] $line] } {
1153 # check if this is known bad case
1155 for {set i 0} {$i < [llength $todos]} {incr i} {
1156 if { [regexp [lindex $todos $i] $line] } {
1159 lappend html_log [_html_highlight BAD $line]
1164 # if it is not in todo, define status
1165 if { ! $is_known } {
1166 set stat [lindex $bw 0 0]
1168 lappend errors_log $line
1170 lappend html_log [_html_highlight $stat $line]
1171 if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1172 set status [lindex $bw 0]
1179 if { ! $ismarked } {
1180 lappend html_log $line
1184 # check for presence of TEST COMPLETED statement
1185 if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1186 # check whether absence of TEST COMPLETED is known problem
1187 set i [lsearch $todos "TEST INCOMPLETE"]
1191 set status "FAILED (no final message is found)"
1195 # check declared bad cases and diagnose possible improvement
1196 # (bad case declared but not detected).
1197 # Note that absence of the problem marked by TODO with question mark
1198 # (unstable) is not reported as improvement.
1199 if { $status == "" } {
1200 for {set i 0} {$i < [llength $todos]} {incr i} {
1201 if { ! [info exists todos_unstable($i)] &&
1202 (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1203 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1209 # report test as known bad if at least one of expected problems is found
1210 if { $status == "" && [llength [array names todo_count]] > 0 } {
1211 set status "BAD (known problem)"
1215 if { $status == "" } {set status "OK" }
1218 set status "FAILED ($res)"
1222 _log_and_puts summary "CASE $group $gridname $casename: $status"
1223 set summary [join $summary "\n"]
1225 foreach error $errors_log {
1226 _log_and_puts summary " $error"
1229 set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1232 # Auxiliary procedure putting message to both cout and log variable (list)
1233 proc _log_and_puts {logvar message} {
1234 if { $logvar != "" } {
1236 lappend log $message
1241 # Auxiliary procedure to log result on single test case
1242 proc _log_test_case {output logdir dir group grid casename logvar} {
1245 # check result and make HTML log
1246 _check_log $dir $group $grid $casename $show_errors $output summary html_log
1247 lappend log $summary
1250 if { $logdir != "" } {
1251 _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1252 _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1256 # Auxiliary procedure to save log to file
1257 proc _log_save {file log {title {}}} {
1258 # create missing directories as needed
1259 catch {file mkdir [file dirname $file]}
1261 # try to open a file
1262 if [catch {set fd [open $file w]} res] {
1263 error "Error saving log file $file: $res"
1266 # dump log and close
1273 # Auxiliary procedure to make a (relative if possible) URL to a file for
1274 # inclusion a reference in HTML log
1275 proc _make_url {htmldir file} {
1276 set htmlpath [file split [file normalize $htmldir]]
1277 set filepath [file split [file normalize $file]]
1278 for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1279 if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1280 if { $i == 0 } { break }
1281 return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1285 # if relative path could not be made, return full file URL
1286 return "file://[file normalize $file]"
1289 # Auxiliary procedure to save log to file
1290 proc _log_html {file log {title {}}} {
1291 # create missing directories as needed
1292 catch {file mkdir [file dirname $file]}
1294 # try to open a file
1295 if [catch {set fd [open $file w]} res] {
1296 error "Error saving log file $file: $res"
1300 puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1302 # add images if present; these should have either PNG, GIF, or JPG extension,
1303 # and start with name of the test script, with optional suffix separated
1304 # by underscore or dash
1305 set imgbasename [file rootname [file tail $file]]
1306 foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails \
1307 ${imgbasename}.gif ${imgbasename}.png ${imgbasename}.jpg \
1308 ${imgbasename}_*.gif ${imgbasename}_*.png ${imgbasename}_*.jpg \
1309 ${imgbasename}-*.gif ${imgbasename}-*.png ${imgbasename}-*.jpg]] {
1310 puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1313 # print log body, trying to add HTML links to script files on lines like
1314 # "Executing <filename>..."
1316 foreach line [split $log "\n"] {
1317 if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1318 [file exists $script] } {
1319 set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1323 puts $fd "</pre></body></html>"
1329 # Auxiliary method to make text with HTML highlighting according to status
1330 proc _html_color {status} {
1331 # choose a color for the cell according to result
1332 if { $status == "OK" } {
1334 } elseif { [regexp -nocase {^FAIL} $status] } {
1336 } elseif { [regexp -nocase {^BAD} $status] } {
1338 } elseif { [regexp -nocase {^IMP} $status] } {
1340 } elseif { [regexp -nocase {^SKIP} $status] } {
1342 } elseif { [regexp -nocase {^IGNOR} $status] } {
1345 puts "Warning: no color defined for status $status, using red as if FAILED"
1350 # Format text line in HTML to be colored according to the status
1351 proc _html_highlight {status line} {
1352 return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1355 # Internal procedure to generate HTML page presenting log of the tests
1356 # execution in tabular form, with links to reports on individual cases
1357 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1358 global _test_case_regexp
1360 # create missing directories as needed
1363 # try to open a file and start HTML
1364 if [catch {set fd [open $logdir/summary.html w]} res] {
1365 error "Error creating log file: $res"
1368 # write HRML header, including command to refresh log if still in progress
1369 puts $fd "<html><head>"
1370 puts $fd "<title>Tests summary</title>"
1371 if { $total_time == "" } {
1372 puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1374 puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1375 puts $fd "</head><body>"
1378 set legend(OK) "Test passed OK"
1379 set legend(FAILED) "Test failed (regression)"
1380 set legend(BAD) "Known problem"
1381 set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1382 set legend(SKIPPED) "Test skipped due to lack of data file"
1383 puts $fd "<h1>Summary</h1><table>"
1384 foreach nbstat $totals {
1385 set status [lindex $nbstat 1]
1386 if { [info exists legend($status)] } {
1387 set comment $legend($status)
1389 set comment "User-defined status"
1391 puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1395 # time stamp and elapsed time info
1396 if { $total_time != "" } {
1397 puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1398 puts $fd [join [split $total_time "\n"] "<p>"]
1400 puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1403 # print regressions and improvements
1404 foreach featured [list $regressions $improvements] {
1405 if { [llength $featured] <= 1 } { continue }
1406 set status [string trim [lindex $featured 0] { :}]
1407 puts $fd "<h2>$status</h2>"
1410 foreach test [lrange $featured 1 end] {
1411 if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1413 set name "Error building short list; check details"
1415 if { $gg != $groupgrid } {
1416 if { $groupgrid != "" } { puts $fd "</tr>" }
1418 puts $fd "<tr><td>$gg</td>"
1420 puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1422 if { $groupgrid != "" } { puts $fd "</tr>" }
1426 # put detailed log with TOC
1427 puts $fd "<hr><h1>Details</h1>"
1428 puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1430 # process log line-by-line
1434 foreach line [lsort -dictionary $log] {
1435 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1436 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1441 if { $grp != $group } {
1442 if { $letter != "" } { lappend body "</tr></table>" }
1446 puts $fd "<a href=\"#$group\">$group</a><br>"
1447 lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1451 if { $grd != $grid } {
1452 if { $letter != "" } { lappend body "</tr></table>" }
1455 puts $fd " <a href=\"#$group-$grid\">$grid</a><br>"
1456 lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1459 # check if test case name is <letter><digit>;
1460 # if not, set alnum to period "." to recognize non-standard test name
1461 if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1462 ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1466 # start new row when letter changes or for non-standard names
1467 if { $alnum != $letter || $alnum == "." } {
1468 if { $letter != "" } {
1469 lappend body "</tr><tr>"
1471 lappend body "<table><tr>"
1476 lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1478 puts $fd "</div>\n[join $body "\n"]</tr></table>"
1480 # add remaining lines of log as plain text
1481 puts $fd "<h2>Plain text messages</h2>\n<pre>"
1483 if { ! [regexp $_test_case_regexp $line] } {
1489 # close file and exit
1495 # Procedure to dump summary logs of tests
1496 proc _log_summarize {logdir log {total_time {}}} {
1498 # sort log records alphabetically to have the same behavior on Linux and Windows
1499 # (also needed if tests are run in parallel)
1500 set loglist [lsort -dictionary $log]
1502 # classify test cases by status
1503 foreach line $loglist {
1504 if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1505 lappend stat($status) $caseid
1509 set improvements {Improvements:}
1510 set regressions {Failed:}
1511 if { [info exists stat] } {
1512 foreach status [lsort [array names stat]] {
1513 lappend totals [list [llength $stat($status)] $status]
1515 # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1516 if { [regexp -nocase {^IMP} $status] } {
1517 eval lappend improvements $stat($status)
1518 } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1519 eval lappend regressions $stat($status)
1524 # if time is specified, add totals
1525 if { $total_time != "" } {
1526 if { [llength $improvements] > 1 } {
1527 _log_and_puts log [join $improvements "\n "]
1529 if { [llength $regressions] > 1 } {
1530 _log_and_puts log [join $regressions "\n "]
1532 if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1533 _log_and_puts log "No regressions"
1535 _log_and_puts log "Total cases: [join $totals {, }]"
1536 _log_and_puts log $total_time
1540 if { $logdir != "" } {
1541 _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1542 _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1548 # Internal procedure to generate XML log in JUnit style, for further
1549 # consumption by Jenkins or similar systems.
1551 # The output is intended to conform to XML schema supported by Jenkins found at
1552 # 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
1554 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1555 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1556 proc _log_xml_summary {logdir filename log include_cout} {
1557 global _test_case_regexp
1559 catch {file mkdir [file dirname $filename]}
1561 # try to open a file and start XML
1562 if [catch {set fd [open $filename w]} res] {
1563 error "Error creating XML summary file $filename: $res"
1565 puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1566 puts $fd "<testsuites>"
1568 # prototype for command to generate test suite tag
1569 set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1570 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"}
1572 # sort log and process it line-by-line
1574 foreach line [lsort -dictionary $log] {
1575 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1576 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1579 set message [string trim $message " \t\r\n()"]
1581 # start new testsuite for each grid
1582 if { $grp != $group || $grd != $grid } {
1584 # write previous test suite
1585 if [info exists testcases] { eval $cmd_testsuite }
1600 # parse test log and get its CPU time
1603 if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } {
1604 puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1606 while { [gets $fdlog logline] >= 0 } {
1607 if { $include_cout } {
1608 set testout "$testout$logline\n"
1610 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1611 set add_cpu " time=\"$cpu\""
1612 set time [expr $time + $cpu]
1617 if { ! $include_cout } {
1618 set testout "$line\n"
1621 # record test case with its output and status
1622 # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1623 set testcases "$testcases\n <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1624 set testcases "$testcases\n <system-out>\n$testout </system-out>"
1625 if { $result != "OK" } {
1626 if { [regexp -nocase {^SKIP} $result] } {
1628 set testcases "$testcases\n <error name=\"$result\" message=\"$message\"/>"
1629 } elseif { [regexp -nocase {^BAD} $result] } {
1631 set testcases "$testcases\n <skipped>$message</skipped>"
1634 set testcases "$testcases\n <failure name=\"$result\" message=\"$message\"/>"
1637 set testcases "$testcases\n </testcase>"
1640 # write last test suite
1641 if [info exists testcases] { eval $cmd_testsuite }
1644 puts $fd "</testsuites>"
1649 # define custom platform name
1650 proc _tests_platform_def {} {
1651 global env tcl_platform
1653 if [info exists env(os_type)] { return }
1655 set env(os_type) $tcl_platform(platform)
1657 # use detailed mapping for various versions of Lunix
1658 # (note that mapping is rather non-uniform, for historical reasons)
1659 if { $tcl_platform(os) == "Linux" && ! [catch {exec cat /etc/issue} issue] } {
1660 if { [regexp {Mandriva[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1661 set env(os_type) Mandriva$num
1662 } elseif { [regexp {Red Hat[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1663 set env(os_type) RedHat$num
1664 } elseif { [regexp {Debian[ \tA-Za-z/]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1665 set env(os_type) Debian$num$subnum
1666 } elseif { [regexp {CentOS[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1667 set env(os_type) CentOS$num$subnum
1668 } elseif { [regexp {Scientific[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1669 set env(os_type) SL$num$subnum
1670 } elseif { [regexp {Fedora Core[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1671 set env(os_type) FedoraCore$num
1673 if { [exec uname -m] == "x86_64" } {
1674 set env(os_type) "$env(os_type)-64"
1676 } elseif { $tcl_platform(os) == "Darwin" } {
1677 set env(os_type) MacOS
1682 # Auxiliary procedure to split path specification (usually defined by
1683 # environment variable) into list of directories or files
1684 proc _split_path {pathspec} {
1687 # first replace all \ (which might occur on Windows) by /
1688 regsub -all "\\\\" $pathspec "/" pathspec
1690 # split path by platform-specific separator
1691 return [split $pathspec [_path_separator]]
1694 # Auxiliary procedure to define platform-specific separator for directories in
1695 # path specification
1696 proc _path_separator {} {
1699 # split path by platform-specific separator
1700 if { $tcl_platform(platform) == "windows" } {
1707 # Procedure to make a diff and common of two lists
1708 proc _list_diff {list1 list2 _in1 _in2 _common} {
1711 upvar $_common common
1716 foreach item $list1 {
1717 if { [lsearch -exact $list2 $item] >= 0 } {
1718 lappend common $item
1723 foreach item $list2 {
1724 if { [lsearch -exact $common $item] < 0 } {
1731 # procedure to load a file to Tcl string
1732 proc _read_file {filename} {
1733 set fd [open $filename r]
1734 set result [read -nonewline $fd]
1739 # procedure to construct name for the mage diff file
1740 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1741 return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1744 # Procedure to compare results of two runs of test cases
1745 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1748 # make sure to load diffimage command
1749 uplevel pload VISUALIZATION
1751 # prepare variable (array) for collecting statistics
1752 if { "$_statvar" != "" } {
1753 upvar $_statvar stat
1762 # first check subdirectories
1763 set path1 [file join $dir1 $basename]
1764 set path2 [file join $dir2 $basename]
1765 set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1766 set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1767 if { [llength $list1] >0 || [llength $list2] > 0 } {
1768 _list_diff $list1 $list2 in1 in2 common
1769 if { "$verbose" > 1 } {
1770 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1771 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1773 foreach subdir $common {
1774 if { "$verbose" > 2 } {
1775 _log_and_puts log "Checking [file join $basename $subdir]"
1777 _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1780 # check log files (only if directory has no subdirs)
1781 set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1782 set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1783 _list_diff $list1 $list2 in1 in2 common
1784 if { "$verbose" > 1 } {
1785 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1786 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1788 foreach logfile $common {
1790 set log1 [_read_file [file join $dir1 $basename $logfile]]
1791 set log2 [_read_file [file join $dir2 $basename $logfile]]
1792 set casename [file rootname $logfile]
1794 # check execution statuses
1795 set status1 UNDEFINED
1796 set status2 UNDEFINED
1797 if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1798 ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1799 "$status1" != "$status2" } {
1800 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1802 # if test statuses are different, further comparison makes
1803 # no sense unless explicitly requested
1804 if { "$status" != "all" } {
1808 if { "$status" == "ok" && "$status1" != "OK" } {
1815 if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1816 [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1817 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1818 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1820 # compare CPU times with 10% precision (but not less 0.5 sec)
1821 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1822 _log_and_puts log "CPU [split $basename /] $casename: $cpu1 / $cpu2"
1826 # check memory delta
1829 if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1830 [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1831 set stat(mem1) [expr $stat(mem1) + $mem1]
1832 set stat(mem2) [expr $stat(mem2) + $mem2]
1834 # compare memory usage with 10% precision (but not less 16 KiB)
1835 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1836 _log_and_puts log "MEMORY [split $basename /] $casename: $mem1 / $mem2"
1841 set imglist1 [glob -directory $path1 -types f -tails -nocomplain $casename*.{png,gif}]
1842 set imglist2 [glob -directory $path2 -types f -tails -nocomplain $casename*.{png,gif}]
1843 _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1844 if { "$verbose" > 1 } {
1845 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1846 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1848 foreach imgfile $imgcommon {
1849 # if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1850 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1851 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1852 [file join $dir2 $basename $imgfile] \
1853 0 0 0 $diffile} diff] } {
1854 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1855 file delete -force $diffile ;# clean possible previous result of diffimage
1856 } elseif { $diff != 0 } {
1857 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1859 file delete -force $diffile ;# clean useless artifact of diffimage
1865 if { "$_statvar" == "" } {
1866 _log_and_puts log "Total MEMORY difference: $stat(mem1) / $stat(mem2)"
1867 _log_and_puts log "Total CPU difference: $stat(cpu1) / $stat(cpu2)"
1871 # Auxiliary procedure to save log of results comparison to file
1872 proc _log_html_diff {file log dir1 dir2} {
1873 # create missing directories as needed
1874 catch {file mkdir [file dirname $file]}
1876 # try to open a file
1877 if [catch {set fd [open $file w]} res] {
1878 error "Error saving log file $file: $res"
1882 puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1883 puts $fd "<h1>Comparison of test results:</h1>"
1884 puts $fd "<h2>Version A - $dir1</h2>"
1885 puts $fd "<h2>Version B - $dir2</h2>"
1887 # print log body, trying to add HTML links to script files on lines like
1888 # "Executing <filename>..."
1890 set logpath [file split [file normalize $file]]
1894 if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1895 if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1896 # note: special handler for the case if test grid directoried are compared directly
1899 set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1900 set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1902 set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1903 if { [file exists $difffile] } {
1904 set imgd "<img src=\"[_make_url $file $difffile]\">"
1909 puts $fd "<table><tr><th><abbr title=\"$dir1\">Version A</abbr></th><th><abbr title=\"$dir2\">Version B</abbr></th><th>Different pixels</th></tr>"
1910 puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1913 puts $fd "</pre></body></html>"
1919 # get number of CPUs on the system
1920 proc _get_nb_cpus {} {
1921 global tcl_platform env
1923 if { "$tcl_platform(platform)" == "windows" } {
1924 # on Windows, take the value of the environment variable
1925 if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1926 ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1927 return $env(NUMBER_OF_PROCESSORS)
1929 } elseif { "$tcl_platform(os)" == "Linux" } {
1930 # on Linux, take number of logical processors listed in /proc/cpuinfo
1931 if { [catch {open "/proc/cpuinfo" r} fd] } {
1932 return 0 ;# should never happen, but...
1935 while { [gets $fd line] >= 0 } {
1936 if { [regexp {^processor[ \t]*:} $line] } {
1942 } elseif { "$tcl_platform(os)" == "Darwin" } {
1943 # on MacOS X, call sysctl command
1944 if { ! [catch {exec sysctl hw.ncpu} ret] &&
1945 [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
1950 # if cannot get good value, return 0 as default
1954 # check two files for difference
1955 proc _diff_files {file1 file2} {
1956 set fd1 [open $file1 "r"]
1957 set fd2 [open $file2 "r"]
1961 set nb1 [gets $fd1 line1]
1962 set nb2 [gets $fd2 line2]
1963 if { $nb1 != $nb2 } { set differ t; break }
1964 if { $nb1 < 0 } { break }
1965 if { [string compare $line1 $line2] } {
1976 # Check if file is in DOS encoding.
1977 # This check is done by presence of \r\n combination at the end of the first
1978 # line (i.e. prior to any other \n symbol).
1979 # Note that presence of non-ascii symbols typically used for recognition
1980 # of binary files is not suitable since some IGES and STEP files contain
1981 # non-ascii symbols.
1982 # Special check is added for PNG files which contain \r\n in the beginning.
1983 proc _check_dos_encoding {file} {
1984 set fd [open $file rb]
1986 if { [gets $fd line] && [regexp {.*\r$} $line] &&
1987 ! [regexp {^.PNG} $line] } {
1994 # procedure to recognize format of a data file by its first symbols (for OCCT
1995 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
1996 proc _check_file_format {file} {
1997 set fd [open $file rb]
1998 set line [read $fd 1024]
2002 set ext [file extension $file]
2004 if { [regexp {^DBRep_DrawableShape} $line] } {
2006 if { "$ext" != ".brep" && "$ext" != ".rle" &&
2007 "$ext" != ".draw" && "$ext" != "" } {
2010 } elseif { [regexp {^DrawTrSurf_} $line] } {
2012 if { "$ext" != ".rle" &&
2013 "$ext" != ".draw" && "$ext" != "" } {
2016 } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2018 if { "$ext" != ".step" && "$ext" != ".stp" } {
2021 } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2023 if { "$ext" != ".iges" && "$ext" != ".igs" } {
2026 } elseif { "$ext" == ".igs" } {
2028 } elseif { "$ext" == ".stp" } {
2031 set format [string toupper [string range $ext 1 end]]
2035 puts "$file: Warning: extension ($ext) does not match format ($format)"
2041 # procedure to load file knowing its format
2042 proc load_data_file {file format shape} {
2044 BREP { uplevel restore $file $shape }
2045 DRAW { uplevel restore $file $shape }
2046 IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
2047 STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
2048 STL { pload XSDRAW; uplevel readstl $shape $file }
2049 default { error "Cannot read $format file $file" }
2053 # procedure to get name of temporary directory,
2054 # ensuring it is existing and writeable
2055 proc _get_temp_dir {} {
2056 global env tcl_platform
2058 # check typical environment variables
2059 foreach var {TempDir Temp Tmp} {
2060 # check different case
2061 foreach name [list [string toupper $var] $var [string tolower $var]] {
2062 if { [info exists env($name)] && [file isdirectory $env($name)] &&
2063 [file writable $env($name)] } {
2064 return [regsub -all {\\} $env($name) /]
2069 # check platform-specific locations
2071 if { "$tcl_platform(platform)" == "windows" } {
2072 set paths "c:/TEMP c:/TMP /TEMP /TMP"
2073 if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
2074 set fallback [regsub -all {\\} "$env(HOMEDRIVE)$(HOMEPATH)/tmp" /]
2077 set paths "/tmp /var/tmp /usr/tmp"
2078 if { [info exists env(HOME)] } {
2079 set fallback "$env(HOME)/tmp"
2082 foreach dir $paths {
2083 if { [file isdirectory $dir] && [file writable $dir] } {
2088 # fallback case: use subdir /tmp of home or current dir
2089 file mkdir $fallback
2093 # extract of code from testgrid command used to process jobs running in
2094 # parallel until number of jobs in the queue becomes equal or less than
2096 proc _testgrid_process_jobs {worker {nb_ok 0}} {
2097 # bind local vars to variables of the caller procedure
2100 upvar job_def job_def
2101 upvar nbpooled nbpooled
2102 upvar userbreak userbreak
2103 upvar refresh refresh
2104 upvar refresh_timer refresh_timer
2106 catch {tpool::resume $worker}
2107 while { ! $userbreak && $nbpooled > $nb_ok } {
2108 foreach job [tpool::wait $worker [array names job_def]] {
2109 eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2114 # check for user break
2115 if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2119 # update summary log with requested period
2120 if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2121 _log_summarize $logdir $log
2122 set refresh_timer [clock seconds]
2125 catch {tpool::suspend $worker}
2130 Use: checkcolor x y red green blue
2131 x y - pixel coordinates
2132 red green blue - expected pixel color (values from 0 to 1)
2133 Function check color with tolerance (5x5 area)
2135 # Procedure to check color using command vreadpixel with tolerance
2136 proc checkcolor { coord_x coord_y rd_get gr_get bl_get } {
2137 puts "Coordinate x = $coord_x"
2138 puts "Coordinate y = $coord_y"
2139 puts "RED color of RGB is $rd_get"
2140 puts "GREEN color of RGB is $gr_get"
2141 puts "BLUE color of RGB is $bl_get"
2143 if { $coord_x <= 1 || $coord_y <= 1 } {
2144 puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2149 catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2150 if {"$color" == ""} {
2151 puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2153 set rd [lindex $color 0]
2154 set gr [lindex $color 1]
2155 set bl [lindex $color 2]
2156 set rd_int [expr int($rd * 1.e+05)]
2157 set gr_int [expr int($gr * 1.e+05)]
2158 set bl_int [expr int($bl * 1.e+05)]
2159 set rd_ch [expr int($rd_get * 1.e+05)]
2160 set gr_ch [expr int($gr_get * 1.e+05)]
2161 set bl_ch [expr int($bl_get * 1.e+05)]
2163 if { $rd_ch != 0 } {
2164 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2168 if { $gr_ch != 0 } {
2169 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2173 if { $bl_ch != 0 } {
2174 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2180 if { $tol_rd > 0.2 } {
2181 puts "Warning : RED light of additive color model RGB is invalid"
2184 if { $tol_gr > 0.2 } {
2185 puts "Warning : GREEN light of additive color model RGB is invalid"
2188 if { $tol_bl > 0.2 } {
2189 puts "Warning : BLUE light of additive color model RGB is invalid"
2193 if { $status != 0 } {
2194 puts "Warning : Colors of default coordinate are not equal"
2198 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2199 set info [_checkpoint $coord_x $coord_y $rd_ch $gr_ch $bl_ch]
2200 set stat [lindex $info end]
2201 if { ${stat} != 1 } {
2202 puts "Error : Colors are not equal in default coordinate and in the near coordinates too"
2205 puts "Point with valid color was found"
2213 # Procedure to check color in the point near default coordinate
2214 proc _checkpoint {coord_x coord_y rd_ch gr_ch bl_ch} {
2215 set x_start [expr ${coord_x} - 2]
2216 set y_start [expr ${coord_y} - 2]
2219 while { $mistake != 1 && $i <= 5 } {
2221 while { $mistake != 1 && $j <= 5 } {
2222 set position_x [expr ${x_start} + $j]
2223 set position_y [expr ${y_start} + $i]
2228 catch { [set color "[vreadpixel ${position_x} ${position_y} rgb]"] }
2229 if {"$color" == ""} {
2230 puts "Warning : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2234 set rd [lindex $color 0]
2235 set gr [lindex $color 1]
2236 set bl [lindex $color 2]
2237 set rd_int [expr int($rd * 1.e+05)]
2238 set gr_int [expr int($gr * 1.e+05)]
2239 set bl_int [expr int($bl * 1.e+05)]
2241 if { $rd_ch != 0 } {
2242 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2246 if { $gr_ch != 0 } {
2247 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2251 if { $bl_ch != 0 } {
2252 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2257 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2258 puts "Warning : Point with true color was not found near default coordinates"