0023905: Clean obsolete test commands
[occt.git] / src / DrawResources / TestCommands.tcl
1 # Copyright (c) 2012 OPEN CASCADE SAS
2 #
3 # The content of this file is subject to the Open CASCADE Technology Public
4 # License Version 6.5 (the "License"). You may not use the content of this file
5 # except in compliance with the License. Please obtain a copy of the License
6 # at http://www.opencascade.org and read it completely before using this file.
7 #
8 # The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
9 # main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
10 #
11 # The Original Code and all software distributed under the License is
12 # distributed on an "AS IS" basis, without warranty of any kind, and the
13 # Initial Developer hereby disclaims all such warranties, including without
14 # limitation, any warranties of merchantability, fitness for a particular
15 # purpose or non-infringement. Please see the License for the specific terms
16 # and conditions governing the rights and limitations under the License.
17
18 ############################################################################
19 # This file defines scripts for execution of OCCT tests.
20 # It should be loaded automatically when DRAW is started, and provides
21 # top-level commands starting with 'test'. Type 'help test' to get their
22 # synopsys.
23 # See OCCT Tests User Guide for description of the test system.
24 #
25 # Note: procedures with names starting with underscore are for internal use 
26 # inside the test system.
27 ############################################################################
28
29 # Default verbose level for command _run_test
30 set _tests_verbose 0
31
32 # regexp for parsing test case results in summary log
33 set _test_case_regexp {^CASE\s+([\w.-]+)\s+([\w.-]+)\s+([\w.-]+)\s*:\s*([\w]+)(.*)}
34
35 # Basic command to run indicated test case in DRAW
36 help test {
37   Run specified test case
38   Use: test group grid casename [echo=0]
39   - If echo is set to 0 (default), log is stored in memory and only summary
40     is output (the log can be obtained with command "dlog get")
41   - If echo is set to 1 or "-echo", all commands and results are echoed 
42     immediately, but log is not saved and summary is not produced
43 }
44 proc test {group grid casename {echo 0}} {
45     # get test case paths (will raise error if input is invalid)
46     _get_test $group $grid $casename dir gridname casefile
47
48     # if echo specified as "-echo", convert it to bool
49     if { "$echo" == "-echo" } { set echo t }
50
51     # run test
52     uplevel _run_test $dir $group $gridname $casefile $echo 
53
54     # check log
55     if { ! $echo } {
56         _check_log $dir $group $gridname $casename [dlog get]
57     }
58
59     return
60 }
61
62 # Basic command to run indicated test case in DRAW
63 help testgrid {
64   Run all tests, or specified group, or one grid
65   Use: testgrid [group [grid]] [options...]
66   Allowed options are:
67   -parallel N: run N parallel processes (default is number of CPUs, 0 to disable)
68   -refresh N: save summary logs every N seconds (default 600, minimal 1, 0 to disable)
69   -outdir dirname: set log directory (should be empty or non-existing)
70   -overwrite: force writing logs in existing non-empty directory
71   -xml filename: write XML report for Jenkins (in JUnit-like format)
72 }
73 proc testgrid {args} {
74     global env tcl_platform _tests_verbose
75
76     ######################################################
77     # check arguments
78     ######################################################
79
80     # check that environment variable defining paths to test scripts is defined
81     if { ! [info exists env(CSF_TestScriptsPath)] || 
82          [llength $env(CSF_TestScriptsPath)] <= 0 } {
83         error "Error: Environment variable CSF_TestScriptsPath is not defined"
84     }
85
86     # treat options
87     set parallel [_get_nb_cpus]
88     set refresh 60
89     set logdir ""
90     set overwrite 0
91     set xmlfile ""
92     for {set narg 0} {$narg < [llength $args]} {incr narg} {
93         set arg [lindex $args $narg]
94
95         # parallel execution
96         if { $arg == "-parallel" } {
97             incr narg
98             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
99                 set parallel [expr [lindex $args $narg]]
100             } else {
101                 error "Option -parallel requires argument"
102             }
103             continue
104         }
105
106         # refresh logs time
107         if { $arg == "-refresh" } {
108             incr narg
109             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
110                 set refresh [expr [lindex $args $narg]]
111             } else {
112                 error "Option -refresh requires argument"
113             }
114             continue
115         }
116
117         # output directory
118         if { $arg == "-outdir" } {
119             incr narg
120             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
121                 set logdir [lindex $args $narg]
122             } else {
123                 error "Option -outdir requires argument"
124             }
125             continue
126         }
127
128         # allow overwrite logs 
129         if { $arg == "-overwrite" } {
130             set overwrite 1
131             continue
132         }
133
134         # refresh logs time
135         if { $arg == "-xml" } {
136             incr narg
137             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
138                 set xmlfile [lindex $args $narg]
139             }
140             if { $xmlfile == "" } {
141                 set xmlfile TESTS-summary.xml
142             }
143             continue
144         }
145
146         # unsupported option
147         if { [regexp {^-} $arg] } {
148             error "Error: unsupported option \"$arg\""
149         }
150
151         # treat arguments not recognized as options as group and grid names
152         if { ! [info exists groupname] } {
153             set groupname $arg
154         } elseif { ! [info exists gridname] } {
155             set gridname $arg
156         } else {
157             error "Error: cannot interpret argument $narg ($arg): both group and grid names are already defined by previous args!"
158         }
159     }
160
161     # check that target log directory is empty or does not exist
162     set logdir [file normalize [string trim $logdir]]
163     if { $logdir == "" } {
164         # if specified logdir is empty string, generate unique name like 
165         # results_<branch>_<timestamp>
166         set prefix "results"
167         if { ! [catch {exec git branch} gitout] &&
168              [regexp {[*] ([\w]+)} $gitout res branch] } {
169             set prefix "${prefix}_$branch"
170         }
171         set logdir "${prefix}_[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
172         set logdir [file normalize $logdir]
173     }
174     if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
175         error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
176     } 
177     if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
178         error "Error: Cannot create directory \"$logdir\", or it is not writable"
179     }
180
181     ######################################################
182     # prepare list of tests to be performed
183     ######################################################
184
185     # list of tests, each defined by a list of:
186     # test scripts directory
187     # group (subfolder) name
188     # grid (subfolder) name
189     # test case name
190     # path to test case file
191     set tests_list {}
192
193     # iterate by all script paths
194     foreach dir [_split_path $env(CSF_TestScriptsPath)] {
195         # protection against empty paths
196         set dir [string trim $dir]
197         if { $dir == "" } { continue }
198
199         if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
200
201         # check that directory exists
202         if { ! [file isdirectory $dir] } {
203             _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
204             continue
205         }
206
207         # if test group is specified, check that directory with given name exists in this dir
208         # if not, continue to the next test dir
209         if { [info exists groupname] && $groupname != "" } {
210             if { [file isdirectory $dir/$groupname] } { 
211                 set groups $groupname
212             } else {
213                 continue 
214             }
215         } else {
216             # else search all directories in the current dir
217             if [catch {glob -directory $dir -tail -types d *} groups] { continue }
218         }
219
220         # iterate by groups
221         if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
222         foreach group [lsort -dictionary $groups] {
223             if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
224
225             # file grids.list must exist: it defines sequence of grids in the group
226             if { ! [file exists $dir/$group/grids.list] } {
227                 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
228                 continue
229             }
230
231             # read grids.list file and make a list of grids to be executed
232             set gridlist {}
233             set fd [open $dir/$group/grids.list]
234             set nline 0
235             while { [gets $fd line] >= 0 } {
236                 incr nline
237
238                 # skip comments and empty lines
239                 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
240                 if { [string trim $line] == "" } { continue }
241
242                 # get grid id and name
243                 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
244                     _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
245                     continue
246                 }
247                 
248                 # if specific grid is requested, check that it is present; otherwise make complete list
249                 if { ! [info exists gridname] || $gridname == "" || $gridname == $gridid || $gridname == $grid } {
250                     lappend gridlist $grid
251                 }
252             }
253             close $fd
254             
255             # iterate by all grids
256             foreach grid $gridlist {
257
258                 # check if this grid is aliased to another one
259                 set griddir $dir/$group/$grid
260                 if { [file exists $griddir/cases.list] } {
261                     set fd [open $griddir/cases.list]
262                     if { [gets $fd line] >= 0 } {
263                         set griddir [file normalize $dir/$group/$grid/[string trim $line]]
264                     }
265                     close $fd
266                 }
267
268                 # check if grid directory actually exists
269                 if { ! [file isdirectory $griddir] } { 
270                     _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
271                     continue 
272                 }
273
274                 # create directory for logging test results
275                 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
276
277                 # iterate by all tests in the grid directory
278                 if { [catch {glob -directory $griddir -type f *} testfiles] } { continue }
279                 foreach casefile [lsort -dictionary $testfiles] {
280                     # filter out begin and end files
281                     set casename [file tail $casefile]
282                     if { $casename == "begin" || $casename == "end" } { continue }
283
284                     lappend tests_list [list $dir $group $grid $casename $casefile]
285                 }
286             }
287         }
288     }
289     if { [llength $tests_list] < 1 } {
290         error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
291     }
292
293     ######################################################
294     # run tests
295     ######################################################
296     
297     # log command arguments and environment
298     lappend log "Command: testgrid $args"
299     lappend log "Host: [info hostname]"
300     lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
301     catch {lappend log "DRAW build:\n[dversion]" }
302     lappend log "Environment:"
303     foreach envar [lsort [array names env]] {
304         lappend log "$envar=\"$env($envar)\""
305     }
306     lappend log ""
307
308     set refresh_timer [clock seconds]
309     uplevel dchrono _timer reset
310     uplevel dchrono _timer start
311
312     # if parallel execution is requested, allocate thread pool
313     if { $parallel > 0 } {
314         if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
315             _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
316             set parallel 0
317         } else {
318             set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
319             # suspend the pool until all jobs are posted, to prevent blocking of the process
320             # of starting / processing jobs by running threads
321             catch {tpool::suspend $worker}
322             if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
323             # limit number of jobs in the queue by reasonable value
324             # to prevent slowdown due to unnecessary queue processing
325             set nbpooled 0
326             set nbpooled_max [expr 10 * $parallel]
327             set nbpooled_ok  [expr  5 * $parallel]
328         }
329     }
330
331     # start test cases
332     set userbreak 0
333     foreach test_def $tests_list {
334         # check for user break
335         if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
336             set userbreak 1
337             break
338         }
339
340         set dir       [lindex $test_def 0]
341         set group     [lindex $test_def 1]
342         set grid      [lindex $test_def 2]
343         set casename  [lindex $test_def 3]
344         set casefile  [lindex $test_def 4]
345
346         # command to set tests for generation of image in results directory
347         set imgdir_cmd ""
348         if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
349
350         # prepare command file for running test case in separate instance of DRAW
351         set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
352         puts $fd_cmd "$imgdir_cmd"
353         puts $fd_cmd "set test_image $casename"
354         puts $fd_cmd "_run_test $dir $group $grid $casefile t"
355
356         # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
357         # note: this is not needed if echo is set to 1 in call to _run_test above
358         if { ! [catch {dlog get}] } {
359             puts $fd_cmd "puts \[dlog get\]"
360         } else {
361             # else try to use old-style QA_ variables to get more output...
362             set env(QA_DUMP) 1
363             set env(QA_DUP) 1
364             set env(QA_print_command) 1
365         }
366
367         # final 'exit' is needed when running on Linux under VirtualGl
368         puts $fd_cmd "exit"
369         close $fd_cmd
370
371         # commant to run DRAW with a command file;
372         # note that empty string is passed as standard input to avoid possible 
373         # hang-ups due to waiting for stdin of the launching process
374         set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
375
376         # alternative method to run without temporary file; disabled as it needs too many backslashes
377 #       else {
378 #           set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
379 #                        _run_test $dir $group $grid $casefile\\\; \
380 #                        puts \\\[dlog get\\\]\\\; exit"
381 #       }
382
383         # run test case, either in parallel or sequentially
384         if { $parallel > 0 } {
385             # parallel execution
386             set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
387             set job_def($job) [list $logdir $dir $group $grid $casename]
388             incr nbpooled
389             if { $nbpooled > $nbpooled_max } {
390                 _testgrid_process_jobs $worker $nbpooled_ok
391             }
392         } else {
393             # sequential execution
394             catch {eval $command} output
395             _log_test_case $output $logdir $dir $group $grid $casename log
396
397             # update summary log with requested period
398             if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
399                 # update and dump summary
400                 _log_summarize $logdir $log
401                 set refresh_timer [clock seconds]
402             }
403         }
404     }
405
406     # get results of started threads
407     if { $parallel > 0 } {
408         _testgrid_process_jobs $worker
409         # release thread pool
410         if { $nbpooled > 0 } {
411             tpool::cancel $worker [array names job_def]
412         }
413         catch {tpool::resume $worker}
414         tpool::release $worker
415     }
416
417     uplevel dchrono _timer stop
418     set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
419
420     if { $userbreak } {
421         _log_and_puts log "*********** Stopped by user break ***********"
422         set time "${time} \nNote: the process is not finished, stopped by user break!"
423     }
424
425     ######################################################
426     # output summary logs and exit
427     ######################################################
428
429     _log_summarize $logdir $log $time
430     if { $logdir != "" } {
431         puts "Detailed logs are saved in $logdir"
432     }
433     if { $logdir != "" && $xmlfile != "" } {
434         # XML output file is assumed relative to log dir unless it is absolute
435         if { [ file pathtype $xmlfile] == "relative" } {
436             set xmlfile [file normalize $logdir/$xmlfile]
437         }
438         _log_xml_summary $logdir $xmlfile $log 0
439         puts "XML summary is saved to $xmlfile"
440     }
441
442     return
443 }
444
445 # Procedure to regenerate summary log from logs of test cases
446 help testsummarize {
447   Regenerate summary log in the test directory from logs of test cases.
448   This can be necessary if test grids are executed separately (e.g. on
449   different stations) or some grids have been re-executed.
450   Use: testsummarize dir
451 }
452 proc testsummarize {dir} {
453     global _test_case_regexp
454
455     if { ! [file isdirectory $dir] } {
456         error "Error: \"$dir\" is not a directory"
457     }
458
459     # get summary statements from all test cases in one log
460     set log {}
461
462     # to avoid huge listing of logs, first find all subdirectories and iterate
463     # by them, parsing log files in each subdirectory independently 
464     foreach grid [glob -directory $dir -types d -tails */*] {
465         foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
466             set file [file join $dir $grid $caselog]
467             set nbfound 0
468             set fd [open $file r]
469             while { [gets $fd line] >= 0 } {
470                 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
471                     if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } { 
472                         puts "Error: $file contains status line for another test case ($line)"
473                     }
474                     lappend log $line
475                     incr nbfound
476                 }
477             }
478             close $fd
479
480             if { $nbfound != 1 } { 
481                 puts "Error: $file contains $nbfound status lines, expected 1"
482             }
483         }
484     }
485
486     _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
487     return
488 }
489
490 # Procedure to compare results of two runs of test cases
491 help testdiff {
492   Compare results of two executions of tests (CPU times, ...)
493   Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
494   Where dir1 and dir2 are directories containing logs of two test runs.
495   Allowed options are:
496   -save filename: save resulting log in specified file (default name is
497                   <dir1>/diff-<dir2>.log); HTML log is saved with same name
498                   and extension .html
499   -status {same|ok|all}: filter cases for comparing by their status:
500           same - only cases with same status are compared (default)
501           ok   - only cases with OK status in both logs are compared
502           all  - results are compared regardless of status
503   -verbose level: 
504           1 - output only differences 
505           2 - output also list of logs and directories present in one of dirs only
506           3 - (default) output also progress messages 
507 }
508 proc testdiff {dir1 dir2 args} {
509     if { "$dir1" == "$dir2" } {
510         error "Input directories are the same"
511     }
512
513     ######################################################
514     # check arguments
515     ######################################################
516
517     # treat options
518     set logfile [file join $dir1 "diff-[file tail $dir2].log"]
519     set basename ""
520     set status "same"
521     set verbose 3
522     for {set narg 0} {$narg < [llength $args]} {incr narg} {
523         set arg [lindex $args $narg]
524
525         # log file name
526         if { $arg == "-save" } {
527             incr narg
528             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
529                 set logfile [lindex $args $narg]
530             } else {
531                 error "Error: Option -save must be followed by log file name"
532             } 
533             continue
534         }
535
536         # status filter
537         if { $arg == "-status" } {
538             incr narg
539             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
540                 set status [lindex $args $narg]
541             } else { set status "" }
542             if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
543                 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
544             }
545             continue
546         }
547
548         # verbose level
549         if { $arg == "-verbose" } {
550             incr narg
551             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
552                 set verbose [expr [lindex $args $narg]]
553             } else {
554                 error "Error: Option -verbose must be followed by integer verbose level"
555             }
556             continue
557         }
558
559         if { [regexp {^-} $arg] } {
560             error "Error: unsupported option \"$arg\""
561         }
562
563         # non-option arguments form a subdirectory path
564         set basename [file join $basename $arg]
565     }
566
567     # run diff procedure (recursive)
568     _test_diff $dir1 $dir2 $basename $status $verbose log
569
570     # save result to log file
571     if { "$logfile" != "" } {
572         _log_save $logfile [join $log "\n"]
573         _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2
574         puts "Log is saved to $logfile (and .html)"
575     }
576
577     return
578 }
579
580 # Procedure to check data file before adding it to repository
581 help testfile {
582   Check data file and prepare it for putting to test data files repository.
583   Use: testfile [filelist]
584
585   Will report if:
586   - data file (non-binary) is in DOS encoding (CR/LF)
587   - same data file (with same or another name) already exists in the repository
588   - another file with the same name already exists 
589   Note that names are assumed to be case-insensitive (for Windows).
590
591   Unless the file is already in the repository, tries to load it, reports
592   the recognized file format, file size, number of faces and edges in the 
593   loaded shape (if any), and makes snapshot (in the temporary directory).
594   Finally it advises whether the file should be put to public section of the 
595   repository.
596 }
597 proc testfile {filelist} {
598     global env
599
600     # check that CSF_TestDataPath is defined
601     if { ! [info exists env(CSF_TestDataPath)] } {
602         error "Environment variable CSF_TestDataPath must be defined!"
603     }
604
605     # build registry of existing data files (name -> path) and (size -> path)
606     puts "Checking available test data files..."
607     foreach dir [_split_path $env(CSF_TestDataPath)] {
608         while {[llength $dir] != 0} {
609             set curr [lindex $dir 0]
610             set dir [lrange $dir 1 end]
611             eval lappend dir [glob -nocomplain -directory $curr -type d *]
612             foreach file [glob -nocomplain -directory $curr -type f *] {
613                 set name [file tail $file]
614                 set name_lower [string tolower $name]
615
616                 # check that the file is not in DOS encoding
617                 if { [_check_dos_encoding $file] } {
618                     puts "Warning: file $file is in DOS encoding; was this intended?"
619                 }
620                 _check_file_format $file
621
622                 # check if file with the same name is present twice or more
623                 if { [info exists names($name_lower)] } {
624                     puts "Error: more than one file with name $name is present in the repository:"
625                     if { [_diff_files $file $names($name_lower)] } {
626                         puts "(files are different by content)"
627                     } else {
628                         puts "(files are same by content)"
629                     }
630                     puts "--> $file"
631                     puts "--> $names($name_lower)"
632                     continue
633                 } 
634                 
635                 # check if file with the same content exists
636                 set size [file size $file]
637                 if { [info exists sizes($size)] } {
638                     foreach other $sizes($size) {
639                         if { ! [_diff_files $file $other] } {
640                             puts "Warning: two files with the same content found:"
641                             puts "--> $file"
642                             puts "--> $other"
643                         }
644                     }
645                 }
646
647                 # add the file to the registry
648                 set names($name_lower) $file
649                 lappend sizes($size) $file
650             }
651         }
652     }
653     if { [llength $filelist] <= 0 } { return }
654
655     # check the new files
656     set has_images f
657     puts "Checking new file(s)..."
658     foreach file $filelist {
659         # check for DOS encoding
660         if { [_check_dos_encoding $file] } {
661             puts "$file: Warning: DOS encoding detected"
662         }
663
664         set name [file tail $file]
665         set name_lower [string tolower $name]
666
667         # check for presence of the file with same name
668         if { [info exists names($name_lower)] } {
669             if { [_diff_files $file $names($name_lower)] } {
670                 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
671             } else {
672                 puts "$file: OK: already in the repository \n--> $names($name_lower)"
673                 continue
674             }
675         }
676                 
677         # check if file with the same content exists
678         set size [file size $file]
679         if { [info exists sizes($size)] } {
680             set found f
681             foreach other $sizes($size) {
682                 if { ! [_diff_files $file $other] } {
683                      puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
684                      set found t
685                      break
686                 }
687             }
688             if { $found } { continue }
689         }
690
691         # try to read the file
692         set format [_check_file_format $file]
693         if { [catch {uplevel load_data_file $file $format a}] } {
694             puts "$file: Error: Cannot read as $format file"
695             continue
696         }
697
698         # get number of faces and edges
699         set edges 0
700         set faces 0
701         set nbs [uplevel nbshapes a]
702         regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
703         regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
704
705         # classify; first check file size and number of faces and edges
706         if { $size < 95000 && $faces < 20 && $edges < 100 } {
707             set dir public
708         } else {
709             set dir private
710             # check if one of names of that file corresponds to typical name for 
711             # MDTV bugs or has extension .rle, this should be old model
712             if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
713                  [regexp -nocase {[.]rle\y} $name] } {
714                 set dir old
715             }
716         }
717
718         # add stats
719         puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
720
721         set tmpdir [_get_temp_dir]
722         file mkdir $tmpdir/$dir
723
724         # make snapshot
725         pload AISV
726         uplevel vdisplay a
727         uplevel vfit
728         uplevel vzfit
729         uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
730         set has_images t
731     }
732     if { $has_images } {
733         puts "Snapshots are saved in subdirectory [_get_temp_dir]"
734     }
735 }
736
737 # Procedure to locate data file for test given its name.
738 # The search is performed assuming that the function is called
739 # from the test case script; the search order is:
740 # - subdirectory "data" of the test script (grid) folder
741 # - subdirectories in environment variable CSF_TestDataPath
742 # - subdirectory set by datadir command
743 # If file is not found, raises Tcl error.
744 proc locate_data_file {filename} {
745     global env groupname gridname casename
746
747     # check if the file is located in the subdirectory data of the script dir
748     set scriptfile [info script]
749     if { $scriptfile != "" } {
750         set path [file join [file dirname $scriptfile] data $filename]
751         if { [file exists $path] } {
752             return [file normalize $path]
753         }
754     }
755
756     # check sub-directories in paths indicated by CSF_TestDataPath
757     if { [info exists env(CSF_TestDataPath)] } {
758         foreach dir [_split_path $env(CSF_TestDataPath)] {
759             while {[llength $dir] != 0} { 
760                 set name [lindex $dir 0]
761                 set dir [lrange $dir 1 end]
762                 eval lappend dir [glob -nocomplain -directory $name -type d *]
763                 if { [file exists $name/$filename] } {
764                     return [file normalize $name/$filename]
765                 }
766             }
767         }
768     }
769
770     # check current datadir
771     if { [file exists [uplevel datadir]/$filename] } {
772         return [file normalize [uplevel datadir]/$filename]
773     }
774
775     # raise error
776     error [join [list "File $filename could not be found" \
777                       "(should be in paths indicated by CSF_TestDataPath environment variable, " \
778                       "or in subfolder data in the script directory)"] "\n"]
779 }
780
781 # Internal procedure to find test case indicated by group, grid, and test case names;
782 # returns:
783 # - dir: path to the base directory of the tests group
784 # - gridname: actual name of the grid
785 # - casefile: path to the test case script 
786 # if no such test is found, raises error with appropriate message
787 proc _get_test {group grid casename _dir _gridname _casefile} {
788     upvar $_dir dir
789     upvar $_gridname gridname
790     upvar $_casefile casefile
791
792     global env
793  
794     # check that environment variable defining paths to test scripts is defined
795     if { ! [info exists env(CSF_TestScriptsPath)] || 
796          [llength $env(CSF_TestScriptsPath)] <= 0 } {
797         error "Error: Environment variable CSF_TestScriptsPath is not defined"
798     }
799
800     # iterate by all script paths
801     foreach dir [_split_path $env(CSF_TestScriptsPath)] {
802         # protection against empty paths
803         set dir [string trim $dir]
804         if { $dir == "" } { continue }
805
806         # check that directory exists
807         if { ! [file isdirectory $dir] } {
808             puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
809             continue
810         }
811
812         # check if test group with given name exists in this dir
813         # if not, continue to the next test dir
814         if { ! [file isdirectory $dir/$group] } { continue }
815
816         # check that grid with given name (possibly alias) exists; stop otherwise
817         set gridname $grid
818         if { ! [file isdirectory $dir/$group/$gridname] } {
819             # check if grid is named by alias rather than by actual name
820             if { [file exists $dir/$group/grids.list] } {
821                 set fd [open $dir/$group/grids.list]
822                 while { [gets $fd line] >= 0 } {
823                     if { [regexp "\[ \t\]*\#.*" $line] } { continue }
824                     if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
825                         break
826                     }
827                 }
828                 close $fd
829             }
830         }
831         if { ! [file isdirectory $dir/$group/$gridname] } { continue }
832
833         # get actual file name of the script; stop if it cannot be found
834         set casefile $dir/$group/$gridname/$casename
835         if { ! [file exists $casefile] } {
836             # check if this grid is aliased to another one
837             if { [file exists $dir/$group/$gridname/cases.list] } {
838                 set fd [open $dir/$group/$gridname/cases.list]
839                 if { [gets $fd line] >= 0 } {
840                     set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
841                 }
842                 close $fd
843             }
844         }
845         if { [file exists $casefile] } { 
846             # normal return
847             return 
848         }
849     }
850
851     # coming here means specified test is not found; report error
852     error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
853                      "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
854 }
855
856 # Internal procedure to run test case indicated by base directory, 
857 # grid and grid names, and test case file path.
858 # The log can be obtained by command "dlog get".
859 proc _run_test {scriptsdir group gridname casefile echo} {
860     global env
861
862     # start timer
863     uplevel dchrono _timer reset
864     uplevel dchrono _timer start
865     catch {uplevel meminfo w} membase
866
867     # enable commands logging; switch to old-style mode if dlog command is not present
868     set dlog_exists 1
869     if { [catch {dlog reset}] } {
870         set dlog_exists 0
871     } elseif { $echo } {
872         decho on
873     } else {
874         dlog reset
875         dlog on
876         rename puts puts-saved
877         proc puts args { 
878             global _tests_verbose
879
880             # log only output to stdout and stderr, not to file!
881             if {[llength $args] > 1} {
882                 set optarg [lindex $args end-1]
883                 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
884                     dlog add [lindex $args end]
885                 } else {
886                     eval puts-saved $args
887                 }
888             } else {
889                 dlog add [lindex $args end]
890             }
891         }
892     }
893
894     # evaluate test case 
895     if [catch {
896         # set variables identifying test case
897         uplevel set casename [file tail $casefile]
898         uplevel set groupname $group
899         uplevel set gridname $gridname
900         uplevel set dirname  $scriptsdir
901
902         # set variables for saving of images if not yet set
903         if { ! [uplevel info exists imagedir] } {
904             uplevel set imagedir [_get_temp_dir]
905             uplevel set test_image \$casename
906         }
907
908         # execute test scripts 
909         if { [file exists $scriptsdir/$group/begin] } {
910             puts "Executing $scriptsdir/$group/begin..."; flush stdout
911             uplevel source $scriptsdir/$group/begin
912         }
913         if { [file exists $scriptsdir/$group/$gridname/begin] } {
914             puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
915             uplevel source $scriptsdir/$group/$gridname/begin
916         }
917         
918         puts "Executing $casefile..."; flush stdout
919         uplevel source $casefile
920         
921         if { [file exists $scriptsdir/$group/$gridname/end] } {
922             puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
923             uplevel source $scriptsdir/$group/$gridname/end
924         }
925         if { [file exists $scriptsdir/$group/end] } {
926             puts "Executing $scriptsdir/$group/end..."; flush stdout
927             uplevel source $scriptsdir/$group/end
928         }
929     } res] {
930         puts "Tcl Exception: $res"
931     }
932
933     # stop logging
934     if { $dlog_exists } {
935         if { $echo } {
936             decho off
937         } else {
938             rename puts {}
939             rename puts-saved puts
940             dlog off
941         }
942     }
943
944     # stop cpulimit killer if armed by the test
945     cpulimit
946
947     # add memory and timing info
948     set stats ""
949     if { ! [catch {uplevel meminfo w} memuse] } {
950         set stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
951     }
952     uplevel dchrono _timer stop
953     set time [uplevel dchrono _timer show]
954     if [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu] {
955         set stats "${stats}TOTAL CPU TIME: $cpu sec\n"
956     }
957     if { $dlog_exists && ! $echo } {
958         dlog add $stats
959     } else {
960         puts $stats
961     }
962 }
963
964 # Internal procedure to check log of test execution and decide if it passed or failed
965 proc _check_log {dir group gridname casename log {_summary {}} {_html_log {}}} {
966     global env
967     if { $_summary != "" } { upvar $_summary summary }
968     if { $_html_log != "" } { upvar $_html_log html_log }
969     set summary {}
970     set html_log {}
971
972 if [catch {
973
974     # load definition of 'bad words' indicating test failure
975     # note that rules are loaded in the order of decreasing priority (grid - group - common),
976     # thus grid rules will override group ones
977     set badwords {}
978     foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
979         if [catch {set fd [open $rulesfile r]}] { continue }
980         while { [gets $fd line] >= 0 } {
981             # skip comments and empty lines
982             if { [regexp "\[ \t\]*\#.*" $line] } { continue }
983             if { [string trim $line] == "" } { continue }
984             # extract regexp
985             if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } { 
986                 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
987                 continue 
988             }
989             set status [string trim $status]
990             if { $comment != "" } { set status "$status ([string trim $comment])" }
991             set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
992             lappend badwords [list $status $rexp]
993         }
994         close $fd
995     }
996     if { [llength $badwords] <= 0 } { 
997         puts "Warning: no definition of error indicators found (check files parse.rules)" 
998     }
999
1000     # analyse log line-by-line
1001     set todos {}
1002     set status ""
1003     foreach line [split $log "\n"] {
1004         # check if line defines specific treatment of some messages
1005         if [regexp -nocase {^[ \t]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1006             if { ! [regexp -nocase {\mAll\M} $platforms] && 
1007                  ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1008                 lappend html_log $line
1009                 continue ;# TODO statement is for another platform
1010             }
1011
1012             # record TODOs that mark unstable cases
1013             if { [regexp {[\?]} $platforms] } {
1014                 set todos_unstable([llength $todos]) 1
1015             }
1016
1017             lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1018             lappend html_log [_html_highlight BAD $line]
1019             continue
1020         }
1021
1022         # check for presence of messages indicating test result
1023         set ismarked 0
1024         foreach bw $badwords {
1025             if { [regexp [lindex $bw 1] $line] } { 
1026                 # check if this is known bad case
1027                 set is_known 0
1028                 for {set i 0} {$i < [llength $todos]} {incr i} {
1029                     if { [regexp [lindex $todos $i] $line] } {
1030                         set is_known 1
1031                         incr todo_count($i)
1032                         lappend html_log [_html_highlight BAD $line]
1033                         break
1034                     }
1035                 }
1036
1037                 # if it is not in todo, define status
1038                 if { ! $is_known } {
1039                     set stat [lindex $bw 0 0]
1040                     lappend html_log [_html_highlight $stat $line]
1041                     if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1042                         set status [lindex $bw 0]
1043                     }
1044                 }
1045                 set ismarked 1
1046                 break
1047             }
1048         }
1049         if { ! $ismarked } { 
1050             lappend html_log $line
1051         }
1052     }
1053
1054     # check for presence of TEST COMPLETED statement
1055     if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1056         # check whether absence of TEST COMPLETED is known problem
1057         set i [lsearch $todos "TEST INCOMPLETE"]
1058         if { $i >= 0 } {
1059             incr todo_count($i)
1060         } else {
1061             set status "FAILED (no final message is found)"
1062         }
1063     }
1064
1065     # check declared bad cases and diagnose possible improvement 
1066     # (bad case declared but not detected).
1067     # Note that absence of the problem marked by TODO with question mark
1068     # (unstable) is not reported as improvement.
1069     if { $status == "" } {
1070         for {set i 0} {$i < [llength $todos]} {incr i} {
1071             if { ! [info exists todos_unstable($i)] &&
1072                  (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1073                 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1074                 break;
1075             }
1076         }
1077     }
1078
1079     # report test as known bad if at least one of expected problems is found
1080     if { $status == "" && [llength [array names todo_count]] > 0 } {
1081         set status "BAD (known problem)"
1082     }
1083
1084     # report normal OK
1085     if { $status == "" } {set status "OK" }
1086
1087 } res] {
1088     set status "FAILED ($res)"
1089 }
1090
1091     # put final message
1092     _log_and_puts summary "CASE $group $gridname $casename: $status"
1093     set summary [join $summary "\n"]
1094     set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1095 }
1096
1097 # Auxiliary procedure putting message to both cout and log variable (list)
1098 proc _log_and_puts {logvar message} {
1099     if { $logvar != "" } { 
1100         upvar $logvar log
1101         lappend log $message
1102     }
1103     puts $message
1104 }
1105
1106 # Auxiliary procedure to log result on single test case
1107 proc _log_test_case {output logdir dir group grid casename logvar} {
1108     upvar $logvar log
1109
1110     # check result and make HTML log
1111     _check_log $dir $group $grid $casename $output summary html_log
1112     lappend log $summary
1113
1114     # save log to file
1115     if { $logdir != "" } {
1116         _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1117         _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1118     }
1119 }
1120
1121 # Auxiliary procedure to save log to file
1122 proc _log_save {file log {title {}}} {
1123     # create missing directories as needed
1124     catch {file mkdir [file dirname $file]}
1125
1126     # try to open a file
1127     if [catch {set fd [open $file w]} res] {
1128         error "Error saving log file $file: $res"
1129     }
1130     
1131     # dump log and close
1132     puts $fd "$title\n"
1133     puts $fd $log
1134     close $fd
1135     return
1136 }
1137
1138 # Auxiliary procedure to make a (relative if possible) URL to a file for 
1139 # inclusion a reference in HTML log
1140 proc _make_url {htmldir file} {
1141     set htmlpath [file split [file normalize $htmldir]]
1142     set filepath [file split [file normalize $file]]
1143     for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1144         if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1145             if { $i == 0 } { break }
1146             return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1147         }
1148     }
1149
1150     # if relative path could not be made, return full file URL
1151     return "file://[file normalize $file]"
1152 }
1153
1154 # Auxiliary procedure to save log to file
1155 proc _log_html {file log {title {}}} {
1156     # create missing directories as needed
1157     catch {file mkdir [file dirname $file]}
1158
1159     # try to open a file
1160     if [catch {set fd [open $file w]} res] {
1161         error "Error saving log file $file: $res"
1162     }
1163     
1164     # print header
1165     puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1166
1167     # add images if present
1168     set imgbasename [file rootname [file tail $file]]
1169     foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails ${imgbasename}*.gif ${imgbasename}*.png ${imgbasename}*.jpg]] {
1170         puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1171     }
1172
1173     # print log body, trying to add HTML links to script files on lines like
1174     # "Executing <filename>..."
1175     puts $fd "<pre>"
1176     foreach line [split $log "\n"] {
1177         if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1178              [file exists $script] } {
1179             set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1180         }
1181         puts $fd $line
1182     }
1183     puts $fd "</pre></body></html>"
1184
1185     close $fd
1186     return
1187 }
1188
1189 # Auxiliary method to make text with HTML highlighting according to status
1190 proc _html_color {status} {
1191     # choose a color for the cell according to result
1192     if { $status == "OK" } { 
1193         return lightgreen
1194     } elseif { [regexp -nocase {^FAIL} $status] } { 
1195         return red
1196     } elseif { [regexp -nocase {^BAD} $status] } { 
1197         return yellow
1198     } elseif { [regexp -nocase {^IMP} $status] } { 
1199         return orange
1200     } elseif { [regexp -nocase {^SKIP} $status] } { 
1201         return gray
1202     } elseif { [regexp -nocase {^IGNOR} $status] } { 
1203         return gray
1204     } else {
1205         puts "Warning: no color defined for status $status, using red as if FAILED"
1206         return red
1207     }
1208 }
1209
1210 # Format text line in HTML to be colored according to the status
1211 proc _html_highlight {status line} {
1212     return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1213 }
1214
1215 # Internal procedure to generate HTML page presenting log of the tests
1216 # execution in tabular form, with links to reports on individual cases
1217 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1218     global _test_case_regexp
1219
1220     # create missing directories as needed
1221     file mkdir $logdir
1222
1223     # try to open a file and start HTML
1224     if [catch {set fd [open $logdir/summary.html w]} res] {
1225         error "Error creating log file: $res"
1226     }
1227
1228     # write HRML header, including command to refresh log if still in progress
1229     puts $fd "<html><head>"
1230     puts $fd "<title>Tests summary</title>"
1231     if { $total_time == "" } {
1232         puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1233     }
1234     puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1235     puts $fd "</head><body>"
1236
1237     # put summary
1238     set legend(OK)          "Test passed OK"
1239     set legend(FAILED)      "Test failed (regression)"
1240     set legend(BAD)         "Known problem"
1241     set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1242     set legend(SKIPPED)     "Test skipped due to lack of data file"
1243     puts $fd "<h1>Summary</h1><table>"
1244     foreach nbstat $totals {
1245         set status [lindex $nbstat 1]
1246         if { [info exists legend($status)] } { 
1247             set comment $legend($status) 
1248         } else {
1249             set comment "User-defined status"
1250         }
1251         puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1252     }
1253     puts $fd "</table>"
1254
1255     # time stamp and elapsed time info
1256     if { $total_time != "" } { 
1257         puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1258         puts $fd [join [split $total_time "\n"] "<p>"]
1259     } else {
1260         puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1261     }
1262    
1263     # print regressions and improvements
1264     foreach featured [list $regressions $improvements] {
1265         if { [llength $featured] <= 1 } { continue }
1266         set status [string trim [lindex $featured 0] { :}]
1267         puts $fd "<h2>$status</h2>"
1268         puts $fd "<table>"
1269         set groupgrid ""
1270         foreach test [lrange $featured 1 end] {
1271             if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1272                 set gg UNKNOWN
1273                 set name "Error building short list; check details"
1274             }
1275             if { $gg != $groupgrid } {
1276                 if { $groupgrid != "" } { puts $fd "</tr>" }
1277                 set groupgrid $gg
1278                 puts $fd "<tr><td>$gg</td>"
1279             }
1280             puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1281         }
1282         if { $groupgrid != "" } { puts $fd "</tr>" }
1283         puts $fd "</table>"
1284     }
1285
1286     # put detailed log with TOC
1287     puts $fd "<hr><h1>Details</h1>"
1288     puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1289
1290     # process log line-by-line
1291     set group {}
1292     set letter {}
1293     set body {}
1294     foreach line [lsort -dictionary $log] {
1295         # check that the line is case report in the form "CASE group grid name: result (explanation)"
1296         if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1297             continue
1298         }
1299
1300         # start new group
1301         if { $grp != $group } {
1302             if { $letter != "" } { lappend body "</tr></table>" }
1303             set letter {}
1304             set group $grp
1305             set grid {}
1306             puts $fd "<a href=\"#$group\">$group</a><br>"
1307             lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1308         }
1309
1310         # start new grid
1311         if { $grd != $grid } {
1312             if { $letter != "" } { lappend body "</tr></table>" }
1313             set letter {}
1314             set grid $grd
1315             puts $fd "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#$group-$grid\">$grid</a><br>"
1316             lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1317         }
1318
1319         # check if test case name is <letter><digit>; 
1320         # if not, set alnum to period "." to recognize non-standard test name
1321         if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1322              ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1323             set alnum $casename
1324         }
1325
1326         # start new row when letter changes or for non-standard names
1327         if { $alnum != $letter || $alnum == "." } {
1328             if { $letter != "" } { 
1329                 lappend body "</tr><tr>" 
1330             } else {
1331                 lappend body "<table><tr>"
1332             }
1333             set letter $alnum
1334         }           
1335
1336         lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1337     }
1338     puts $fd "</div>\n[join $body "\n"]</tr></table>"
1339
1340     # add remaining lines of log as plain text
1341     puts $fd "<h2>Plain text messages</h2>\n<pre>"
1342     foreach line $log {
1343         if { ! [regexp $_test_case_regexp $line] } {
1344             puts $fd "$line"
1345         }
1346     }
1347     puts $fd "</pre>"
1348
1349     # close file and exit
1350     puts $fd "</body>"
1351     close $fd
1352     return
1353 }
1354
1355 # Procedure to dump summary logs of tests
1356 proc _log_summarize {logdir log {total_time {}}} {
1357
1358     # sort log records alphabetically to have the same behavior on Linux and Windows 
1359     # (also needed if tests are run in parallel)
1360     set loglist [lsort -dictionary $log]
1361
1362     # classify test cases by status
1363     foreach line $loglist {
1364         if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1365             lappend stat($status) $caseid
1366         }
1367     }
1368     set totals {}
1369     set improvements {Improvements:}
1370     set regressions {Failed:}
1371     if { [info exists stat] } {
1372         foreach status [lsort [array names stat]] {
1373             lappend totals [list [llength $stat($status)] $status]
1374
1375             # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1376             if { [regexp -nocase {^IMP} $status] } {
1377                 eval lappend improvements $stat($status)
1378             } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1379                 eval lappend regressions $stat($status)
1380             }
1381         }
1382     }
1383
1384     # if time is specified, add totals
1385     if { $total_time != "" } {
1386         if { [llength $improvements] > 1 } {
1387             _log_and_puts log [join $improvements "\n  "]
1388         }
1389         if { [llength $regressions] > 1 } {
1390             _log_and_puts log [join $regressions "\n  "]
1391         }
1392         if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1393             _log_and_puts log "No regressions"
1394         }
1395         _log_and_puts log "Total cases: [join $totals {, }]"
1396         _log_and_puts log $total_time
1397     }
1398
1399     # save log to files
1400     if { $logdir != "" } {
1401         _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1402         _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1403     }
1404
1405     return
1406 }
1407
1408 # Internal procedure to generate XML log in JUnit style, for further
1409 # consumption by Jenkins or similar systems.
1410 #
1411 # The output is intended to conform to XML schema supported by Jenkins found at
1412 # 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
1413 #
1414 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1415 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1416 proc _log_xml_summary {logdir filename log include_cout} {
1417     global _test_case_regexp
1418
1419     catch {file mkdir [file dirname $filename]}
1420
1421     # try to open a file and start XML
1422     if [catch {set fd [open $filename w]} res] {
1423         error "Error creating XML summary file $filename: $res"
1424     }
1425     puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1426     puts $fd "<testsuites>"
1427
1428     # prototype for command to generate test suite tag
1429     set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1430     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"}
1431
1432     # sort log and process it line-by-line
1433     set group {}
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] } {
1437             continue
1438         }
1439         set message [string trim $message " \t\r\n()"]
1440
1441         # start new testsuite for each grid
1442         if { $grp != $group || $grd != $grid } {
1443
1444             # write previous test suite
1445             if [info exists testcases] { eval $cmd_testsuite }
1446
1447             set testcases {}
1448             set nbtests 0
1449             set nberr 0
1450             set nbfail 0
1451             set nbskip 0
1452             set time 0.
1453
1454             set group $grp
1455             set grid $grd
1456         }
1457
1458         incr nbtests
1459          
1460         # parse test log and get its CPU time
1461         set testout {}
1462         set add_cpu {}
1463         if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } { 
1464             puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1465         } else {
1466             while { [gets $fdlog logline] >= 0 } {
1467                 if { $include_cout } {
1468                     set testout "$testout$logline\n"
1469                 }
1470                 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1471                     set add_cpu " time=\"$cpu\""
1472                     set time [expr $time + $cpu]
1473                 }
1474             }
1475             close $fdlog
1476         }
1477         if { ! $include_cout } {
1478             set testout "$line\n"
1479         }
1480
1481         # record test case with its output and status
1482         # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1483         set testcases "$testcases\n  <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1484         set testcases "$testcases\n    <system-out>\n$testout    </system-out>"
1485         if { $result != "OK" } {
1486             if { [regexp -nocase {^SKIP} $result] } {
1487                 incr nberr
1488                 set testcases "$testcases\n    <error name=\"$result\" message=\"$message\"/>"
1489             } elseif { [regexp -nocase {^BAD} $result] } {
1490                 incr nbskip
1491                 set testcases "$testcases\n    <skipped>$message</skipped>"
1492             } else {
1493                 incr nbfail
1494                 set testcases "$testcases\n    <failure name=\"$result\" message=\"$message\"/>"
1495             }
1496         }
1497         set testcases "$testcases\n  </testcase>"
1498     }
1499
1500     # write last test suite
1501     if [info exists testcases] { eval $cmd_testsuite }
1502
1503     # the end
1504     puts $fd "</testsuites>"
1505     close $fd
1506     return
1507 }
1508
1509 # define custom platform name 
1510 proc _tests_platform_def {} {
1511     global env tcl_platform
1512
1513     if [info exists env(os_type)] { return }
1514
1515     set env(os_type) $tcl_platform(platform)
1516
1517     # use detailed mapping for various versions of Lunix
1518     # (note that mapping is rather non-uniform, for historical reasons)
1519     if { $tcl_platform(os) == "Linux" && ! [catch {exec cat /etc/issue} issue] } {
1520         if { [regexp {Mandriva[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1521             set env(os_type) Mandriva$num
1522         } elseif { [regexp {Red Hat[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1523             set env(os_type) RedHat$num
1524         } elseif { [regexp {Debian[ \tA-Za-z/]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1525             set env(os_type) Debian$num$subnum
1526         } elseif { [regexp {CentOS[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1527             set env(os_type) CentOS$num$subnum
1528         } elseif { [regexp {Scientific[ \tA-Za-z]+([0-9]+)[.]([0-9]+)} $issue res num subnum] } {
1529             set env(os_type) SL$num$subnum
1530         } elseif { [regexp {Fedora Core[ \tA-Za-z]+([0-9]+)} $issue res num] } {
1531             set env(os_type) FedoraCore$num
1532         }
1533         if { [exec uname -m] == "x86_64" } {
1534             set env(os_type) "$env(os_type)-64"
1535         }
1536     } elseif { $tcl_platform(os) == "Darwin" } {
1537         set env(os_type) MacOS
1538     }
1539 }
1540 _tests_platform_def
1541
1542 # Auxiliary procedure to split path specification (usually defined by
1543 # environment variable) into list of directories or files
1544 proc _split_path {pathspec} {
1545     global tcl_platform
1546
1547     # first replace all \ (which might occur on Windows) by /  
1548     regsub -all "\\\\" $pathspec "/" pathspec
1549
1550     # split path by platform-specific separator
1551     return [split $pathspec [_path_separator]]
1552 }
1553
1554 # Auxiliary procedure to define platform-specific separator for directories in
1555 # path specification
1556 proc _path_separator {} {
1557     global tcl_platform
1558
1559     # split path by platform-specific separator
1560     if { $tcl_platform(platform) == "windows" } {
1561         return ";"
1562     } else {
1563         return ":"
1564     }
1565 }
1566
1567 # Procedure to make a diff and common of two lists
1568 proc _list_diff {list1 list2 _in1 _in2 _common} {
1569     upvar $_in1 in1
1570     upvar $_in2 in2
1571     upvar $_common common
1572
1573     set in1 {}
1574     set in2 {}
1575     set common {}
1576     foreach item $list1 {
1577         if { [lsearch -exact $list2 $item] >= 0 } {
1578             lappend common $item
1579         } else {
1580             lappend in1 $item
1581         }
1582     }
1583     foreach item $list2 {
1584         if { [lsearch -exact $common $item] < 0 } {
1585             lappend in2 $item
1586         }
1587     }
1588     return
1589 }
1590
1591 # procedure to load a file to Tcl string
1592 proc _read_file {filename} {
1593     set fd [open $filename r]
1594     set result [read -nonewline $fd]
1595     close $fd
1596     return $result
1597 }
1598
1599 # procedure to construct name for the mage diff file
1600 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1601     return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1602 }
1603
1604 # Procedure to compare results of two runs of test cases
1605 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1606     upvar $_logvar log
1607
1608     # make sure to load diffimage command
1609     uplevel pload VISUALIZATION
1610
1611     # prepare variable (array) for collecting statistics
1612     if { "$_statvar" != "" } {
1613         upvar $_statvar stat
1614     } else {
1615         set stat(cpu1) 0
1616         set stat(cpu2) 0
1617         set stat(mem1) 0
1618         set stat(mem2) 0
1619         set log {}
1620     }
1621
1622     # first check subdirectories
1623     set path1 [file join $dir1 $basename]
1624     set path2 [file join $dir2 $basename]
1625     set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1626     set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1627     if { [llength $list1] >0 || [llength $list2] > 0 } {
1628         _list_diff $list1 $list2 in1 in2 common
1629         if { "$verbose" > 1 } {
1630             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1631             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1632         }
1633         foreach subdir $common {
1634             if { "$verbose" > 2 } {
1635                 _log_and_puts log "Checking [file join $basename $subdir]"
1636             }
1637             _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1638         }
1639     } else {
1640         # check log files (only if directory has no subdirs)
1641         set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1642         set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1643         _list_diff $list1 $list2 in1 in2 common
1644         if { "$verbose" > 1 } {
1645             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1646             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1647         }
1648         foreach logfile $common {
1649             # load two logs
1650             set log1 [_read_file [file join $dir1 $basename $logfile]]
1651             set log2 [_read_file [file join $dir2 $basename $logfile]]
1652             set casename [file rootname $logfile]
1653
1654             # check execution statuses
1655             set status1 UNDEFINED
1656             set status2 UNDEFINED
1657             if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1658                  ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1659                  "$status1" != "$status2" } {
1660                 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1661
1662                 # if test statuses are different, further comparison makes 
1663                 # no sense unless explicitly requested
1664                 if { "$status" != "all" } {
1665                     continue
1666                 }
1667             }
1668             if { "$status" == "ok" && "$status1" != "OK" } { 
1669                 continue
1670             }
1671
1672             # check CPU times
1673             set cpu1 UNDEFINED
1674             set cpu2 UNDEFINED
1675             if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1676                  [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1677                 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1678                 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1679
1680                 # compare CPU times with 10% precision (but not less 0.5 sec)
1681                 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1682                     _log_and_puts log "CPU [split $basename /] $casename: $cpu1 / $cpu2"
1683                 }
1684             }
1685
1686             # check memory delta
1687             set mem1 UNDEFINED
1688             set mem2 UNDEFINED
1689             if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1690                  [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1691                 set stat(mem1) [expr $stat(mem1) + $mem1]
1692                 set stat(mem2) [expr $stat(mem2) + $mem2]
1693
1694                 # compare memory usage with 10% precision (but not less 16 KiB)
1695                 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1696                     _log_and_puts log "MEMORY [split $basename /] $casename: $mem1 / $mem2"
1697                 }
1698             }
1699
1700             # check images
1701             set imglist1 [glob -directory $path1 -types f -tails -nocomplain $casename*.{png,gif}]
1702             set imglist2 [glob -directory $path2 -types f -tails -nocomplain $casename*.{png,gif}]
1703             _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1704             if { "$verbose" > 1 } {
1705                 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1706                 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1707             }
1708             foreach imgfile $imgcommon {
1709 #                if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1710                 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1711                 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1712                                        [file join $dir2 $basename $imgfile] \
1713                                        0 0 0 $diffile} diff] } {
1714                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1715                     file delete -force $diffile ;# clean possible previous result of diffimage
1716                 } elseif { $diff != 0 } {
1717                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1718                 } else {
1719                     file delete -force $diffile ;# clean useless artifact of diffimage
1720                 }
1721             }
1722         }
1723     }
1724
1725     if { "$_statvar" == "" } {
1726         _log_and_puts log "Total MEMORY difference: $stat(mem1) / $stat(mem2)"
1727         _log_and_puts log "Total CPU difference: $stat(cpu1) / $stat(cpu2)"
1728     }
1729 }
1730
1731 # Auxiliary procedure to save log of results comparison to file
1732 proc _log_html_diff {file log dir1 dir2} {
1733     # create missing directories as needed
1734     catch {file mkdir [file dirname $file]}
1735
1736     # try to open a file
1737     if [catch {set fd [open $file w]} res] {
1738         error "Error saving log file $file: $res"
1739     }
1740     
1741     # print header
1742     puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1743     puts $fd "<h1>Comparison of test results: $dir1 vs. $dir2</h1>"
1744
1745     # print log body, trying to add HTML links to script files on lines like
1746     # "Executing <filename>..."
1747     puts $fd "<pre>"
1748     set logpath [file split [file normalize $file]]
1749     foreach line $log {
1750         puts $fd $line
1751
1752         if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1753             if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1754                # note: special handler for the case if test grid directoried are compared directly
1755                set gridpath ""
1756             }
1757             set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1758             set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1759
1760             set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1761             if { [file exists $difffile] } {
1762                 set imgd "<img src=\"[_make_url $file $difffile]\">"
1763             } else {
1764                 set imgd "N/A"
1765             }
1766
1767             puts $fd "<table><tr><th>[file tail $dir1]</th><th>[file tail $dir2]</th><th>Different pixels</th></tr>"
1768             puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1769         }
1770     }
1771     puts $fd "</pre></body></html>"
1772
1773     close $fd
1774     return
1775 }
1776
1777 # get number of CPUs on the system
1778 proc _get_nb_cpus {} {
1779     global tcl_platform env
1780
1781     if { "$tcl_platform(platform)" == "windows" } {
1782         # on Windows, take the value of the environment variable 
1783         if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1784              ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1785             return $env(NUMBER_OF_PROCESSORS)
1786         }
1787     } elseif { "$tcl_platform(os)" == "Linux" } {
1788         # on Linux, take number of logical processors listed in /proc/cpuinfo
1789         if { [catch {open "/proc/cpuinfo" r} fd] } { 
1790             return 0 ;# should never happen, but...
1791         }
1792         set nb 0
1793         while { [gets $fd line] >= 0 } {
1794             if { [regexp {^processor[ \t]*:} $line] } {
1795                 incr nb
1796             }
1797         }
1798         close $fd
1799         return $nb
1800     } elseif { "$tcl_platform(os)" == "Darwin" } {
1801         # on MacOS X, call sysctl command
1802         if { ! [catch {exec sysctl hw.ncpu} ret] && 
1803              [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
1804             return $nb
1805         }
1806     }
1807
1808     # if cannot get good value, return 0 as default
1809     return 0
1810 }
1811
1812 # check two files for difference
1813 proc _diff_files {file1 file2} {
1814     set fd1 [open $file1 "r"]
1815     set fd2 [open $file2 "r"]
1816
1817     set differ f
1818     while {! $differ} {
1819         set nb1 [gets $fd1 line1]
1820         set nb2 [gets $fd2 line2]
1821         if { $nb1 != $nb2 } { set differ t; break }
1822         if { $nb1 < 0 } { break }
1823         if { [string compare $line1 $line2] } {
1824             set differ t
1825         }
1826     }
1827
1828     close $fd1
1829     close $fd2
1830
1831     return $differ
1832 }
1833
1834 # Check if file is in DOS encoding.
1835 # This check is done by presence of \r\n combination at the end of the first 
1836 # line (i.e. prior to any other \n symbol).
1837 # Note that presence of non-ascii symbols typically used for recognition
1838 # of binary files is not suitable since some IGES and STEP files contain
1839 # non-ascii symbols.
1840 # Special check is added for PNG files which contain \r\n in the beginning.
1841 proc _check_dos_encoding {file} {
1842     set fd [open $file rb]
1843     set isdos f
1844     if { [gets $fd line] && [regexp {.*\r$} $line] && 
1845          ! [regexp {^.PNG} $line] } {
1846         set isdos t
1847     }
1848     close $fd
1849     return $isdos
1850 }
1851
1852 # procedure to recognize format of a data file by its first symbols (for OCCT 
1853 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
1854 proc _check_file_format {file} {
1855     set fd [open $file rb]
1856     set line [read $fd 1024]
1857     close $fd
1858
1859     set warn f
1860     set ext [file extension $file]
1861     set format unknown
1862     if { [regexp {^DBRep_DrawableShape} $line] } {
1863         set format BREP
1864         if { "$ext" != ".brep" && "$ext" != ".rle" && 
1865              "$ext" != ".draw" && "$ext" != "" } {
1866             set warn t
1867         }
1868     } elseif { [regexp {^DrawTrSurf_} $line] } {
1869         set format DRAW
1870         if { "$ext" != ".rle" && 
1871              "$ext" != ".draw" && "$ext" != "" } {
1872             set warn t
1873         }
1874     } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
1875         set format STEP
1876         if { "$ext" != ".step" && "$ext" != ".stp" } {
1877             set warn t
1878         }
1879     } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
1880         set format IGES
1881         if { "$ext" != ".iges" && "$ext" != ".igs" } {
1882             set warn t
1883         }
1884     } elseif { "$ext" == ".igs" } {
1885         set format IGES
1886     } elseif { "$ext" == ".stp" } {
1887         set format STEP
1888     } else {
1889         set format [string toupper [string range $ext 1 end]]
1890     }
1891     
1892     if { $warn } {
1893         puts "$file: Warning: extension ($ext) does not match format ($format)"
1894     }
1895
1896     return $format
1897 }
1898
1899 # procedure to load file knowing its format
1900 proc load_data_file {file format shape} {
1901     switch $format {
1902     BREP { uplevel restore $file $shape }
1903     DRAW { uplevel restore $file $shape }
1904     IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
1905     STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
1906     STL  { pload XSDRAW; uplevel readstl $shape $file }
1907     default { error "Cannot read $format file $file" }
1908     }
1909 }
1910
1911 # procedure to get name of temporary directory,
1912 # ensuring it is existing and writeable 
1913 proc _get_temp_dir {} {
1914     global env tcl_platform
1915
1916     # check typical environment variables 
1917     foreach var {TempDir Temp Tmp} {
1918         # check different case
1919         foreach name [list [string toupper $var] $var [string tolower $var]] {
1920             if { [info exists env($name)] && [file isdirectory $env($name)] &&
1921                  [file writable $env($name)] } {
1922                 return [regsub -all {\\} $env($name) /]
1923             }
1924         }
1925     }
1926
1927     # check platform-specific locations
1928     set fallback tmp
1929     if { "$tcl_platform(platform)" == "windows" } {
1930         set paths "c:/TEMP c:/TMP /TEMP /TMP"
1931         if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
1932             set fallback [regsub -all {\\} "$env(HOMEDRIVE)$(HOMEPATH)/tmp" /]
1933         }
1934     } else {
1935         set paths "/tmp /var/tmp /usr/tmp"
1936         if { [info exists env(HOME)] } {
1937             set fallback "$env(HOME)/tmp"
1938         }
1939     }
1940     foreach dir $paths {
1941         if { [file isdirectory $dir] && [file writable $dir] } {
1942             return $dir
1943         }
1944     }
1945
1946     # fallback case: use subdir /tmp of home or current dir
1947     file mkdir $fallback
1948     return $fallback
1949 }
1950
1951 # extract of code from testgrid command used to process jobs running in 
1952 # parallel until number of jobs in the queue becomes equal or less than 
1953 # specified value
1954 proc _testgrid_process_jobs {worker {nb_ok 0}} {
1955     # bind local vars to variables of the caller procedure
1956     upvar log log
1957     upvar logdir logdir
1958     upvar job_def job_def
1959     upvar nbpooled nbpooled
1960     upvar userbreak userbreak
1961     upvar refresh refresh
1962     upvar refresh_timer refresh_timer
1963
1964     catch {tpool::resume $worker}
1965     while { ! $userbreak && $nbpooled > $nb_ok } {
1966         foreach job [tpool::wait $worker [array names job_def]] {
1967             eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
1968             unset job_def($job)
1969             incr nbpooled -1
1970         }
1971
1972         # check for user break
1973         if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
1974             set userbreak 1
1975         }
1976
1977         # update summary log with requested period
1978         if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
1979             _log_summarize $logdir $log
1980             set refresh_timer [clock seconds]
1981         }
1982     }
1983     catch {tpool::suspend $worker}
1984 }