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}]"
255 if { [array names ::env OCCT_SHARE_PATH] != "" && "$::env(OCCT_SHARE_PATH)" != ""} {
256 set logdir "$::env(OCCT_SHARE_PATH)/${logdir}"
259 set logdir [file normalize $logdir]
261 if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
262 error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
264 if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
265 error "Error: Cannot create directory \"$logdir\", or it is not writable"
268 # masks for search of test groups, grids, and cases
269 if { ! [info exists groupmask] } { set groupmask * }
270 if { ! [info exists gridmask ] } { set gridmask * }
271 if { ! [info exists casemask ] } { set casemask * }
273 ######################################################
274 # prepare list of tests to be performed
275 ######################################################
277 # list of tests, each defined by a list of:
278 # test scripts directory
279 # group (subfolder) name
280 # grid (subfolder) name
282 # path to test case file
285 # iterate by all script paths
286 foreach dir [lsort -unique [_split_path $env(CSF_TestScriptsPath)]] {
287 # protection against empty paths
288 set dir [string trim $dir]
289 if { $dir == "" } { continue }
291 if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
293 # check that directory exists
294 if { ! [file isdirectory $dir] } {
295 _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
299 # search all directories in the current dir with specified mask
300 if [catch {glob -directory $dir -tail -types d {*}$groupmask} groups] { continue }
303 if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
304 foreach group [lsort -dictionary $groups] {
305 if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
307 # file grids.list must exist: it defines sequence of grids in the group
308 if { ! [file exists $dir/$group/grids.list] } {
309 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
313 # read grids.list file and make a list of grids to be executed
315 set fd [open $dir/$group/grids.list]
317 while { [gets $fd line] >= 0 } {
320 # skip comments and empty lines
321 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
322 if { [string trim $line] == "" } { continue }
324 # get grid id and name
325 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
326 _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
330 # check that grid fits into the specified mask
331 foreach mask $gridmask {
332 if { $mask == $gridid || [string match $mask $grid] } {
333 lappend gridlist $grid
339 # iterate by all grids
340 foreach grid $gridlist {
342 # check if this grid is aliased to another one
343 set griddir $dir/$group/$grid
344 if { [file exists $griddir/cases.list] } {
345 set fd [open $griddir/cases.list]
346 if { [gets $fd line] >= 0 } {
347 set griddir [file normalize $dir/$group/$grid/[string trim $line]]
352 # check if grid directory actually exists
353 if { ! [file isdirectory $griddir] } {
354 _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
358 # create directory for logging test results
359 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
361 # iterate by all tests in the grid directory
362 if { [catch {glob -directory $griddir -type f {*}$casemask} testfiles] } { continue }
363 foreach casefile [lsort -dictionary $testfiles] {
364 # filter out files with reserved names
365 set casename [file tail $casefile]
366 if { $casename == "begin" || $casename == "end" ||
367 $casename == "parse.rules" } {
371 lappend tests_list [list $dir $group $grid $casename $casefile]
376 if { [llength $tests_list] < 1 } {
377 error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
379 puts "Running tests (total [llength $tests_list] test cases)..."
382 ######################################################
384 ######################################################
386 # log command arguments and environment
387 lappend log "Command: testgrid $args"
388 lappend log "Host: [info hostname]"
389 lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
390 catch {lappend log "DRAW build:\n[dversion]" }
391 lappend log "Environment:"
392 foreach envar [lsort [array names env]] {
393 lappend log "$envar=\"$env($envar)\""
397 set refresh_timer [clock seconds]
398 uplevel dchrono _timer reset
399 uplevel dchrono _timer start
401 # if parallel execution is requested, allocate thread pool
402 if { $parallel > 0 } {
403 if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
404 _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
407 set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
408 # suspend the pool until all jobs are posted, to prevent blocking of the process
409 # of starting / processing jobs by running threads
410 catch {tpool::suspend $worker}
411 if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
412 # limit number of jobs in the queue by reasonable value
413 # to prevent slowdown due to unnecessary queue processing
415 set nbpooled_max [expr 10 * $parallel]
416 set nbpooled_ok [expr 5 * $parallel]
422 foreach test_def $tests_list {
423 # check for user break
424 if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
429 set dir [lindex $test_def 0]
430 set group [lindex $test_def 1]
431 set grid [lindex $test_def 2]
432 set casename [lindex $test_def 3]
433 set casefile [lindex $test_def 4]
435 # command to set tests for generation of image in results directory
437 if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
439 # prepare command file for running test case in separate instance of DRAW
440 set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
441 puts $fd_cmd "$imgdir_cmd"
442 puts $fd_cmd "set test_image $casename"
443 puts $fd_cmd "_run_test $dir $group $grid $casefile t"
445 # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
446 # note: this is not needed if echo is set to 1 in call to _run_test above
447 if { ! [catch {dlog get}] } {
448 puts $fd_cmd "puts \[dlog get\]"
450 # else try to use old-style QA_ variables to get more output...
453 set env(QA_print_command) 1
456 # final 'exit' is needed when running on Linux under VirtualGl
460 # commant to run DRAW with a command file;
461 # note that empty string is passed as standard input to avoid possible
462 # hang-ups due to waiting for stdin of the launching process
463 set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
465 # alternative method to run without temporary file; disabled as it needs too many backslashes
467 # set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
468 # _run_test $dir $group $grid $casefile\\\; \
469 # puts \\\[dlog get\\\]\\\; exit"
472 # run test case, either in parallel or sequentially
473 if { $parallel > 0 } {
475 set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
476 set job_def($job) [list $logdir $dir $group $grid $casename]
478 if { $nbpooled > $nbpooled_max } {
479 _testgrid_process_jobs $worker $nbpooled_ok
482 # sequential execution
483 catch {eval $command} output
484 _log_test_case $output $logdir $dir $group $grid $casename log
486 # update summary log with requested period
487 if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
488 # update and dump summary
489 _log_summarize $logdir $log
490 set refresh_timer [clock seconds]
495 # get results of started threads
496 if { $parallel > 0 } {
497 _testgrid_process_jobs $worker
498 # release thread pool
499 if { $nbpooled > 0 } {
500 tpool::cancel $worker [array names job_def]
502 catch {tpool::resume $worker}
503 tpool::release $worker
506 uplevel dchrono _timer stop
507 set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
510 _log_and_puts log "*********** Stopped by user break ***********"
511 set time "${time} \nNote: the process is not finished, stopped by user break!"
514 ######################################################
515 # output summary logs and exit
516 ######################################################
518 _log_summarize $logdir $log $time
519 if { $logdir != "" } {
520 puts "Detailed logs are saved in $logdir"
522 if { $logdir != "" && $xmlfile != "" } {
523 # XML output file is assumed relative to log dir unless it is absolute
524 if { [ file pathtype $xmlfile] == "relative" } {
525 set xmlfile [file normalize $logdir/$xmlfile]
527 _log_xml_summary $logdir $xmlfile $log 0
528 puts "XML summary is saved to $xmlfile"
530 # play sound signal at the end of test
537 # Procedure to regenerate summary log from logs of test cases
539 Regenerate summary log in the test directory from logs of test cases.
540 This can be necessary if test grids are executed separately (e.g. on
541 different stations) or some grids have been re-executed.
542 Use: testsummarize dir
544 proc testsummarize {dir} {
545 global _test_case_regexp
547 if { ! [file isdirectory $dir] } {
548 error "Error: \"$dir\" is not a directory"
551 # get summary statements from all test cases in one log
554 # to avoid huge listing of logs, first find all subdirectories and iterate
555 # by them, parsing log files in each subdirectory independently
556 foreach grid [glob -directory $dir -types d -tails */*] {
557 foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
558 set file [file join $dir $grid $caselog]
560 set fd [open $file r]
561 while { [gets $fd line] >= 0 } {
562 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
563 if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } {
564 puts "Error: $file contains status line for another test case ($line)"
572 if { $nbfound != 1 } {
573 puts "Error: $file contains $nbfound status lines, expected 1"
578 _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
582 # Procedure to compare results of two runs of test cases
584 Compare results of two executions of tests (CPU times, ...)
585 Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
586 Where dir1 and dir2 are directories containing logs of two test runs.
588 -save filename: save resulting log in specified file (default name is
589 <dir1>/diff-<dir2>.log); HTML log is saved with same name
591 -status {same|ok|all}: filter cases for comparing by their status:
592 same - only cases with same status are compared (default)
593 ok - only cases with OK status in both logs are compared
594 all - results are compared regardless of status
596 1 - output only differences
597 2 - output also list of logs and directories present in one of dirs only
598 3 - (default) output also progress messages
599 -highlight_percent value: highlight considerable (>value in %) deviations
600 of CPU and memory (default value is 5%)
602 proc testdiff {dir1 dir2 args} {
603 if { "$dir1" == "$dir2" } {
604 error "Input directories are the same"
607 ######################################################
609 ######################################################
612 set logfile [file join $dir1 "diff-[file tail $dir2].log"]
616 set highlight_percent 5
617 for {set narg 0} {$narg < [llength $args]} {incr narg} {
618 set arg [lindex $args $narg]
621 if { $arg == "-save" } {
623 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
624 set logfile [lindex $args $narg]
626 error "Error: Option -save must be followed by log file name"
632 if { $arg == "-status" } {
634 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
635 set status [lindex $args $narg]
639 if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
640 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
646 if { $arg == "-verbose" } {
648 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
649 set verbose [expr [lindex $args $narg]]
651 error "Error: Option -verbose must be followed by integer verbose level"
657 if { $arg == "-highlight_percent" } {
659 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
660 set highlight_percent [expr [lindex $args $narg]]
662 error "Error: Option -highlight_percent must be followed by integer value"
667 if { [regexp {^-} $arg] } {
668 error "Error: unsupported option \"$arg\""
671 # non-option arguments form a subdirectory path
672 set basename [file join $basename $arg]
675 # run diff procedure (recursive)
676 _test_diff $dir1 $dir2 $basename $status $verbose log
678 # save result to log file
679 if { "$logfile" != "" } {
680 _log_save $logfile [join $log "\n"]
681 _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2 ${highlight_percent}
682 puts "Log is saved to $logfile (and .html)"
688 # Procedure to check data file before adding it to repository
690 Check data file and prepare it for putting to test data files repository.
691 Use: testfile [filelist]
694 - data file (non-binary) is in DOS encoding (CR/LF)
695 - same data file (with same or another name) already exists in the repository
696 - another file with the same name already exists
697 Note that names are assumed to be case-insensitive (for Windows).
699 Unless the file is already in the repository, tries to load it, reports
700 the recognized file format, file size, number of faces and edges in the
701 loaded shape (if any), and makes snapshot (in the temporary directory).
702 Finally it advises whether the file should be put to public section of the
705 proc testfile {filelist} {
708 # check that CSF_TestDataPath is defined
709 if { ! [info exists env(CSF_TestDataPath)] } {
710 error "Environment variable CSF_TestDataPath must be defined!"
713 # build registry of existing data files (name -> path) and (size -> path)
714 puts "Checking available test data files..."
715 foreach dir [_split_path $env(CSF_TestDataPath)] {
716 while {[llength $dir] != 0} {
717 set curr [lindex $dir 0]
718 set dir [lrange $dir 1 end]
719 eval lappend dir [glob -nocomplain -directory $curr -type d *]
720 foreach file [glob -nocomplain -directory $curr -type f *] {
721 set name [file tail $file]
722 set name_lower [string tolower $name]
724 # check that the file is not in DOS encoding
725 if { [_check_dos_encoding $file] } {
726 puts "Warning: file $file is in DOS encoding; was this intended?"
728 _check_file_format $file
730 # check if file with the same name is present twice or more
731 if { [info exists names($name_lower)] } {
732 puts "Error: more than one file with name $name is present in the repository:"
733 if { [_diff_files $file $names($name_lower)] } {
734 puts "(files are different by content)"
736 puts "(files are same by content)"
739 puts "--> $names($name_lower)"
743 # check if file with the same content exists
744 set size [file size $file]
745 if { [info exists sizes($size)] } {
746 foreach other $sizes($size) {
747 if { ! [_diff_files $file $other] } {
748 puts "Warning: two files with the same content found:"
755 # add the file to the registry
756 set names($name_lower) $file
757 lappend sizes($size) $file
761 if { [llength $filelist] <= 0 } { return }
763 # check the new files
765 puts "Checking new file(s)..."
766 foreach file $filelist {
767 # check for DOS encoding
768 if { [_check_dos_encoding $file] } {
769 puts "$file: Warning: DOS encoding detected"
772 set name [file tail $file]
773 set name_lower [string tolower $name]
775 # check for presence of the file with same name
776 if { [info exists names($name_lower)] } {
777 if { [_diff_files $file $names($name_lower)] } {
778 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
780 puts "$file: OK: already in the repository \n--> $names($name_lower)"
785 # check if file with the same content exists
786 set size [file size $file]
787 if { [info exists sizes($size)] } {
789 foreach other $sizes($size) {
790 if { ! [_diff_files $file $other] } {
791 puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
796 if { $found } { continue }
799 # try to read the file
800 set format [_check_file_format $file]
801 if { [catch {uplevel load_data_file $file $format a}] } {
802 puts "$file: Error: Cannot read as $format file"
806 # get number of faces and edges
809 set nbs [uplevel nbshapes a]
810 regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
811 regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
813 # classify; first check file size and number of faces and edges
814 if { $size < 95000 && $faces < 20 && $edges < 100 } {
818 # check if one of names of that file corresponds to typical name for
819 # MDTV bugs or has extension .rle, this should be old model
820 if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
821 [regexp -nocase {[.]rle\y} $name] } {
827 puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
829 set tmpdir [_get_temp_dir]
830 file mkdir $tmpdir/$dir
837 uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
841 puts "Snapshots are saved in subdirectory [_get_temp_dir]"
845 # Procedure to locate data file for test given its name.
846 # The search is performed assuming that the function is called
847 # from the test case script; the search order is:
848 # - subdirectory "data" of the test script (grid) folder
849 # - subdirectories in environment variable CSF_TestDataPath
850 # - subdirectory set by datadir command
851 # If file is not found, raises Tcl error.
852 proc locate_data_file {filename} {
853 global env groupname gridname casename
855 # check if the file is located in the subdirectory data of the script dir
856 set scriptfile [info script]
857 if { $scriptfile != "" } {
858 set path [file join [file dirname $scriptfile] data $filename]
859 if { [file exists $path] } {
860 return [file normalize $path]
864 # check sub-directories in paths indicated by CSF_TestDataPath
865 if { [info exists env(CSF_TestDataPath)] } {
866 foreach dir [_split_path $env(CSF_TestDataPath)] {
867 while {[llength $dir] != 0} {
868 set name [lindex $dir 0]
869 set dir [lrange $dir 1 end]
870 # skip directories starting with dot
871 if { [regexp {^[.]} $name] } { continue }
872 if { [file exists $name/$filename] } {
873 return [file normalize $name/$filename]
875 eval lappend dir [glob -nocomplain -directory $name -type d *]
880 # check current datadir
881 if { [file exists [uplevel datadir]/$filename] } {
882 return [file normalize [uplevel datadir]/$filename]
886 error [join [list "File $filename could not be found" \
887 "(should be in paths indicated by CSF_TestDataPath environment variable, " \
888 "or in subfolder data in the script directory)"] "\n"]
891 # Internal procedure to find test case indicated by group, grid, and test case names;
893 # - dir: path to the base directory of the tests group
894 # - gridname: actual name of the grid
895 # - casefile: path to the test case script
896 # if no such test is found, raises error with appropriate message
897 proc _get_test {group grid casename _dir _gridname _casefile} {
899 upvar $_gridname gridname
900 upvar $_casefile casefile
904 # check that environment variable defining paths to test scripts is defined
905 if { ! [info exists env(CSF_TestScriptsPath)] ||
906 [llength $env(CSF_TestScriptsPath)] <= 0 } {
907 error "Error: Environment variable CSF_TestScriptsPath is not defined"
910 # iterate by all script paths
911 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
912 # protection against empty paths
913 set dir [string trim $dir]
914 if { $dir == "" } { continue }
916 # check that directory exists
917 if { ! [file isdirectory $dir] } {
918 puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
922 # check if test group with given name exists in this dir
923 # if not, continue to the next test dir
924 if { ! [file isdirectory $dir/$group] } { continue }
926 # check that grid with given name (possibly alias) exists; stop otherwise
928 if { ! [file isdirectory $dir/$group/$gridname] } {
929 # check if grid is named by alias rather than by actual name
930 if { [file exists $dir/$group/grids.list] } {
931 set fd [open $dir/$group/grids.list]
932 while { [gets $fd line] >= 0 } {
933 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
934 if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
941 if { ! [file isdirectory $dir/$group/$gridname] } { continue }
943 # get actual file name of the script; stop if it cannot be found
944 set casefile $dir/$group/$gridname/$casename
945 if { ! [file exists $casefile] } {
946 # check if this grid is aliased to another one
947 if { [file exists $dir/$group/$gridname/cases.list] } {
948 set fd [open $dir/$group/$gridname/cases.list]
949 if { [gets $fd line] >= 0 } {
950 set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
955 if { [file exists $casefile] } {
961 # coming here means specified test is not found; report error
962 error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
963 "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
966 # Internal procedure to run test case indicated by base directory,
967 # grid and grid names, and test case file path.
968 # The log can be obtained by command "dlog get".
969 proc _run_test {scriptsdir group gridname casefile echo} {
973 uplevel dchrono _timer reset
974 uplevel dchrono _timer start
975 catch {uplevel meminfo h} membase
977 # enable commands logging; switch to old-style mode if dlog command is not present
979 if { [catch {dlog reset}] } {
986 rename puts puts-saved
988 global _tests_verbose
990 # log only output to stdout and stderr, not to file!
991 if {[llength $args] > 1} {
992 set optarg [lindex $args end-1]
993 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
994 dlog add [lindex $args end]
996 eval puts-saved $args
999 dlog add [lindex $args end]
1004 # evaluate test case
1007 # set variables identifying test case
1008 uplevel set casename [file tail $casefile]
1009 uplevel set groupname $group
1010 uplevel set gridname $gridname
1011 uplevel set dirname $scriptsdir
1013 # set path for saving of log and images (if not yet set) to temp dir
1014 if { ! [uplevel info exists imagedir] } {
1015 uplevel set test_image \$casename
1017 # create subdirectory in temp named after group and grid with timestamp
1018 set rootlogdir [_get_temp_dir]
1020 set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
1021 set imagedir [file normalize ${rootlogdir}/$imagedir]
1023 if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1024 ! [catch {glob -directory $imagedir *}] } {
1025 # puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
1026 set imagedir $rootlogdir
1029 uplevel set imagedir \"$imagedir\"
1033 # execute test scripts
1034 if { [file exists $scriptsdir/$group/begin] } {
1035 puts "Executing $scriptsdir/$group/begin..."; flush stdout
1036 uplevel source $scriptsdir/$group/begin
1038 if { [file exists $scriptsdir/$group/$gridname/begin] } {
1039 puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1040 uplevel source $scriptsdir/$group/$gridname/begin
1043 puts "Executing $casefile..."; flush stdout
1044 uplevel source $casefile
1046 if { [file exists $scriptsdir/$group/$gridname/end] } {
1047 puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1048 uplevel source $scriptsdir/$group/$gridname/end
1050 if { [file exists $scriptsdir/$group/end] } {
1051 puts "Executing $scriptsdir/$group/end..."; flush stdout
1052 uplevel source $scriptsdir/$group/end
1055 puts "Tcl Exception: $res"
1059 if { $dlog_exists } {
1064 rename puts-saved puts
1069 # stop cpulimit killer if armed by the test
1072 # add memory and timing info
1074 if { ! [catch {uplevel meminfo h} memuse] } {
1075 append stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
1077 uplevel dchrono _timer stop
1078 set time [uplevel dchrono _timer show]
1079 if { [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu_usr] } {
1080 append stats "TOTAL CPU TIME: $cpu_usr sec\n"
1082 if { $dlog_exists && ! $echo } {
1089 uplevel unset casename groupname gridname dirname
1090 if { $tmp_imagedir } { uplevel unset imagedir test_image }
1093 # Internal procedure to check log of test execution and decide if it passed or failed
1094 proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
1096 if { $_summary != "" } { upvar $_summary summary }
1097 if { $_html_log != "" } { upvar $_html_log html_log }
1104 # load definition of 'bad words' indicating test failure
1105 # note that rules are loaded in the order of decreasing priority (grid - group - common),
1106 # thus grid rules will override group ones
1108 foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
1109 if [catch {set fd [open $rulesfile r]}] { continue }
1110 while { [gets $fd line] >= 0 } {
1111 # skip comments and empty lines
1112 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
1113 if { [string trim $line] == "" } { continue }
1115 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } {
1116 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1119 set status [string trim $status]
1120 if { $comment != "" } { append status " ([string trim $comment])" }
1121 set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1122 lappend badwords [list $status $rexp]
1126 if { [llength $badwords] <= 0 } {
1127 puts "Warning: no definition of error indicators found (check files parse.rules)"
1130 # analyse log line-by-line
1131 set todos {} ;# TODO statements
1132 set requs {} ;# REQUIRED statements
1133 set todo_incomplete -1
1135 foreach line [split $log "\n"] {
1136 # check if line defines specific treatment of some messages
1137 if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1138 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1139 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1140 lappend html_log [_html_highlight IGNORE $line]
1141 continue ;# TODO statement is for another platform
1144 # record TODOs that mark unstable cases
1145 if { [regexp {[\?]} $platforms] } {
1146 set todos_unstable([llength $todos]) 1
1149 # convert legacy regexps from Perl to Tcl style
1150 set pattern [regsub -all {\\b} [string trim $pattern] {\\y}]
1152 # special case: TODO TEST INCOMPLETE
1153 if { [string trim $pattern] == "TEST INCOMPLETE" } {
1154 set todo_incomplete [llength $todos]
1157 lappend todos [list $pattern [llength $html_log] $line]
1158 lappend html_log [_html_highlight BAD $line]
1161 if [regexp -nocase {^[ \s]*REQUIRED ([^:]*):[ \s]*(.*)$} $line res platforms pattern] {
1162 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1163 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1164 lappend html_log [_html_highlight IGNORE $line]
1165 continue ;# REQUIRED statement is for another platform
1167 lappend requs [list $pattern [llength $html_log] $line]
1168 lappend html_log [_html_highlight OK $line]
1172 # check for presence of required messages
1174 for {set i 0} {$i < [llength $requs]} {incr i} {
1175 set pattern [lindex $requs $i 0]
1176 if { [regexp $pattern $line] } {
1177 incr required_count($i)
1178 lappend html_log [_html_highlight OK $line]
1187 # check for presence of messages indicating test result
1188 foreach bw $badwords {
1189 if { [regexp [lindex $bw 1] $line] } {
1190 # check if this is known bad case
1192 for {set i 0} {$i < [llength $todos]} {incr i} {
1193 set pattern [lindex $todos $i 0]
1194 if { [regexp $pattern $line] } {
1197 lappend html_log [_html_highlight BAD $line]
1202 # if it is not in todo, define status
1203 if { ! $is_known } {
1204 set stat [lindex $bw 0 0]
1206 lappend errors_log $line
1208 lappend html_log [_html_highlight $stat $line]
1209 if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1210 set status [lindex $bw 0]
1217 if { ! $ismarked } {
1218 lappend html_log $line
1222 # check for presence of TEST COMPLETED statement
1223 if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1224 # check whether absence of TEST COMPLETED is known problem
1225 if { $todo_incomplete >= 0 } {
1226 incr todo_count($todo_incomplete)
1228 set status "FAILED (no final message is found)"
1232 # report test as failed if it doesn't contain required pattern
1233 if { $status == "" } {
1234 for {set i 0} {$i < [llength $requs]} {incr i} {
1235 if { ! [info exists required_count($i)] } {
1236 set linenum [lindex $requs $i 1]
1237 set html_log [lreplace $html_log $linenum $linenum [_html_highlight FAILED [lindex $requs $i 2]]]
1238 set status "FAILED (REQUIRED statement no. [expr $i + 1] is not found)"
1243 # check declared bad cases and diagnose possible improvement
1244 # (bad case declared but not detected).
1245 # Note that absence of the problem marked by TODO with question mark
1246 # (unstable) is not reported as improvement.
1247 if { $status == "" } {
1248 for {set i 0} {$i < [llength $todos]} {incr i} {
1249 if { ! [info exists todos_unstable($i)] &&
1250 (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1251 set linenum [lindex $todos $i 1]
1252 set html_log [lreplace $html_log $linenum $linenum [_html_highlight IMPROVEMENT [lindex $todos $i 2]]]
1253 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1259 # report test as known bad if at least one of expected problems is found
1260 if { $status == "" && [llength [array names todo_count]] > 0 } {
1261 set status "BAD (known problem)"
1265 if { $status == "" } {set status "OK" }
1268 set status "FAILED ($res)"
1272 _log_and_puts summary "CASE $group $gridname $casename: $status"
1273 set summary [join $summary "\n"]
1275 foreach error $errors_log {
1276 _log_and_puts summary " $error"
1279 set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1282 # Auxiliary procedure putting message to both cout and log variable (list)
1283 proc _log_and_puts {logvar message} {
1284 if { $logvar != "" } {
1286 lappend log $message
1291 # Auxiliary procedure to log result on single test case
1292 proc _log_test_case {output logdir dir group grid casename logvar} {
1295 # check result and make HTML log
1296 _check_log $dir $group $grid $casename $show_errors $output summary html_log
1297 lappend log $summary
1300 if { $logdir != "" } {
1301 _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1302 _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1306 # Auxiliary procedure to save log to file
1307 proc _log_save {file log {title {}}} {
1308 # create missing directories as needed
1309 catch {file mkdir [file dirname $file]}
1311 # try to open a file
1312 if [catch {set fd [open $file w]} res] {
1313 error "Error saving log file $file: $res"
1316 # dump log and close
1323 # Auxiliary procedure to make a (relative if possible) URL to a file for
1324 # inclusion a reference in HTML log
1325 proc _make_url {htmldir file} {
1326 set htmlpath [file split [file normalize $htmldir]]
1327 set filepath [file split [file normalize $file]]
1328 for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1329 if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1330 if { $i == 0 } { break }
1331 return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1335 # if relative path could not be made, return full file URL
1336 return "file://[file normalize $file]"
1339 # Auxiliary procedure to save log to file
1340 proc _log_html {file log {title {}}} {
1341 # create missing directories as needed
1342 catch {file mkdir [file dirname $file]}
1344 # try to open a file
1345 if [catch {set fd [open $file w]} res] {
1346 error "Error saving log file $file: $res"
1350 puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1352 # add images if present; these should have either PNG, GIF, or JPG extension,
1353 # and start with name of the test script, with optional suffix separated
1354 # by underscore or dash
1355 set imgbasename [file rootname [file tail $file]]
1356 foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails \
1357 ${imgbasename}.gif ${imgbasename}.png ${imgbasename}.jpg \
1358 ${imgbasename}_*.gif ${imgbasename}_*.png ${imgbasename}_*.jpg \
1359 ${imgbasename}-*.gif ${imgbasename}-*.png ${imgbasename}-*.jpg]] {
1360 puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1363 # print log body, trying to add HTML links to script files on lines like
1364 # "Executing <filename>..."
1366 foreach line [split $log "\n"] {
1367 if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1368 [file exists $script] } {
1369 set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1373 puts $fd "</pre></body></html>"
1379 # Auxiliary method to make text with HTML highlighting according to status
1380 proc _html_color {status} {
1381 # choose a color for the cell according to result
1382 if { $status == "OK" } {
1384 } elseif { [regexp -nocase {^FAIL} $status] } {
1386 } elseif { [regexp -nocase {^BAD} $status] } {
1388 } elseif { [regexp -nocase {^IMP} $status] } {
1390 } elseif { [regexp -nocase {^SKIP} $status] } {
1392 } elseif { [regexp -nocase {^IGNOR} $status] } {
1395 puts "Warning: no color defined for status $status, using red as if FAILED"
1400 # Format text line in HTML to be colored according to the status
1401 proc _html_highlight {status line} {
1402 return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1405 # Internal procedure to generate HTML page presenting log of the tests
1406 # execution in tabular form, with links to reports on individual cases
1407 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1408 global _test_case_regexp
1410 # create missing directories as needed
1413 # try to open a file and start HTML
1414 if [catch {set fd [open $logdir/summary.html w]} res] {
1415 error "Error creating log file: $res"
1418 # write HRML header, including command to refresh log if still in progress
1419 puts $fd "<html><head>"
1420 puts $fd "<title>Tests summary</title>"
1421 if { $total_time == "" } {
1422 puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1424 puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1425 puts $fd "</head><body>"
1428 set legend(OK) "Test passed OK"
1429 set legend(FAILED) "Test failed (regression)"
1430 set legend(BAD) "Known problem"
1431 set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1432 set legend(SKIPPED) "Test skipped due to lack of data file"
1433 puts $fd "<h1>Summary</h1><table>"
1434 foreach nbstat $totals {
1435 set status [lindex $nbstat 1]
1436 if { [info exists legend($status)] } {
1437 set comment $legend($status)
1439 set comment "User-defined status"
1441 puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1445 # time stamp and elapsed time info
1446 if { $total_time != "" } {
1447 puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1448 puts $fd [join [split $total_time "\n"] "<p>"]
1450 puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1453 # print regressions and improvements
1454 foreach featured [list $regressions $improvements] {
1455 if { [llength $featured] <= 1 } { continue }
1456 set status [string trim [lindex $featured 0] { :}]
1457 puts $fd "<h2>$status</h2>"
1460 foreach test [lrange $featured 1 end] {
1461 if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1463 set name "Error building short list; check details"
1465 if { $gg != $groupgrid } {
1466 if { $groupgrid != "" } { puts $fd "</tr>" }
1468 puts $fd "<tr><td>$gg</td>"
1470 puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1472 if { $groupgrid != "" } { puts $fd "</tr>" }
1476 # put detailed log with TOC
1477 puts $fd "<hr><h1>Details</h1>"
1478 puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1480 # process log line-by-line
1484 foreach line [lsort -dictionary $log] {
1485 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1486 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1491 if { $grp != $group } {
1492 if { $letter != "" } { lappend body "</tr></table>" }
1496 puts $fd "<a href=\"#$group\">$group</a><br>"
1497 lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1501 if { $grd != $grid } {
1502 if { $letter != "" } { lappend body "</tr></table>" }
1505 puts $fd " <a href=\"#$group-$grid\">$grid</a><br>"
1506 lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1509 # check if test case name is <letter><digit>;
1510 # if not, set alnum to period "." to recognize non-standard test name
1511 if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1512 ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1516 # start new row when letter changes or for non-standard names
1517 if { $alnum != $letter || $alnum == "." } {
1518 if { $letter != "" } {
1519 lappend body "</tr><tr>"
1521 lappend body "<table><tr>"
1526 lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1528 puts $fd "</div>\n[join $body "\n"]</tr></table>"
1530 # add remaining lines of log as plain text
1531 puts $fd "<h2>Plain text messages</h2>\n<pre>"
1533 if { ! [regexp $_test_case_regexp $line] } {
1539 # close file and exit
1545 # Procedure to dump summary logs of tests
1546 proc _log_summarize {logdir log {total_time {}}} {
1548 # sort log records alphabetically to have the same behavior on Linux and Windows
1549 # (also needed if tests are run in parallel)
1550 set loglist [lsort -dictionary $log]
1552 # classify test cases by status
1553 foreach line $loglist {
1554 if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1555 lappend stat($status) $caseid
1559 set improvements {Improvements:}
1560 set regressions {Failed:}
1561 if { [info exists stat] } {
1562 foreach status [lsort [array names stat]] {
1563 lappend totals [list [llength $stat($status)] $status]
1565 # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1566 if { [regexp -nocase {^IMP} $status] } {
1567 eval lappend improvements $stat($status)
1568 } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1569 eval lappend regressions $stat($status)
1574 # if time is specified, add totals
1575 if { $total_time != "" } {
1576 if { [llength $improvements] > 1 } {
1577 _log_and_puts log [join $improvements "\n "]
1579 if { [llength $regressions] > 1 } {
1580 _log_and_puts log [join $regressions "\n "]
1582 if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1583 _log_and_puts log "No regressions"
1585 _log_and_puts log "Total cases: [join $totals {, }]"
1586 _log_and_puts log $total_time
1590 if { $logdir != "" } {
1591 _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1592 _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1598 # Internal procedure to generate XML log in JUnit style, for further
1599 # consumption by Jenkins or similar systems.
1601 # The output is intended to conform to XML schema supported by Jenkins found at
1602 # 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
1604 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1605 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1606 proc _log_xml_summary {logdir filename log include_cout} {
1607 global _test_case_regexp
1609 catch {file mkdir [file dirname $filename]}
1611 # try to open a file and start XML
1612 if [catch {set fd [open $filename w]} res] {
1613 error "Error creating XML summary file $filename: $res"
1615 puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1616 puts $fd "<testsuites>"
1618 # prototype for command to generate test suite tag
1619 set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1620 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"}
1622 # sort log and process it line-by-line
1624 foreach line [lsort -dictionary $log] {
1625 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1626 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1629 set message [string trim $message " \t\r\n()"]
1631 # start new testsuite for each grid
1632 if { $grp != $group || $grd != $grid } {
1634 # write previous test suite
1635 if [info exists testcases] { eval $cmd_testsuite }
1650 # parse test log and get its CPU time
1653 if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } {
1654 puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1656 while { [gets $fdlog logline] >= 0 } {
1657 if { $include_cout } {
1658 append testout "$logline\n"
1660 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1661 set add_cpu " time=\"$cpu\""
1662 set time [expr $time + $cpu]
1667 if { ! $include_cout } {
1668 set testout "$line\n"
1671 # record test case with its output and status
1672 # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1673 append testcases "\n <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1674 append testcases "\n <system-out>\n$testout </system-out>"
1675 if { $result != "OK" } {
1676 if { [regexp -nocase {^SKIP} $result] } {
1678 append testcases "\n <error name=\"$result\" message=\"$message\"/>"
1679 } elseif { [regexp -nocase {^BAD} $result] } {
1681 append testcases "\n <skipped>$message</skipped>"
1684 append testcases "\n <failure name=\"$result\" message=\"$message\"/>"
1687 append testcases "\n </testcase>"
1690 # write last test suite
1691 if [info exists testcases] { eval $cmd_testsuite }
1694 puts $fd "</testsuites>"
1699 # define custom platform name
1700 proc _tests_platform_def {} {
1701 global env tcl_platform
1703 if [info exists env(os_type)] { return }
1704 set env(os_type) $tcl_platform(platform)
1705 if { $tcl_platform(os) == "Linux" } {
1706 set env(os_type) Linux
1708 if { $tcl_platform(os) == "Darwin" } {
1709 set env(os_type) MacOS
1714 # Auxiliary procedure to split path specification (usually defined by
1715 # environment variable) into list of directories or files
1716 proc _split_path {pathspec} {
1719 # first replace all \ (which might occur on Windows) by /
1720 regsub -all "\\\\" $pathspec "/" pathspec
1722 # split path by platform-specific separator
1723 return [split $pathspec [_path_separator]]
1726 # Auxiliary procedure to define platform-specific separator for directories in
1727 # path specification
1728 proc _path_separator {} {
1731 # split path by platform-specific separator
1732 if { $tcl_platform(platform) == "windows" } {
1739 # Procedure to make a diff and common of two lists
1740 proc _list_diff {list1 list2 _in1 _in2 _common} {
1743 upvar $_common common
1748 foreach item $list1 {
1749 if { [lsearch -exact $list2 $item] >= 0 } {
1750 lappend common $item
1755 foreach item $list2 {
1756 if { [lsearch -exact $common $item] < 0 } {
1763 # procedure to load a file to Tcl string
1764 proc _read_file {filename} {
1765 set fd [open $filename r]
1766 set result [read -nonewline $fd]
1771 # procedure to construct name for the mage diff file
1772 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1773 return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1776 # auxiliary procedure to produce string comparing two values
1777 proc _diff_show_ratio {value1 value2} {
1778 return "$value1 / $value2 \[[format "%+5.2f%%" [expr 100 * ($value1 - $value2) / double($value2)]]\]"
1781 # Procedure to compare results of two runs of test cases
1782 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1785 # make sure to load diffimage command
1786 uplevel pload VISUALIZATION
1788 # prepare variable (array) for collecting statistics
1789 if { "$_statvar" != "" } {
1790 upvar $_statvar stat
1799 # first check subdirectories
1800 set path1 [file join $dir1 $basename]
1801 set path2 [file join $dir2 $basename]
1802 set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1803 set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1804 if { [llength $list1] >0 || [llength $list2] > 0 } {
1805 _list_diff $list1 $list2 in1 in2 common
1806 if { "$verbose" > 1 } {
1807 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1808 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1810 foreach subdir $common {
1811 if { "$verbose" > 2 } {
1812 _log_and_puts log "Checking [file join $basename $subdir]"
1814 _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1817 # check log files (only if directory has no subdirs)
1818 set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1819 set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1820 _list_diff $list1 $list2 in1 in2 common
1821 if { "$verbose" > 1 } {
1822 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1823 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1829 foreach logfile $common {
1831 set log1 [_read_file [file join $dir1 $basename $logfile]]
1832 set log2 [_read_file [file join $dir2 $basename $logfile]]
1833 set casename [file rootname $logfile]
1835 # check execution statuses
1836 set status1 UNDEFINED
1837 set status2 UNDEFINED
1838 if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1839 ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1840 "$status1" != "$status2" } {
1841 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1843 # if test statuses are different, further comparison makes
1844 # no sense unless explicitly requested
1845 if { "$status" != "all" } {
1849 if { "$status" == "ok" && "$status1" != "OK" } {
1856 if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1857 [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1858 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1859 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1860 set gcpu1 [expr $gcpu1 + $cpu1]
1861 set gcpu2 [expr $gcpu2 + $cpu2]
1863 # compare CPU times with 10% precision (but not less 0.5 sec)
1864 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1865 _log_and_puts log "CPU [split $basename /] $casename: [_diff_show_ratio $cpu1 $cpu2]"
1869 # check memory delta
1872 if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1873 [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1874 set stat(mem1) [expr $stat(mem1) + $mem1]
1875 set stat(mem2) [expr $stat(mem2) + $mem2]
1876 set gmem1 [expr $gmem1 + $mem1]
1877 set gmem2 [expr $gmem2 + $mem2]
1879 # compare memory usage with 10% precision (but not less 16 KiB)
1880 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1881 _log_and_puts log "MEMORY [split $basename /] $casename: [_diff_show_ratio $mem1 $mem2]"
1886 set imglist1 [glob -directory $path1 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1887 set imglist2 [glob -directory $path2 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1888 _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1889 if { "$verbose" > 1 } {
1890 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1891 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1893 foreach imgfile $imgcommon {
1894 # if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1895 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1896 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1897 [file join $dir2 $basename $imgfile] \
1898 0 0 0 $diffile} diff] } {
1899 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1900 file delete -force $diffile ;# clean possible previous result of diffimage
1901 } elseif { $diff != 0 } {
1902 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1904 file delete -force $diffile ;# clean useless artifact of diffimage
1909 # report CPU and memory difference in group if it is greater than 10%
1910 if { [expr abs ($gcpu1 - $gcpu2) > 0.5 + 0.005 * abs ($gcpu1 + $gcpu2)] } {
1911 _log_and_puts log "CPU [split $basename /]: [_diff_show_ratio $gcpu1 $gcpu2]"
1913 if { [expr abs ($gmem1 - $gmem2) > 16 + 0.005 * abs ($gmem1 + $gmem2)] } {
1914 _log_and_puts log "MEMORY [split $basename /]: [_diff_show_ratio $gmem1 $gmem2]"
1918 if { "$_statvar" == "" } {
1919 _log_and_puts log "Total MEMORY difference: [_diff_show_ratio $stat(mem1) $stat(mem2)]"
1920 _log_and_puts log "Total CPU difference: [_diff_show_ratio $stat(cpu1) $stat(cpu2)]"
1924 # Auxiliary procedure to save log of results comparison to file
1925 proc _log_html_diff {file log dir1 dir2 highlight_percent} {
1926 # create missing directories as needed
1927 catch {file mkdir [file dirname $file]}
1929 # try to open a file
1930 if [catch {set fd [open $file w]} res] {
1931 error "Error saving log file $file: $res"
1935 puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1936 puts $fd "<h1>Comparison of test results:</h1>"
1937 puts $fd "<h2>Version A - $dir1</h2>"
1938 puts $fd "<h2>Version B - $dir2</h2>"
1940 # print log body, trying to add HTML links to script files on lines like
1941 # "Executing <filename>..."
1943 set logpath [file split [file normalize $file]]
1945 # put a line; highlight considerable (> ${highlight_percent}%) deviations of CPU and memory
1946 if { [regexp "\[\\\[](\[0-9.e+-]+)%\[\]]" $line res value] &&
1947 [expr abs($value)] > ${highlight_percent} } {
1948 puts $fd "<table><tr><td bgcolor=\"[expr $value > 0 ? \"red\" : \"lightgreen\"]\">$line</td></tr></table>"
1954 if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1955 if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1956 # note: special handler for the case if test grid directoried are compared directly
1959 set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1960 set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1962 set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1963 if { [file exists $difffile] } {
1964 set imgd "<img src=\"[_make_url $file $difffile]\">"
1969 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>"
1970 puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1973 puts $fd "</pre></body></html>"
1979 # get number of CPUs on the system
1980 proc _get_nb_cpus {} {
1981 global tcl_platform env
1983 if { "$tcl_platform(platform)" == "windows" } {
1984 # on Windows, take the value of the environment variable
1985 if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1986 ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1987 return $env(NUMBER_OF_PROCESSORS)
1989 } elseif { "$tcl_platform(os)" == "Linux" } {
1990 # on Linux, take number of logical processors listed in /proc/cpuinfo
1991 if { [catch {open "/proc/cpuinfo" r} fd] } {
1992 return 0 ;# should never happen, but...
1995 while { [gets $fd line] >= 0 } {
1996 if { [regexp {^processor[ \t]*:} $line] } {
2002 } elseif { "$tcl_platform(os)" == "Darwin" } {
2003 # on MacOS X, call sysctl command
2004 if { ! [catch {exec sysctl hw.ncpu} ret] &&
2005 [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
2010 # if cannot get good value, return 0 as default
2014 # check two files for difference
2015 proc _diff_files {file1 file2} {
2016 set fd1 [open $file1 "r"]
2017 set fd2 [open $file2 "r"]
2021 set nb1 [gets $fd1 line1]
2022 set nb2 [gets $fd2 line2]
2023 if { $nb1 != $nb2 } { set differ t; break }
2024 if { $nb1 < 0 } { break }
2025 if { [string compare $line1 $line2] } {
2036 # Check if file is in DOS encoding.
2037 # This check is done by presence of \r\n combination at the end of the first
2038 # line (i.e. prior to any other \n symbol).
2039 # Note that presence of non-ascii symbols typically used for recognition
2040 # of binary files is not suitable since some IGES and STEP files contain
2041 # non-ascii symbols.
2042 # Special check is added for PNG files which contain \r\n in the beginning.
2043 proc _check_dos_encoding {file} {
2044 set fd [open $file rb]
2046 if { [gets $fd line] && [regexp {.*\r$} $line] &&
2047 ! [regexp {^.PNG} $line] } {
2054 # procedure to recognize format of a data file by its first symbols (for OCCT
2055 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
2056 proc _check_file_format {file} {
2057 set fd [open $file rb]
2058 set line [read $fd 1024]
2062 set ext [file extension $file]
2064 if { [regexp {^DBRep_DrawableShape} $line] } {
2066 if { "$ext" != ".brep" && "$ext" != ".rle" &&
2067 "$ext" != ".draw" && "$ext" != "" } {
2070 } elseif { [regexp {^DrawTrSurf_} $line] } {
2072 if { "$ext" != ".rle" &&
2073 "$ext" != ".draw" && "$ext" != "" } {
2076 } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2078 if { "$ext" != ".step" && "$ext" != ".stp" } {
2081 } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2083 if { "$ext" != ".iges" && "$ext" != ".igs" } {
2086 } elseif { "$ext" == ".igs" } {
2088 } elseif { "$ext" == ".stp" } {
2091 set format [string toupper [string range $ext 1 end]]
2095 puts "$file: Warning: extension ($ext) does not match format ($format)"
2101 # procedure to load file knowing its format
2102 proc load_data_file {file format shape} {
2104 BREP { uplevel restore $file $shape }
2105 DRAW { uplevel restore $file $shape }
2106 IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
2107 STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
2108 STL { pload XSDRAW; uplevel readstl $shape $file }
2109 default { error "Cannot read $format file $file" }
2113 # procedure to get name of temporary directory,
2114 # ensuring it is existing and writeable
2115 proc _get_temp_dir {} {
2116 global env tcl_platform
2118 # check typical environment variables
2119 foreach var {TempDir Temp Tmp} {
2120 # check different case
2121 foreach name [list [string toupper $var] $var [string tolower $var]] {
2122 if { [info exists env($name)] && [file isdirectory $env($name)] &&
2123 [file writable $env($name)] } {
2124 return [regsub -all {\\} $env($name) /]
2129 # check platform-specific locations
2131 if { "$tcl_platform(platform)" == "windows" } {
2132 set paths "c:/TEMP c:/TMP /TEMP /TMP"
2133 if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
2134 set fallback [regsub -all {\\} "$env(HOMEDRIVE)$env(HOMEPATH)/tmp" /]
2137 set paths "/tmp /var/tmp /usr/tmp"
2138 if { [info exists env(HOME)] } {
2139 set fallback "$env(HOME)/tmp"
2142 foreach dir $paths {
2143 if { [file isdirectory $dir] && [file writable $dir] } {
2148 # fallback case: use subdir /tmp of home or current dir
2149 file mkdir $fallback
2153 # extract of code from testgrid command used to process jobs running in
2154 # parallel until number of jobs in the queue becomes equal or less than
2156 proc _testgrid_process_jobs {worker {nb_ok 0}} {
2157 # bind local vars to variables of the caller procedure
2160 upvar job_def job_def
2161 upvar nbpooled nbpooled
2162 upvar userbreak userbreak
2163 upvar refresh refresh
2164 upvar refresh_timer refresh_timer
2166 catch {tpool::resume $worker}
2167 while { ! $userbreak && $nbpooled > $nb_ok } {
2168 foreach job [tpool::wait $worker [array names job_def]] {
2169 eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2174 # check for user break
2175 if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2179 # update summary log with requested period
2180 if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2181 _log_summarize $logdir $log
2182 set refresh_timer [clock seconds]
2185 catch {tpool::suspend $worker}
2190 Use: checkcolor x y red green blue
2191 x y - pixel coordinates
2192 red green blue - expected pixel color (values from 0 to 1)
2193 Function check color with tolerance (5x5 area)
2195 # Procedure to check color using command vreadpixel with tolerance
2196 proc checkcolor { coord_x coord_y rd_get gr_get bl_get } {
2197 puts "Coordinate x = $coord_x"
2198 puts "Coordinate y = $coord_y"
2199 puts "RED color of RGB is $rd_get"
2200 puts "GREEN color of RGB is $gr_get"
2201 puts "BLUE color of RGB is $bl_get"
2203 if { $coord_x <= 1 || $coord_y <= 1 } {
2204 puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2209 catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2210 if {"$color" == ""} {
2211 puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2213 set rd [lindex $color 0]
2214 set gr [lindex $color 1]
2215 set bl [lindex $color 2]
2216 set rd_int [expr int($rd * 1.e+05)]
2217 set gr_int [expr int($gr * 1.e+05)]
2218 set bl_int [expr int($bl * 1.e+05)]
2219 set rd_ch [expr int($rd_get * 1.e+05)]
2220 set gr_ch [expr int($gr_get * 1.e+05)]
2221 set bl_ch [expr int($bl_get * 1.e+05)]
2223 if { $rd_ch != 0 } {
2224 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2228 if { $gr_ch != 0 } {
2229 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2233 if { $bl_ch != 0 } {
2234 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2240 if { $tol_rd > 0.2 } {
2241 puts "Warning : RED light of additive color model RGB is invalid"
2244 if { $tol_gr > 0.2 } {
2245 puts "Warning : GREEN light of additive color model RGB is invalid"
2248 if { $tol_bl > 0.2 } {
2249 puts "Warning : BLUE light of additive color model RGB is invalid"
2253 if { $status != 0 } {
2254 puts "Warning : Colors of default coordinate are not equal"
2258 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2259 set info [_checkpoint $coord_x $coord_y $rd_ch $gr_ch $bl_ch]
2260 set stat [lindex $info end]
2261 if { ${stat} != 1 } {
2262 puts "Error : Colors are not equal in default coordinate and in the near coordinates too"
2265 puts "Point with valid color was found"
2273 # Procedure to check color in the point near default coordinate
2274 proc _checkpoint {coord_x coord_y rd_ch gr_ch bl_ch} {
2275 set x_start [expr ${coord_x} - 2]
2276 set y_start [expr ${coord_y} - 2]
2279 while { $mistake != 1 && $i <= 5 } {
2281 while { $mistake != 1 && $j <= 5 } {
2282 set position_x [expr ${x_start} + $j]
2283 set position_y [expr ${y_start} + $i]
2288 catch { [set color "[vreadpixel ${position_x} ${position_y} rgb]"] }
2289 if {"$color" == ""} {
2290 puts "Warning : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2294 set rd [lindex $color 0]
2295 set gr [lindex $color 1]
2296 set bl [lindex $color 2]
2297 set rd_int [expr int($rd * 1.e+05)]
2298 set gr_int [expr int($gr * 1.e+05)]
2299 set bl_int [expr int($bl * 1.e+05)]
2301 if { $rd_ch != 0 } {
2302 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2306 if { $gr_ch != 0 } {
2307 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2311 if { $bl_ch != 0 } {
2312 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2317 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2318 puts "Warning : Point with true color was not found near default coordinates"