0027062: Fixed misspelling of resources install path
[occt.git] / src / DrawResources / TestCommands.tcl
CommitLineData
d5f74e42 1# Copyright (c) 2013-2014 OPEN CASCADE SAS
40093367 2#
973c2be1 3# This file is part of Open CASCADE Technology software library.
40093367 4#
d5f74e42 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
973c2be1 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.
40093367 10#
973c2be1 11# Alternatively, this file may be used under the terms of Open CASCADE
12# commercial license or contractual agreement.
40093367 13
14############################################################################
15# This file defines scripts for execution of OCCT tests.
16# It should be loaded automatically when DRAW is started, and provides
351bbcba 17# top-level commands starting with 'test'. Type 'help test' to get their
18# synopsys.
40093367 19# See OCCT Tests User Guide for description of the test system.
20#
21# Note: procedures with names starting with underscore are for internal use
22# inside the test system.
23############################################################################
24
25# Default verbose level for command _run_test
26set _tests_verbose 0
27
28# regexp for parsing test case results in summary log
29set _test_case_regexp {^CASE\s+([\w.-]+)\s+([\w.-]+)\s+([\w.-]+)\s*:\s*([\w]+)(.*)}
30
31# Basic command to run indicated test case in DRAW
b725d7c5 32help test {
33 Run specified test case
433673e0 34 Use: test group grid casename [options...]
35 Allowed options are:
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
5fd3308a 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.
b725d7c5 49}
433673e0 50proc test {group grid casename {args {}}} {
51 # set default values of arguments
52 set echo 0
5fd3308a 53 set errors 0
433673e0 54 set logfile ""
55 set overwrite 0
56 set signal 0
57
40093367 58 # get test case paths (will raise error if input is invalid)
59 _get_test $group $grid $casename dir gridname casefile
60
433673e0 61 # check arguments
62 for {set narg 0} {$narg < [llength $args]} {incr narg} {
63 set arg [lindex $args $narg]
433673e0 64 # if echo specified as "-echo", convert it to bool
65 if { $arg == "-echo" || $arg == "1" } {
6d368502 66 set echo t
67 continue
433673e0 68 }
69
70 # output log file
71 if { $arg == "-outfile" } {
6d368502 72 incr narg
73 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
74 set logfile [lindex $args $narg]
75 } else {
76 error "Option -outfile requires argument"
77 }
78 continue
433673e0 79 }
80
81 # allow overwrite existing log
82 if { $arg == "-overwrite" } {
6d368502 83 set overwrite 1
84 continue
433673e0 85 }
86
87 # sound signal at the end of the test
88 if { $arg == "-beep" } {
6d368502 89 set signal t
90 continue
433673e0 91 }
92
5fd3308a 93 # if errors specified as "-errors", convert it to bool
94 if { $arg == "-errors" } {
6d368502 95 set errors t
96 continue
5fd3308a 97 }
98
433673e0 99 # unsupported option
100 error "Error: unsupported option \"$arg\""
101 }
40093367 102 # run test
c97067ad 103 uplevel _run_test $dir $group $gridname $casefile $echo
40093367 104
105 # check log
433673e0 106 if { !$echo } {
5fd3308a 107 _check_log $dir $group $gridname $casename $errors [dlog get] summary html_log
433673e0 108
109 # create log file
110 if { ! $overwrite && [file isfile $logfile] } {
111 error "Error: Specified log file \"$logfile\" exists; please remove it before running test or use -overwrite option"
112 }
113 if {$logfile != ""} {
6d368502 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]}
117 }
118 _log_html $logfile $html_log "Test $group $grid $casename"
119 } else {
120 _log_save $logfile "[dlog get]\n$summary" "Test $group $grid $casename"
433673e0 121 }
433673e0 122 }
5df3a117 123 }
40093367 124
433673e0 125 # play sound signal at the end of test
126 if {$signal} {
6d368502 127 puts "\7\7\7\7"
433673e0 128 }
40093367 129 return
130}
131
132# Basic command to run indicated test case in DRAW
b725d7c5 133help testgrid {
134 Run all tests, or specified group, or one grid
87f42a3f 135 Use: testgrid [groupmask [gridmask [casemask]]] [options...]
b725d7c5 136 Allowed options are:
137 -parallel N: run N parallel processes (default is number of CPUs, 0 to disable)
9753e6de 138 -refresh N: save summary logs every N seconds (default 600, minimal 1, 0 to disable)
b725d7c5 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)
433673e0 142 -beep: play sound signal at the end of the tests
87f42a3f 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 (*).
40093367 145}
b725d7c5 146proc testgrid {args} {
40093367 147 global env tcl_platform _tests_verbose
148
149 ######################################################
150 # check arguments
151 ######################################################
152
153 # check that environment variable defining paths to test scripts is defined
154 if { ! [info exists env(CSF_TestScriptsPath)] ||
6d368502 155 [llength $env(CSF_TestScriptsPath)] <= 0 } {
40093367 156 error "Error: Environment variable CSF_TestScriptsPath is not defined"
157 }
158
159 # treat options
b725d7c5 160 set parallel [_get_nb_cpus]
40093367 161 set refresh 60
b725d7c5 162 set logdir ""
40093367 163 set overwrite 0
164 set xmlfile ""
433673e0 165 set signal 0
40093367 166 for {set narg 0} {$narg < [llength $args]} {incr narg} {
6d368502 167 set arg [lindex $args $narg]
168
169 # parallel execution
170 if { $arg == "-parallel" } {
171 incr narg
172 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
173 set parallel [expr [lindex $args $narg]]
174 } else {
175 error "Option -parallel requires argument"
176 }
177 continue
178 }
179
180 # refresh logs time
181 if { $arg == "-refresh" } {
182 incr narg
183 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
184 set refresh [expr [lindex $args $narg]]
185 } else {
186 error "Option -refresh requires argument"
187 }
188 continue
189 }
190
191 # output directory
192 if { $arg == "-outdir" } {
193 incr narg
194 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
195 set logdir [lindex $args $narg]
196 } else {
197 error "Option -outdir requires argument"
198 }
199 continue
200 }
201
202 # allow overwrite logs
203 if { $arg == "-overwrite" } {
204 set overwrite 1
205 continue
206 }
207
208 # refresh logs time
209 if { $arg == "-xml" } {
210 incr narg
211 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
212 set xmlfile [lindex $args $narg]
213 }
214 if { $xmlfile == "" } {
215 set xmlfile TESTS-summary.xml
216 }
217 continue
218 }
219
220 # sound signal at the end of the test
221 if { $arg == "-beep" } {
222 set signal t
223 continue
224 }
225
226 # unsupported option
227 if { [regexp {^-} $arg] } {
228 error "Error: unsupported option \"$arg\""
229 }
230
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 ,]
238 } else {
239 error "Error: cannot interpret argument $narg ($arg)"
240 }
40093367 241 }
242
243 # check that target log directory is empty or does not exist
244 set logdir [file normalize [string trim $logdir]]
245 if { $logdir == "" } {
6d368502 246 # if specified logdir is empty string, generate unique name like
ffc26091 247 # results/<branch>_<timestamp>
248 set prefix ""
b725d7c5 249 if { ! [catch {exec git branch} gitout] &&
250 [regexp {[*] ([\w]+)} $gitout res branch] } {
ffc26091 251 set prefix "${branch}_"
b725d7c5 252 }
6d368502 253 set logdir "results/${prefix}[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
096ef695 254
255 if { [array names ::env OCCT_SHARE_PATH] != "" && "$::env(OCCT_SHARE_PATH)" != ""} {
256 set logdir "$::env(OCCT_SHARE_PATH)/${logdir}"
257 }
258
6d368502 259 set logdir [file normalize $logdir]
40093367 260 }
261 if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
6d368502 262 error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
40093367 263 }
264 if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
6d368502 265 error "Error: Cannot create directory \"$logdir\", or it is not writable"
40093367 266 }
267
87f42a3f 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 * }
272
40093367 273 ######################################################
274 # prepare list of tests to be performed
275 ######################################################
276
277 # list of tests, each defined by a list of:
278 # test scripts directory
279 # group (subfolder) name
280 # grid (subfolder) name
281 # test case name
282 # path to test case file
283 set tests_list {}
284
285 # iterate by all script paths
2124e769 286 foreach dir [lsort -unique [_split_path $env(CSF_TestScriptsPath)]] {
6d368502 287 # protection against empty paths
288 set dir [string trim $dir]
289 if { $dir == "" } { continue }
40093367 290
6d368502 291 if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
40093367 292
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"
6d368502 296 continue
40093367 297 }
298
6d368502 299 # search all directories in the current dir with specified mask
300 if [catch {glob -directory $dir -tail -types d {*}$groupmask} groups] { continue }
40093367 301
6d368502 302 # iterate by groups
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" }
40093367 306
6d368502 307 # file grids.list must exist: it defines sequence of grids in the group
40093367 308 if { ! [file exists $dir/$group/grids.list] } {
6d368502 309 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
310 continue
311 }
312
313 # read grids.list file and make a list of grids to be executed
314 set gridlist {}
315 set fd [open $dir/$group/grids.list]
316 set nline 0
317 while { [gets $fd line] >= 0 } {
318 incr nline
319
320 # skip comments and empty lines
321 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
322 if { [string trim $line] == "" } { continue }
323
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"
327 continue
328 }
329
330 # check that grid fits into the specified mask
87f42a3f 331 foreach mask $gridmask {
6d368502 332 if { $mask == $gridid || [string match $mask $grid] } {
333 lappend gridlist $grid
334 }
335 }
336 }
337 close $fd
338
339 # iterate by all grids
340 foreach grid $gridlist {
341
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]]
87f42a3f 348 }
6d368502 349 close $fd
350 }
351
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"
355 continue
356 }
357
358 # create directory for logging test results
359 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
360
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" ||
87f42a3f 367 $casename == "parse.rules" } {
6d368502 368 continue
87f42a3f 369 }
40093367 370
6d368502 371 lappend tests_list [list $dir $group $grid $casename $casefile]
372 }
373 }
374 }
40093367 375 }
376 if { [llength $tests_list] < 1 } {
6d368502 377 error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
433673e0 378 } else {
6d368502 379 puts "Running tests (total [llength $tests_list] test cases)..."
40093367 380 }
381
382 ######################################################
383 # run tests
384 ######################################################
385
386 # log command arguments and environment
9753e6de 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:"
8a262fa1 392 foreach envar [lsort [array names env]] {
6d368502 393 lappend log "$envar=\"$env($envar)\""
40093367 394 }
9753e6de 395 lappend log ""
40093367 396
397 set refresh_timer [clock seconds]
398 uplevel dchrono _timer reset
399 uplevel dchrono _timer start
400
401 # if parallel execution is requested, allocate thread pool
402 if { $parallel > 0 } {
6d368502 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"
405 set parallel 0
406 } else {
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" }
9753e6de 412 # limit number of jobs in the queue by reasonable value
413 # to prevent slowdown due to unnecessary queue processing
414 set nbpooled 0
415 set nbpooled_max [expr 10 * $parallel]
416 set nbpooled_ok [expr 5 * $parallel]
6d368502 417 }
40093367 418 }
419
420 # start test cases
8a262fa1 421 set userbreak 0
40093367 422 foreach test_def $tests_list {
8a262fa1 423 # check for user break
9753e6de 424 if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
8a262fa1 425 set userbreak 1
426 break
427 }
428
6d368502 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]
434
435 # command to set tests for generation of image in results directory
436 set imgdir_cmd ""
437 if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
438
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"
444
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\]"
449 } else {
450 # else try to use old-style QA_ variables to get more output...
451 set env(QA_DUMP) 1
452 set env(QA_DUP) 1
453 set env(QA_print_command) 1
454 }
455
456 # final 'exit' is needed when running on Linux under VirtualGl
457 puts $fd_cmd "exit"
458 close $fd_cmd
8418c617 459
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
6d368502 463 set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
464
465 # alternative method to run without temporary file; disabled as it needs too many backslashes
466 # else {
467 # set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
468 # _run_test $dir $group $grid $casefile\\\; \
469 # puts \\\[dlog get\\\]\\\; exit"
470 # }
471
472 # run test case, either in parallel or sequentially
473 if { $parallel > 0 } {
474 # parallel execution
475 set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
476 set job_def($job) [list $logdir $dir $group $grid $casename]
9753e6de 477 incr nbpooled
478 if { $nbpooled > $nbpooled_max } {
479 _testgrid_process_jobs $worker $nbpooled_ok
480 }
6d368502 481 } else {
482 # sequential execution
483 catch {eval $command} output
484 _log_test_case $output $logdir $dir $group $grid $casename log
485
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]
491 }
492 }
40093367 493 }
494
495 # get results of started threads
496 if { $parallel > 0 } {
9753e6de 497 _testgrid_process_jobs $worker
6d368502 498 # release thread pool
9753e6de 499 if { $nbpooled > 0 } {
6d368502 500 tpool::cancel $worker [array names job_def]
9753e6de 501 }
502 catch {tpool::resume $worker}
6d368502 503 tpool::release $worker
40093367 504 }
505
506 uplevel dchrono _timer stop
507 set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
508
8a262fa1 509 if { $userbreak } {
9753e6de 510 _log_and_puts log "*********** Stopped by user break ***********"
8a262fa1 511 set time "${time} \nNote: the process is not finished, stopped by user break!"
512 }
513
40093367 514 ######################################################
515 # output summary logs and exit
516 ######################################################
517
518 _log_summarize $logdir $log $time
519 if { $logdir != "" } {
6d368502 520 puts "Detailed logs are saved in $logdir"
40093367 521 }
522 if { $logdir != "" && $xmlfile != "" } {
6d368502 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]
526 }
527 _log_xml_summary $logdir $xmlfile $log 0
528 puts "XML summary is saved to $xmlfile"
40093367 529 }
433673e0 530 # play sound signal at the end of test
531 if {$signal} {
6d368502 532 puts "\7\7\7\7"
433673e0 533 }
40093367 534 return
535}
536
22db40eb 537# Procedure to regenerate summary log from logs of test cases
538help testsummarize {
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
543}
544proc testsummarize {dir} {
545 global _test_case_regexp
546
547 if { ! [file isdirectory $dir] } {
6d368502 548 error "Error: \"$dir\" is not a directory"
22db40eb 549 }
550
551 # get summary statements from all test cases in one log
9753e6de 552 set log {}
22db40eb 553
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]
559 set nbfound 0
560 set fd [open $file r]
6d368502 561 while { [gets $fd line] >= 0 } {
562 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
22db40eb 563 if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } {
564 puts "Error: $file contains status line for another test case ($line)"
565 }
6d368502 566 lappend log $line
567 incr nbfound
568 }
569 }
22db40eb 570 close $fd
571
572 if { $nbfound != 1 } {
573 puts "Error: $file contains $nbfound status lines, expected 1"
574 }
575 }
576 }
577
578 _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
579 return
580}
581
cc6a292d 582# Procedure to compare results of two runs of test cases
b725d7c5 583help testdiff {
584 Compare results of two executions of tests (CPU times, ...)
22db40eb 585 Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
b725d7c5 586 Where dir1 and dir2 are directories containing logs of two test runs.
587 Allowed options are:
22db40eb 588 -save filename: save resulting log in specified file (default name is
60874ff8 589 <dir1>/diff-<dir2>.log); HTML log is saved with same name
22db40eb 590 and extension .html
b725d7c5 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
595 -verbose level:
596 1 - output only differences
22db40eb 597 2 - output also list of logs and directories present in one of dirs only
598 3 - (default) output also progress messages
d5f061b6 599 -highlight_percent value: highlight considerable (>value in %) deviations
600 of CPU and memory (default value is 5%)
cc6a292d 601}
602proc testdiff {dir1 dir2 args} {
603 if { "$dir1" == "$dir2" } {
6d368502 604 error "Input directories are the same"
cc6a292d 605 }
606
607 ######################################################
608 # check arguments
609 ######################################################
610
611 # treat options
22db40eb 612 set logfile [file join $dir1 "diff-[file tail $dir2].log"]
cc6a292d 613 set basename ""
614 set status "same"
615 set verbose 3
6d368502 616 set highlight_percent 5
cc6a292d 617 for {set narg 0} {$narg < [llength $args]} {incr narg} {
6d368502 618 set arg [lindex $args $narg]
619
620 # log file name
621 if { $arg == "-save" } {
622 incr narg
623 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
624 set logfile [lindex $args $narg]
625 } else {
626 error "Error: Option -save must be followed by log file name"
627 }
628 continue
629 }
630
631 # status filter
632 if { $arg == "-status" } {
633 incr narg
634 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
635 set status [lindex $args $narg]
636 } else {
637 set status ""
638 }
639 if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
640 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
641 }
642 continue
643 }
644
645 # verbose level
646 if { $arg == "-verbose" } {
647 incr narg
648 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
649 set verbose [expr [lindex $args $narg]]
650 } else {
651 error "Error: Option -verbose must be followed by integer verbose level"
652 }
653 continue
654 }
655
656 # highlight_percent
657 if { $arg == "-highlight_percent" } {
658 incr narg
659 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
660 set highlight_percent [expr [lindex $args $narg]]
661 } else {
662 error "Error: Option -highlight_percent must be followed by integer value"
663 }
664 continue
665 }
666
667 if { [regexp {^-} $arg] } {
668 error "Error: unsupported option \"$arg\""
669 }
22db40eb 670
671 # non-option arguments form a subdirectory path
6d368502 672 set basename [file join $basename $arg]
cc6a292d 673 }
674
675 # run diff procedure (recursive)
676 _test_diff $dir1 $dir2 $basename $status $verbose log
677
678 # save result to log file
679 if { "$logfile" != "" } {
9753e6de 680 _log_save $logfile [join $log "\n"]
d5f061b6 681 _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2 ${highlight_percent}
22db40eb 682 puts "Log is saved to $logfile (and .html)"
cc6a292d 683 }
684
685 return
686}
687
351bbcba 688# Procedure to check data file before adding it to repository
689help testfile {
690 Check data file and prepare it for putting to test data files repository.
691 Use: testfile [filelist]
692
693 Will report if:
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).
698
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
60874ff8 701 loaded shape (if any), and makes snapshot (in the temporary directory).
351bbcba 702 Finally it advises whether the file should be put to public section of the
703 repository.
704}
705proc testfile {filelist} {
706 global env
707
708 # check that CSF_TestDataPath is defined
709 if { ! [info exists env(CSF_TestDataPath)] } {
710 error "Environment variable CSF_TestDataPath must be defined!"
711 }
712
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]
723
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?"
727 }
728 _check_file_format $file
729
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)"
735 } else {
736 puts "(files are same by content)"
737 }
738 puts "--> $file"
739 puts "--> $names($name_lower)"
740 continue
741 }
742
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:"
749 puts "--> $file"
750 puts "--> $other"
751 }
752 }
753 }
754
755 # add the file to the registry
756 set names($name_lower) $file
757 lappend sizes($size) $file
6d368502 758 }
759 }
351bbcba 760 }
761 if { [llength $filelist] <= 0 } { return }
762
763 # check the new files
764 set has_images f
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"
770 }
771
772 set name [file tail $file]
773 set name_lower [string tolower $name]
774
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)"
779 } else {
780 puts "$file: OK: already in the repository \n--> $names($name_lower)"
781 continue
782 }
783 }
784
785 # check if file with the same content exists
786 set size [file size $file]
787 if { [info exists sizes($size)] } {
788 set found f
789 foreach other $sizes($size) {
790 if { ! [_diff_files $file $other] } {
6d368502 791 puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
792 set found t
793 break
351bbcba 794 }
795 }
796 if { $found } { continue }
797 }
798
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"
803 continue
804 }
805
806 # get number of faces and edges
807 set edges 0
808 set faces 0
809 set nbs [uplevel nbshapes a]
810 regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
811 regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
812
813 # classify; first check file size and number of faces and edges
814 if { $size < 95000 && $faces < 20 && $edges < 100 } {
815 set dir public
816 } else {
817 set dir private
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] } {
822 set dir old
823 }
824 }
825
826 # add stats
827 puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
828
60874ff8 829 set tmpdir [_get_temp_dir]
830 file mkdir $tmpdir/$dir
351bbcba 831
832 # make snapshot
833 pload AISV
834 uplevel vdisplay a
835 uplevel vfit
836 uplevel vzfit
60874ff8 837 uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
351bbcba 838 set has_images t
839 }
840 if { $has_images } {
60874ff8 841 puts "Snapshots are saved in subdirectory [_get_temp_dir]"
351bbcba 842 }
843}
844
22db40eb 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.
852proc locate_data_file {filename} {
853 global env groupname gridname casename
854
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]
6d368502 859 if { [file exists $path] } {
860 return [file normalize $path]
861 }
22db40eb 862 }
863
864 # check sub-directories in paths indicated by CSF_TestDataPath
865 if { [info exists env(CSF_TestDataPath)] } {
6d368502 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]
80482e01 870 # skip directories starting with dot
871 if { [regexp {^[.]} $name] } { continue }
6d368502 872 if { [file exists $name/$filename] } {
873 return [file normalize $name/$filename]
874 }
875 eval lappend dir [glob -nocomplain -directory $name -type d *]
876 }
877 }
22db40eb 878 }
879
880 # check current datadir
881 if { [file exists [uplevel datadir]/$filename] } {
6d368502 882 return [file normalize [uplevel datadir]/$filename]
22db40eb 883 }
884
885 # raise error
c97067ad 886 error [join [list "File $filename could not be found" \
6d368502 887 "(should be in paths indicated by CSF_TestDataPath environment variable, " \
22db40eb 888 "or in subfolder data in the script directory)"] "\n"]
889}
890
40093367 891# Internal procedure to find test case indicated by group, grid, and test case names;
892# returns:
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
897proc _get_test {group grid casename _dir _gridname _casefile} {
898 upvar $_dir dir
899 upvar $_gridname gridname
900 upvar $_casefile casefile
901
902 global env
903
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"
908 }
909
910 # iterate by all script paths
911 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
6d368502 912 # protection against empty paths
913 set dir [string trim $dir]
914 if { $dir == "" } { continue }
40093367 915
916 # check that directory exists
917 if { ! [file isdirectory $dir] } {
918 puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
6d368502 919 continue
40093367 920 }
921
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 }
925
926 # check that grid with given name (possibly alias) exists; stop otherwise
927 set gridname $grid
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] } {
935 break
936 }
937 }
938 close $fd
6d368502 939 }
940 }
40093367 941 if { ! [file isdirectory $dir/$group/$gridname] } { continue }
942
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]
951 }
6d368502 952 close $fd
953 }
40093367 954 }
955 if { [file exists $casefile] } {
956 # normal return
957 return
958 }
959 }
960
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" \
6d368502 963 "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
40093367 964}
965
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".
5df3a117 969proc _run_test {scriptsdir group gridname casefile echo} {
40093367 970 global env
971
972 # start timer
973 uplevel dchrono _timer reset
974 uplevel dchrono _timer start
433673e0 975 catch {uplevel meminfo h} membase
40093367 976
977 # enable commands logging; switch to old-style mode if dlog command is not present
978 set dlog_exists 1
979 if { [catch {dlog reset}] } {
6d368502 980 set dlog_exists 0
5df3a117 981 } elseif { $echo } {
982 decho on
40093367 983 } else {
6d368502 984 dlog reset
985 dlog on
986 rename puts puts-saved
987 proc puts args {
988 global _tests_verbose
989
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]
995 } else {
996 eval puts-saved $args
997 }
998 } else {
999 dlog add [lindex $args end]
1000 }
1001 }
40093367 1002 }
1003
40093367 1004 # evaluate test case
936f43da 1005 set tmp_imagedir 0
40093367 1006 if [catch {
60874ff8 1007 # set variables identifying test case
6d368502 1008 uplevel set casename [file tail $casefile]
1009 uplevel set groupname $group
1010 uplevel set gridname $gridname
1011 uplevel set dirname $scriptsdir
40093367 1012
6d368502 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
a3ef6605 1016
1017 # create subdirectory in temp named after group and grid with timestamp
1018 set rootlogdir [_get_temp_dir]
1019
1020 set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
1021 set imagedir [file normalize ${rootlogdir}/$imagedir]
1022
1023 if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1024 ! [catch {glob -directory $imagedir *}] } {
6d368502 1025 # puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
a3ef6605 1026 set imagedir $rootlogdir
1027 }
1028
d16b64f1 1029 uplevel set imagedir \"$imagedir\"
936f43da 1030 set tmp_imagedir 1
6d368502 1031 }
60874ff8 1032
6d368502 1033 # execute test scripts
40093367 1034 if { [file exists $scriptsdir/$group/begin] } {
6d368502 1035 puts "Executing $scriptsdir/$group/begin..."; flush stdout
1036 uplevel source $scriptsdir/$group/begin
1037 }
1038 if { [file exists $scriptsdir/$group/$gridname/begin] } {
1039 puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1040 uplevel source $scriptsdir/$group/$gridname/begin
1041 }
1042
1043 puts "Executing $casefile..."; flush stdout
1044 uplevel source $casefile
1045
1046 if { [file exists $scriptsdir/$group/$gridname/end] } {
1047 puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1048 uplevel source $scriptsdir/$group/$gridname/end
1049 }
1050 if { [file exists $scriptsdir/$group/end] } {
1051 puts "Executing $scriptsdir/$group/end..."; flush stdout
1052 uplevel source $scriptsdir/$group/end
1053 }
40093367 1054 } res] {
6d368502 1055 puts "Tcl Exception: $res"
40093367 1056 }
1057
40093367 1058 # stop logging
1059 if { $dlog_exists } {
5df3a117 1060 if { $echo } {
6d368502 1061 decho off
5df3a117 1062 } else {
1063 rename puts {}
6d368502 1064 rename puts-saved puts
1065 dlog off
1066 }
40093367 1067 }
1068
8418c617 1069 # stop cpulimit killer if armed by the test
1070 cpulimit
1071
22db40eb 1072 # add memory and timing info
1073 set stats ""
433673e0 1074 if { ! [catch {uplevel meminfo h} memuse] } {
936f43da 1075 append stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
22db40eb 1076 }
40093367 1077 uplevel dchrono _timer stop
1078 set time [uplevel dchrono _timer show]
936f43da 1079 if { [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu_usr] } {
6d368502 1080 append stats "TOTAL CPU TIME: $cpu_usr sec\n"
22db40eb 1081 }
1082 if { $dlog_exists && ! $echo } {
6d368502 1083 dlog add $stats
22db40eb 1084 } else {
6d368502 1085 puts $stats
40093367 1086 }
936f43da 1087
1088 # unset global vars
1089 uplevel unset casename groupname gridname dirname
1090 if { $tmp_imagedir } { uplevel unset imagedir test_image }
40093367 1091}
1092
1093# Internal procedure to check log of test execution and decide if it passed or failed
5fd3308a 1094proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
40093367 1095 global env
1096 if { $_summary != "" } { upvar $_summary summary }
1097 if { $_html_log != "" } { upvar $_html_log html_log }
9753e6de 1098 set summary {}
1099 set html_log {}
5fd3308a 1100 set errors_log {}
40093367 1101
6d368502 1102 if [catch {
1103
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
1107 set badwords {}
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 }
1114 # extract regexp
1115 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } {
1116 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1117 continue
1118 }
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]
1123 }
1124 close $fd
1125 }
1126 if { [llength $badwords] <= 0 } {
1127 puts "Warning: no definition of error indicators found (check files parse.rules)"
1128 }
1129
1130 # analyse log line-by-line
1131 set todos {} ;# TODO statements
1132 set requs {} ;# REQUIRED statements
1133 set todo_incomplete -1
1134 set status ""
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
1142 }
1143
1144 # record TODOs that mark unstable cases
1145 if { [regexp {[\?]} $platforms] } {
1146 set todos_unstable([llength $todos]) 1
1147 }
1148
1149 # convert legacy regexps from Perl to Tcl style
1150 set pattern [regsub -all {\\b} [string trim $pattern] {\\y}]
1151
1152 # special case: TODO TEST INCOMPLETE
1153 if { [string trim $pattern] == "TEST INCOMPLETE" } {
1154 set todo_incomplete [llength $todos]
1155 }
1156
1157 lappend todos [list $pattern [llength $html_log] $line]
1158 lappend html_log [_html_highlight BAD $line]
1159 continue
1160 }
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
1166 }
1167 lappend requs [list $pattern [llength $html_log] $line]
1168 lappend html_log [_html_highlight OK $line]
1169 continue
1170 }
1171
1172 # check for presence of required messages
1173 set ismarked 0
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]
1179 set ismarked 1
1180 continue
1181 }
1182 }
1183 if { $ismarked } {
1184 continue
1185 }
1186
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
1191 set is_known 0
1192 for {set i 0} {$i < [llength $todos]} {incr i} {
1193 set pattern [lindex $todos $i 0]
1194 if { [regexp $pattern $line] } {
1195 set is_known 1
1196 incr todo_count($i)
1197 lappend html_log [_html_highlight BAD $line]
1198 break
1199 }
1200 }
1201
1202 # if it is not in todo, define status
1203 if { ! $is_known } {
1204 set stat [lindex $bw 0 0]
1205 if {$errors} {
1206 lappend errors_log $line
1207 }
1208 lappend html_log [_html_highlight $stat $line]
1209 if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1210 set status [lindex $bw 0]
1211 }
1212 }
1213 set ismarked 1
1214 break
1215 }
1216 }
1217 if { ! $ismarked } {
1218 lappend html_log $line
1219 }
1220 }
1221
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)
1227 } else {
1228 set status "FAILED (no final message is found)"
1229 }
1230 }
1231
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)"
1239 }
1240 }
1241 }
1242
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)"
1254 break;
1255 }
1256 }
1257 }
1258
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)"
1262 }
1263
1264 # report normal OK
1265 if { $status == "" } {set status "OK" }
1266
1267 } res] {
1268 set status "FAILED ($res)"
1269 }
40093367 1270
1271 # put final message
1272 _log_and_puts summary "CASE $group $gridname $casename: $status"
9753e6de 1273 set summary [join $summary "\n"]
5fd3308a 1274 if {$errors} {
6d368502 1275 foreach error $errors_log {
1276 _log_and_puts summary " $error"
1277 }
5fd3308a 1278 }
9753e6de 1279 set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
40093367 1280}
1281
1282# Auxiliary procedure putting message to both cout and log variable (list)
1283proc _log_and_puts {logvar message} {
1284 if { $logvar != "" } {
6d368502 1285 upvar $logvar log
1286 lappend log $message
40093367 1287 }
1288 puts $message
1289}
1290
1291# Auxiliary procedure to log result on single test case
1292proc _log_test_case {output logdir dir group grid casename logvar} {
1293 upvar $logvar log
5fd3308a 1294 set show_errors 0
40093367 1295 # check result and make HTML log
5fd3308a 1296 _check_log $dir $group $grid $casename $show_errors $output summary html_log
9753e6de 1297 lappend log $summary
40093367 1298
1299 # save log to file
1300 if { $logdir != "" } {
6d368502 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"
40093367 1303 }
1304}
1305
1306# Auxiliary procedure to save log to file
1307proc _log_save {file log {title {}}} {
1308 # create missing directories as needed
1309 catch {file mkdir [file dirname $file]}
1310
1311 # try to open a file
1312 if [catch {set fd [open $file w]} res] {
6d368502 1313 error "Error saving log file $file: $res"
40093367 1314 }
1315
1316 # dump log and close
1317 puts $fd "$title\n"
1318 puts $fd $log
1319 close $fd
1320 return
1321}
1322
22db40eb 1323# Auxiliary procedure to make a (relative if possible) URL to a file for
1324# inclusion a reference in HTML log
1325proc _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]]"
1332 }
1333 }
1334
1335 # if relative path could not be made, return full file URL
1336 return "file://[file normalize $file]"
1337}
1338
40093367 1339# Auxiliary procedure to save log to file
1340proc _log_html {file log {title {}}} {
1341 # create missing directories as needed
1342 catch {file mkdir [file dirname $file]}
1343
1344 # try to open a file
1345 if [catch {set fd [open $file w]} res] {
6d368502 1346 error "Error saving log file $file: $res"
40093367 1347 }
1348
1349 # print header
22db40eb 1350 puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
40093367 1351
ffc26091 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
40093367 1355 set imgbasename [file rootname [file tail $file]]
ffc26091 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]] {
6d368502 1360 puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
40093367 1361 }
1362
b725d7c5 1363 # print log body, trying to add HTML links to script files on lines like
1364 # "Executing <filename>..."
40093367 1365 puts $fd "<pre>"
b725d7c5 1366 foreach line [split $log "\n"] {
1367 if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1368 [file exists $script] } {
22db40eb 1369 set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
b725d7c5 1370 }
1371 puts $fd $line
1372 }
40093367 1373 puts $fd "</pre></body></html>"
1374
1375 close $fd
1376 return
1377}
1378
1379# Auxiliary method to make text with HTML highlighting according to status
1380proc _html_color {status} {
1381 # choose a color for the cell according to result
1382 if { $status == "OK" } {
6d368502 1383 return lightgreen
40093367 1384 } elseif { [regexp -nocase {^FAIL} $status] } {
6d368502 1385 return red
40093367 1386 } elseif { [regexp -nocase {^BAD} $status] } {
6d368502 1387 return yellow
40093367 1388 } elseif { [regexp -nocase {^IMP} $status] } {
6d368502 1389 return orange
40093367 1390 } elseif { [regexp -nocase {^SKIP} $status] } {
6d368502 1391 return gray
40093367 1392 } elseif { [regexp -nocase {^IGNOR} $status] } {
6d368502 1393 return gray
40093367 1394 } else {
6d368502 1395 puts "Warning: no color defined for status $status, using red as if FAILED"
1396 return red
40093367 1397 }
1398}
1399
1400# Format text line in HTML to be colored according to the status
1401proc _html_highlight {status line} {
1402 return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1403}
1404
1405# Internal procedure to generate HTML page presenting log of the tests
1406# execution in tabular form, with links to reports on individual cases
1407proc _log_html_summary {logdir log totals regressions improvements total_time} {
1408 global _test_case_regexp
1409
9753e6de 1410 # create missing directories as needed
1411 file mkdir $logdir
40093367 1412
1413 # try to open a file and start HTML
1414 if [catch {set fd [open $logdir/summary.html w]} res] {
6d368502 1415 error "Error creating log file: $res"
40093367 1416 }
1417
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 == "" } {
6d368502 1422 puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
40093367 1423 }
1424 puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1425 puts $fd "</head><body>"
1426
1427 # put summary
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 {
6d368502 1435 set status [lindex $nbstat 1]
1436 if { [info exists legend($status)] } {
1437 set comment $legend($status)
1438 } else {
1439 set comment "User-defined status"
1440 }
1441 puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
40093367 1442 }
1443 puts $fd "</table>"
1444
1445 # time stamp and elapsed time info
1446 if { $total_time != "" } {
6d368502 1447 puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
8a262fa1 1448 puts $fd [join [split $total_time "\n"] "<p>"]
40093367 1449 } else {
6d368502 1450 puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
40093367 1451 }
1452
1453 # print regressions and improvements
1454 foreach featured [list $regressions $improvements] {
6d368502 1455 if { [llength $featured] <= 1 } { continue }
1456 set status [string trim [lindex $featured 0] { :}]
1457 puts $fd "<h2>$status</h2>"
1458 puts $fd "<table>"
1459 set groupgrid ""
1460 foreach test [lrange $featured 1 end] {
1461 if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1462 set gg UNKNOWN
1463 set name "Error building short list; check details"
1464 }
1465 if { $gg != $groupgrid } {
1466 if { $groupgrid != "" } { puts $fd "</tr>" }
1467 set groupgrid $gg
1468 puts $fd "<tr><td>$gg</td>"
1469 }
1470 puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1471 }
1472 if { $groupgrid != "" } { puts $fd "</tr>" }
1473 puts $fd "</table>"
40093367 1474 }
1475
9753e6de 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;\">"
40093367 1479
1480 # process log line-by-line
1481 set group {}
1482 set letter {}
9753e6de 1483 set body {}
1484 foreach line [lsort -dictionary $log] {
6d368502 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] } {
1487 continue
1488 }
1489
1490 # start new group
1491 if { $grp != $group } {
1492 if { $letter != "" } { lappend body "</tr></table>" }
1493 set letter {}
1494 set group $grp
1495 set grid {}
1496 puts $fd "<a href=\"#$group\">$group</a><br>"
1497 lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1498 }
1499
1500 # start new grid
1501 if { $grd != $grid } {
1502 if { $letter != "" } { lappend body "</tr></table>" }
1503 set letter {}
1504 set grid $grd
1505 puts $fd "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#$group-$grid\">$grid</a><br>"
1506 lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1507 }
1508
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] &&
9753e6de 1512 ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
6d368502 1513 set alnum $casename
1514 }
40093367 1515
6d368502 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>"
1520 } else {
1521 lappend body "<table><tr>"
1522 }
1523 set letter $alnum
1524 }
40093367 1525
6d368502 1526 lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
40093367 1527 }
9753e6de 1528 puts $fd "</div>\n[join $body "\n"]</tr></table>"
40093367 1529
1530 # add remaining lines of log as plain text
1531 puts $fd "<h2>Plain text messages</h2>\n<pre>"
9753e6de 1532 foreach line $log {
6d368502 1533 if { ! [regexp $_test_case_regexp $line] } {
1534 puts $fd "$line"
1535 }
40093367 1536 }
1537 puts $fd "</pre>"
1538
1539 # close file and exit
1540 puts $fd "</body>"
1541 close $fd
1542 return
1543}
1544
1545# Procedure to dump summary logs of tests
1546proc _log_summarize {logdir log {total_time {}}} {
1547
1548 # sort log records alphabetically to have the same behavior on Linux and Windows
1549 # (also needed if tests are run in parallel)
9753e6de 1550 set loglist [lsort -dictionary $log]
40093367 1551
1552 # classify test cases by status
1553 foreach line $loglist {
6d368502 1554 if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1555 lappend stat($status) $caseid
1556 }
40093367 1557 }
1558 set totals {}
1559 set improvements {Improvements:}
1560 set regressions {Failed:}
1561 if { [info exists stat] } {
6d368502 1562 foreach status [lsort [array names stat]] {
1563 lappend totals [list [llength $stat($status)] $status]
1564
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)
1570 }
1571 }
40093367 1572 }
1573
1574 # if time is specified, add totals
1575 if { $total_time != "" } {
6d368502 1576 if { [llength $improvements] > 1 } {
1577 _log_and_puts log [join $improvements "\n "]
1578 }
1579 if { [llength $regressions] > 1 } {
1580 _log_and_puts log [join $regressions "\n "]
1581 }
1582 if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1583 _log_and_puts log "No regressions"
1584 }
1585 _log_and_puts log "Total cases: [join $totals {, }]"
1586 _log_and_puts log $total_time
40093367 1587 }
1588
1589 # save log to files
1590 if { $logdir != "" } {
6d368502 1591 _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1592 _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
40093367 1593 }
1594
1595 return
1596}
1597
1598# Internal procedure to generate XML log in JUnit style, for further
1599# consumption by Jenkins or similar systems.
1600#
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
1603#
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
1606proc _log_xml_summary {logdir filename log include_cout} {
1607 global _test_case_regexp
1608
1609 catch {file mkdir [file dirname $filename]}
1610
1611 # try to open a file and start XML
1612 if [catch {set fd [open $filename w]} res] {
6d368502 1613 error "Error creating XML summary file $filename: $res"
40093367 1614 }
1615 puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1616 puts $fd "<testsuites>"
1617
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"}
1621
1622 # sort log and process it line-by-line
1623 set group {}
9753e6de 1624 foreach line [lsort -dictionary $log] {
6d368502 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] } {
1627 continue
1628 }
1629 set message [string trim $message " \t\r\n()"]
1630
1631 # start new testsuite for each grid
1632 if { $grp != $group || $grd != $grid } {
1633
1634 # write previous test suite
1635 if [info exists testcases] { eval $cmd_testsuite }
1636
1637 set testcases {}
1638 set nbtests 0
1639 set nberr 0
1640 set nbfail 0
1641 set nbskip 0
1642 set time 0.
1643
1644 set group $grp
1645 set grid $grd
1646 }
1647
1648 incr nbtests
1649
1650 # parse test log and get its CPU time
1651 set testout {}
1652 set add_cpu {}
1653 if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } {
1654 puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1655 } else {
1656 while { [gets $fdlog logline] >= 0 } {
1657 if { $include_cout } {
1658 append testout "$logline\n"
1659 }
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]
1663 }
1664 }
1665 close $fdlog
1666 }
1667 if { ! $include_cout } {
40093367 1668 set testout "$line\n"
6d368502 1669 }
1670
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] } {
1677 incr nberr
1678 append testcases "\n <error name=\"$result\" message=\"$message\"/>"
1679 } elseif { [regexp -nocase {^BAD} $result] } {
1680 incr nbskip
1681 append testcases "\n <skipped>$message</skipped>"
1682 } else {
1683 incr nbfail
1684 append testcases "\n <failure name=\"$result\" message=\"$message\"/>"
1685 }
1686 }
1687 append testcases "\n </testcase>"
40093367 1688 }
1689
1690 # write last test suite
1691 if [info exists testcases] { eval $cmd_testsuite }
1692
1693 # the end
1694 puts $fd "</testsuites>"
1695 close $fd
1696 return
1697}
1698
1699# define custom platform name
1700proc _tests_platform_def {} {
1701 global env tcl_platform
1702
1703 if [info exists env(os_type)] { return }
40093367 1704 set env(os_type) $tcl_platform(platform)
6d368502 1705 if { $tcl_platform(os) == "Linux" } {
37d6975c 1706 set env(os_type) Linux
40093367 1707 }
6d368502 1708 if { $tcl_platform(os) == "Darwin" } {
37d6975c 1709 set env(os_type) MacOS
1710 }
40093367 1711}
1712_tests_platform_def
1713
1714# Auxiliary procedure to split path specification (usually defined by
1715# environment variable) into list of directories or files
1716proc _split_path {pathspec} {
1717 global tcl_platform
1718
1719 # first replace all \ (which might occur on Windows) by /
1720 regsub -all "\\\\" $pathspec "/" pathspec
1721
1722 # split path by platform-specific separator
1723 return [split $pathspec [_path_separator]]
1724}
1725
1726# Auxiliary procedure to define platform-specific separator for directories in
1727# path specification
1728proc _path_separator {} {
1729 global tcl_platform
1730
1731 # split path by platform-specific separator
1732 if { $tcl_platform(platform) == "windows" } {
6d368502 1733 return ";"
40093367 1734 } else {
6d368502 1735 return ":"
40093367 1736 }
1737}
1738
cc6a292d 1739# Procedure to make a diff and common of two lists
1740proc _list_diff {list1 list2 _in1 _in2 _common} {
1741 upvar $_in1 in1
1742 upvar $_in2 in2
1743 upvar $_common common
1744
1745 set in1 {}
1746 set in2 {}
1747 set common {}
1748 foreach item $list1 {
6d368502 1749 if { [lsearch -exact $list2 $item] >= 0 } {
1750 lappend common $item
cc6a292d 1751 } else {
6d368502 1752 lappend in1 $item
1753 }
cc6a292d 1754 }
1755 foreach item $list2 {
6d368502 1756 if { [lsearch -exact $common $item] < 0 } {
1757 lappend in2 $item
1758 }
cc6a292d 1759 }
1760 return
1761}
1762
1763# procedure to load a file to Tcl string
1764proc _read_file {filename} {
1765 set fd [open $filename r]
1766 set result [read -nonewline $fd]
1767 close $fd
1768 return $result
1769}
1770
22db40eb 1771# procedure to construct name for the mage diff file
1772proc _diff_img_name {dir1 dir2 casepath imgfile} {
1773 return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1774}
1775
936f43da 1776# auxiliary procedure to produce string comparing two values
1777proc _diff_show_ratio {value1 value2} {
1778 return "$value1 / $value2 \[[format "%+5.2f%%" [expr 100 * ($value1 - $value2) / double($value2)]]\]"
1779}
1780
cc6a292d 1781# Procedure to compare results of two runs of test cases
1782proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1783 upvar $_logvar log
1784
22db40eb 1785 # make sure to load diffimage command
1786 uplevel pload VISUALIZATION
1787
cc6a292d 1788 # prepare variable (array) for collecting statistics
1789 if { "$_statvar" != "" } {
1790 upvar $_statvar stat
1791 } else {
1792 set stat(cpu1) 0
1793 set stat(cpu2) 0
22db40eb 1794 set stat(mem1) 0
1795 set stat(mem2) 0
cc6a292d 1796 set log {}
1797 }
1798
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" }
1809 }
1810 foreach subdir $common {
1811 if { "$verbose" > 2 } {
6d368502 1812 _log_and_puts log "Checking [file join $basename $subdir]"
1813 }
1814 _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
cc6a292d 1815 }
1816 } else {
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" }
1824 }
936f43da 1825 set gcpu1 0
1826 set gcpu2 0
1827 set gmem1 0
1828 set gmem2 0
cc6a292d 1829 foreach logfile $common {
1830 # load two logs
6d368502 1831 set log1 [_read_file [file join $dir1 $basename $logfile]]
1832 set log2 [_read_file [file join $dir2 $basename $logfile]]
22db40eb 1833 set casename [file rootname $logfile]
cc6a292d 1834
1835 # check execution statuses
1836 set status1 UNDEFINED
1837 set status2 UNDEFINED
6d368502 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"
cc6a292d 1842
1843 # if test statuses are different, further comparison makes
6d368502 1844 # no sense unless explicitly requested
1845 if { "$status" != "all" } {
cc6a292d 1846 continue
6d368502 1847 }
1848 }
1849 if { "$status" == "ok" && "$status1" != "OK" } {
1850 continue
1851 }
cc6a292d 1852
1853 # check CPU times
1854 set cpu1 UNDEFINED
1855 set cpu2 UNDEFINED
6d368502 1856 if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1857 [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
cc6a292d 1858 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1859 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
936f43da 1860 set gcpu1 [expr $gcpu1 + $cpu1]
1861 set gcpu2 [expr $gcpu2 + $cpu2]
cc6a292d 1862
1863 # compare CPU times with 10% precision (but not less 0.5 sec)
6d368502 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]"
cc6a292d 1866 }
6d368502 1867 }
22db40eb 1868
1869 # check memory delta
1870 set mem1 UNDEFINED
1871 set mem2 UNDEFINED
6d368502 1872 if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1873 [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
22db40eb 1874 set stat(mem1) [expr $stat(mem1) + $mem1]
1875 set stat(mem2) [expr $stat(mem2) + $mem2]
936f43da 1876 set gmem1 [expr $gmem1 + $mem1]
1877 set gmem2 [expr $gmem2 + $mem2]
22db40eb 1878
1879 # compare memory usage with 10% precision (but not less 16 KiB)
6d368502 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]"
22db40eb 1882 }
6d368502 1883 }
22db40eb 1884
1885 # check images
936f43da 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}]
22db40eb 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" }
1892 }
1893 foreach imgfile $imgcommon {
6d368502 1894 # if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
22db40eb 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"
1903 } else {
1904 file delete -force $diffile ;# clean useless artifact of diffimage
1905 }
1906 }
6d368502 1907 }
936f43da 1908
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]"
1912 }
6d368502 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]"
936f43da 1915 }
cc6a292d 1916 }
1917
1918 if { "$_statvar" == "" } {
936f43da 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)]"
cc6a292d 1921 }
1922}
b725d7c5 1923
22db40eb 1924# Auxiliary procedure to save log of results comparison to file
d5f061b6 1925proc _log_html_diff {file log dir1 dir2 highlight_percent} {
22db40eb 1926 # create missing directories as needed
1927 catch {file mkdir [file dirname $file]}
1928
1929 # try to open a file
1930 if [catch {set fd [open $file w]} res] {
6d368502 1931 error "Error saving log file $file: $res"
22db40eb 1932 }
1933
1934 # print header
1935 puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
433673e0 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>"
22db40eb 1939
1940 # print log body, trying to add HTML links to script files on lines like
1941 # "Executing <filename>..."
1942 puts $fd "<pre>"
1943 set logpath [file split [file normalize $file]]
9753e6de 1944 foreach line $log {
d5f061b6 1945 # put a line; highlight considerable (> ${highlight_percent}%) deviations of CPU and memory
936f43da 1946 if { [regexp "\[\\\[](\[0-9.e+-]+)%\[\]]" $line res value] &&
d5f061b6 1947 [expr abs($value)] > ${highlight_percent} } {
936f43da 1948 puts $fd "<table><tr><td bgcolor=\"[expr $value > 0 ? \"red\" : \"lightgreen\"]\">$line</td></tr></table>"
1949 } else {
1950 puts $fd $line
1951 }
22db40eb 1952
936f43da 1953 # add images
22db40eb 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] } {
6d368502 1956 # note: special handler for the case if test grid directoried are compared directly
1957 set gridpath ""
22db40eb 1958 }
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]]\">"
1961
1962 set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1963 if { [file exists $difffile] } {
1964 set imgd "<img src=\"[_make_url $file $difffile]\">"
1965 } else {
1966 set imgd "N/A"
1967 }
1968
433673e0 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>"
22db40eb 1970 puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1971 }
1972 }
1973 puts $fd "</pre></body></html>"
1974
1975 close $fd
1976 return
1977}
1978
b725d7c5 1979# get number of CPUs on the system
1980proc _get_nb_cpus {} {
1981 global tcl_platform env
1982
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)
1988 }
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...
1993 }
1994 set nb 0
6d368502 1995 while { [gets $fd line] >= 0 } {
1996 if { [regexp {^processor[ \t]*:} $line] } {
1997 incr nb
1998 }
1999 }
b725d7c5 2000 close $fd
2001 return $nb
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] } {
2006 return $nb
2007 }
2008 }
2009
2010 # if cannot get good value, return 0 as default
2011 return 0
2012}
351bbcba 2013
2014# check two files for difference
2015proc _diff_files {file1 file2} {
2016 set fd1 [open $file1 "r"]
2017 set fd2 [open $file2 "r"]
2018
2019 set differ f
2020 while {! $differ} {
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] } {
2026 set differ t
2027 }
2028 }
2029
2030 close $fd1
2031 close $fd2
2032
2033 return $differ
2034}
2035
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.
2043proc _check_dos_encoding {file} {
2044 set fd [open $file rb]
2045 set isdos f
2046 if { [gets $fd line] && [regexp {.*\r$} $line] &&
2047 ! [regexp {^.PNG} $line] } {
2048 set isdos t
2049 }
2050 close $fd
2051 return $isdos
2052}
2053
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)
2056proc _check_file_format {file} {
2057 set fd [open $file rb]
2058 set line [read $fd 1024]
2059 close $fd
2060
2061 set warn f
2062 set ext [file extension $file]
2063 set format unknown
2064 if { [regexp {^DBRep_DrawableShape} $line] } {
2065 set format BREP
2066 if { "$ext" != ".brep" && "$ext" != ".rle" &&
2067 "$ext" != ".draw" && "$ext" != "" } {
2068 set warn t
2069 }
2070 } elseif { [regexp {^DrawTrSurf_} $line] } {
2071 set format DRAW
2072 if { "$ext" != ".rle" &&
2073 "$ext" != ".draw" && "$ext" != "" } {
2074 set warn t
2075 }
2076 } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2077 set format STEP
2078 if { "$ext" != ".step" && "$ext" != ".stp" } {
2079 set warn t
2080 }
2081 } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2082 set format IGES
2083 if { "$ext" != ".iges" && "$ext" != ".igs" } {
2084 set warn t
2085 }
2086 } elseif { "$ext" == ".igs" } {
2087 set format IGES
2088 } elseif { "$ext" == ".stp" } {
2089 set format STEP
2090 } else {
2091 set format [string toupper [string range $ext 1 end]]
2092 }
2093
2094 if { $warn } {
2095 puts "$file: Warning: extension ($ext) does not match format ($format)"
2096 }
2097
2098 return $format
2099}
2100
2101# procedure to load file knowing its format
2102proc load_data_file {file format shape} {
2103 switch $format {
6d368502 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" }
351bbcba 2110 }
2111}
60874ff8 2112
2113# procedure to get name of temporary directory,
2114# ensuring it is existing and writeable
2115proc _get_temp_dir {} {
723754e2 2116 global env tcl_platform
60874ff8 2117
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) /]
2125 }
2126 }
2127 }
2128
2129 # check platform-specific locations
2130 set fallback tmp
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)] } {
338434c7 2134 set fallback [regsub -all {\\} "$env(HOMEDRIVE)$env(HOMEPATH)/tmp" /]
60874ff8 2135 }
2136 } else {
2137 set paths "/tmp /var/tmp /usr/tmp"
2138 if { [info exists env(HOME)] } {
2139 set fallback "$env(HOME)/tmp"
2140 }
2141 }
2142 foreach dir $paths {
723754e2 2143 if { [file isdirectory $dir] && [file writable $dir] } {
60874ff8 2144 return $dir
2145 }
2146 }
2147
2148 # fallback case: use subdir /tmp of home or current dir
2149 file mkdir $fallback
2150 return $fallback
2151}
9753e6de 2152
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
2155# specified value
2156proc _testgrid_process_jobs {worker {nb_ok 0}} {
2157 # bind local vars to variables of the caller procedure
2158 upvar log log
2159 upvar logdir logdir
2160 upvar job_def job_def
2161 upvar nbpooled nbpooled
2162 upvar userbreak userbreak
2163 upvar refresh refresh
2164 upvar refresh_timer refresh_timer
2165
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
2170 unset job_def($job)
2171 incr nbpooled -1
2172 }
2173
2174 # check for user break
2175 if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2176 set userbreak 1
2177 }
2178
2179 # update summary log with requested period
2180 if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
6d368502 2181 _log_summarize $logdir $log
2182 set refresh_timer [clock seconds]
9753e6de 2183 }
2184 }
2185 catch {tpool::suspend $worker}
2186}
ccadc126 2187
2188help checkcolor {
2189 Check pixel color.
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)
2194}
2195# Procedure to check color using command vreadpixel with tolerance
2196proc 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"
2202
2203 if { $coord_x <= 1 || $coord_y <= 1 } {
6d368502 2204 puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2205 return -1
ccadc126 2206 }
2207
2208 set color ""
2209 catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2210 if {"$color" == ""} {
6d368502 2211 puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
ccadc126 2212 }
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)]
2222
2223 if { $rd_ch != 0 } {
6d368502 2224 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
ccadc126 2225 } else {
6d368502 2226 set tol_rd $rd_int
ccadc126 2227 }
2228 if { $gr_ch != 0 } {
6d368502 2229 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
ccadc126 2230 } else {
6d368502 2231 set tol_gr $gr_int
ccadc126 2232 }
2233 if { $bl_ch != 0 } {
6d368502 2234 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
ccadc126 2235 } else {
6d368502 2236 set tol_bl $bl_int
ccadc126 2237 }
2238
2239 set status 0
2240 if { $tol_rd > 0.2 } {
6d368502 2241 puts "Warning : RED light of additive color model RGB is invalid"
2242 set status 1
ccadc126 2243 }
2244 if { $tol_gr > 0.2 } {
6d368502 2245 puts "Warning : GREEN light of additive color model RGB is invalid"
2246 set status 1
ccadc126 2247 }
2248 if { $tol_bl > 0.2 } {
6d368502 2249 puts "Warning : BLUE light of additive color model RGB is invalid"
2250 set status 1
ccadc126 2251 }
2252
2253 if { $status != 0 } {
6d368502 2254 puts "Warning : Colors of default coordinate are not equal"
ccadc126 2255 }
2256
2257 global stat
2258 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
6d368502 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"
2263 return $stat
2264 } else {
2265 puts "Point with valid color was found"
2266 return $stat
2267 }
ccadc126 2268 } else {
6d368502 2269 set stat 1
ccadc126 2270 }
2271}
2272
2273# Procedure to check color in the point near default coordinate
2274proc _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]
2277 set mistake 0
2278 set i 0
2279 while { $mistake != 1 && $i <= 5 } {
6d368502 2280 set j 0
2281 while { $mistake != 1 && $j <= 5 } {
2282 set position_x [expr ${x_start} + $j]
2283 set position_y [expr ${y_start} + $i]
2284 puts $position_x
2285 puts $position_y
2286
2287 set color ""
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"
2291 incr j
2292 continue
2293 }
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)]
2300
2301 if { $rd_ch != 0 } {
2302 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2303 } else {
2304 set tol_rd $rd_int
2305 }
2306 if { $gr_ch != 0 } {
2307 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2308 } else {
2309 set tol_gr $gr_int
2310 }
2311 if { $bl_ch != 0 } {
2312 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2313 } else {
2314 set tol_bl $bl_int
2315 }
2316
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"
2319 set mistake 0
2320 } else {
2321 set mistake 1
2322 }
ccadc126 2323 incr j
6d368502 2324 }
2325 incr i
ccadc126 2326 }
2327 return $mistake
2328}