0026668: Eliminate compile warnings obtained by building occt with vc14: conversion...
[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" } {
66 set echo t
67 continue
68 }
69
70 # output log file
71 if { $arg == "-outfile" } {
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
79 }
80
81 # allow overwrite existing log
82 if { $arg == "-overwrite" } {
83 set overwrite 1
84 continue
85 }
86
87 # sound signal at the end of the test
88 if { $arg == "-beep" } {
89 set signal t
90 continue
91 }
92
5fd3308a 93 # if errors specified as "-errors", convert it to bool
94 if { $arg == "-errors" } {
95 set errors t
96 continue
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 != ""} {
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"
121 }
122 }
5df3a117 123 }
40093367 124
433673e0 125 # play sound signal at the end of test
126 if {$signal} {
127 puts "\7\7\7\7"
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)] ||
155 [llength $env(CSF_TestScriptsPath)] <= 0 } {
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} {
167 set arg [lindex $args $narg]
168
169 # parallel execution
170 if { $arg == "-parallel" } {
171 incr narg
b725d7c5 172 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
40093367 173 set parallel [expr [lindex $args $narg]]
174 } else {
b725d7c5 175 error "Option -parallel requires argument"
40093367 176 }
177 continue
178 }
179
180 # refresh logs time
181 if { $arg == "-refresh" } {
182 incr narg
b725d7c5 183 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
40093367 184 set refresh [expr [lindex $args $narg]]
185 } else {
b725d7c5 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"
40093367 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
b725d7c5 211 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
40093367 212 set xmlfile [lindex $args $narg]
213 }
214 if { $xmlfile == "" } {
215 set xmlfile TESTS-summary.xml
216 }
217 continue
218 }
219
433673e0 220 # sound signal at the end of the test
221 if { $arg == "-beep" } {
222 set signal t
223 continue
224 }
225
40093367 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
87f42a3f 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 ,]
40093367 238 } else {
87f42a3f 239 error "Error: cannot interpret argument $narg ($arg)"
40093367 240 }
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 == "" } {
b725d7c5 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 }
ffc26091 253 set logdir "results/${prefix}[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
40093367 254 set logdir [file normalize $logdir]
255 }
256 if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
257 error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
258 }
259 if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
260 error "Error: Cannot create directory \"$logdir\", or it is not writable"
261 }
262
87f42a3f 263 # masks for search of test groups, grids, and cases
264 if { ! [info exists groupmask] } { set groupmask * }
265 if { ! [info exists gridmask ] } { set gridmask * }
266 if { ! [info exists casemask ] } { set casemask * }
267
40093367 268 ######################################################
269 # prepare list of tests to be performed
270 ######################################################
271
272 # list of tests, each defined by a list of:
273 # test scripts directory
274 # group (subfolder) name
275 # grid (subfolder) name
276 # test case name
277 # path to test case file
278 set tests_list {}
279
280 # iterate by all script paths
2124e769 281 foreach dir [lsort -unique [_split_path $env(CSF_TestScriptsPath)]] {
40093367 282 # protection against empty paths
283 set dir [string trim $dir]
284 if { $dir == "" } { continue }
285
286 if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
287
288 # check that directory exists
289 if { ! [file isdirectory $dir] } {
290 _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
291 continue
292 }
293
87f42a3f 294 # search all directories in the current dir with specified mask
295 if [catch {glob -directory $dir -tail -types d {*}$groupmask} groups] { continue }
40093367 296
297 # iterate by groups
298 if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
299 foreach group [lsort -dictionary $groups] {
300 if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
301
302 # file grids.list must exist: it defines sequence of grids in the group
303 if { ! [file exists $dir/$group/grids.list] } {
304 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
305 continue
306 }
307
308 # read grids.list file and make a list of grids to be executed
309 set gridlist {}
310 set fd [open $dir/$group/grids.list]
311 set nline 0
312 while { [gets $fd line] >= 0 } {
313 incr nline
314
315 # skip comments and empty lines
316 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
317 if { [string trim $line] == "" } { continue }
318
319 # get grid id and name
320 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
321 _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
322 continue
323 }
324
87f42a3f 325 # check that grid fits into the specified mask
326 foreach mask $gridmask {
327 if { $mask == $gridid || [string match $mask $grid] } {
328 lappend gridlist $grid
329 }
40093367 330 }
331 }
332 close $fd
333
334 # iterate by all grids
335 foreach grid $gridlist {
336
337 # check if this grid is aliased to another one
338 set griddir $dir/$group/$grid
339 if { [file exists $griddir/cases.list] } {
340 set fd [open $griddir/cases.list]
341 if { [gets $fd line] >= 0 } {
342 set griddir [file normalize $dir/$group/$grid/[string trim $line]]
343 }
344 close $fd
345 }
346
347 # check if grid directory actually exists
348 if { ! [file isdirectory $griddir] } {
349 _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
350 continue
351 }
352
353 # create directory for logging test results
354 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
355
356 # iterate by all tests in the grid directory
87f42a3f 357 if { [catch {glob -directory $griddir -type f {*}$casemask} testfiles] } { continue }
40093367 358 foreach casefile [lsort -dictionary $testfiles] {
87f42a3f 359 # filter out files with reserved names
40093367 360 set casename [file tail $casefile]
87f42a3f 361 if { $casename == "begin" || $casename == "end" ||
362 $casename == "parse.rules" } {
363 continue
364 }
40093367 365
366 lappend tests_list [list $dir $group $grid $casename $casefile]
367 }
368 }
369 }
370 }
371 if { [llength $tests_list] < 1 } {
372 error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
433673e0 373 } else {
374 puts "Running tests (total [llength $tests_list] test cases)..."
40093367 375 }
376
377 ######################################################
378 # run tests
379 ######################################################
380
381 # log command arguments and environment
9753e6de 382 lappend log "Command: testgrid $args"
383 lappend log "Host: [info hostname]"
384 lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
385 catch {lappend log "DRAW build:\n[dversion]" }
386 lappend log "Environment:"
8a262fa1 387 foreach envar [lsort [array names env]] {
9753e6de 388 lappend log "$envar=\"$env($envar)\""
40093367 389 }
9753e6de 390 lappend log ""
40093367 391
392 set refresh_timer [clock seconds]
393 uplevel dchrono _timer reset
394 uplevel dchrono _timer start
395
396 # if parallel execution is requested, allocate thread pool
397 if { $parallel > 0 } {
398 if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
399 _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
400 set parallel 0
401 } else {
402 set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
403 # suspend the pool until all jobs are posted, to prevent blocking of the process
404 # of starting / processing jobs by running threads
b725d7c5 405 catch {tpool::suspend $worker}
40093367 406 if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
9753e6de 407 # limit number of jobs in the queue by reasonable value
408 # to prevent slowdown due to unnecessary queue processing
409 set nbpooled 0
410 set nbpooled_max [expr 10 * $parallel]
411 set nbpooled_ok [expr 5 * $parallel]
40093367 412 }
413 }
414
415 # start test cases
8a262fa1 416 set userbreak 0
40093367 417 foreach test_def $tests_list {
8a262fa1 418 # check for user break
9753e6de 419 if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
8a262fa1 420 set userbreak 1
421 break
422 }
423
40093367 424 set dir [lindex $test_def 0]
425 set group [lindex $test_def 1]
426 set grid [lindex $test_def 2]
427 set casename [lindex $test_def 3]
428 set casefile [lindex $test_def 4]
429
430 # command to set tests for generation of image in results directory
431 set imgdir_cmd ""
432 if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
433
434 # prepare command file for running test case in separate instance of DRAW
435 set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
436 puts $fd_cmd "$imgdir_cmd"
437 puts $fd_cmd "set test_image $casename"
b725d7c5 438 puts $fd_cmd "_run_test $dir $group $grid $casefile t"
5df3a117 439
40093367 440 # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
5df3a117 441 # note: this is not needed if echo is set to 1 in call to _run_test above
40093367 442 if { ! [catch {dlog get}] } {
443 puts $fd_cmd "puts \[dlog get\]"
444 } else {
445 # else try to use old-style QA_ variables to get more output...
446 set env(QA_DUMP) 1
447 set env(QA_DUP) 1
448 set env(QA_print_command) 1
449 }
5df3a117 450
40093367 451 # final 'exit' is needed when running on Linux under VirtualGl
452 puts $fd_cmd "exit"
453 close $fd_cmd
8418c617 454
455 # commant to run DRAW with a command file;
456 # note that empty string is passed as standard input to avoid possible
457 # hang-ups due to waiting for stdin of the launching process
458 set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
459
40093367 460 # alternative method to run without temporary file; disabled as it needs too many backslashes
461# else {
8418c617 462# set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
40093367 463# _run_test $dir $group $grid $casefile\\\; \
464# puts \\\[dlog get\\\]\\\; exit"
465# }
466
467 # run test case, either in parallel or sequentially
468 if { $parallel > 0 } {
469 # parallel execution
470 set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
471 set job_def($job) [list $logdir $dir $group $grid $casename]
9753e6de 472 incr nbpooled
473 if { $nbpooled > $nbpooled_max } {
474 _testgrid_process_jobs $worker $nbpooled_ok
475 }
40093367 476 } else {
477 # sequential execution
478 catch {eval $command} output
479 _log_test_case $output $logdir $dir $group $grid $casename log
480
481 # update summary log with requested period
482 if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
483 # update and dump summary
484 _log_summarize $logdir $log
485 set refresh_timer [clock seconds]
486 }
487 }
488 }
489
490 # get results of started threads
491 if { $parallel > 0 } {
9753e6de 492 _testgrid_process_jobs $worker
40093367 493 # release thread pool
9753e6de 494 if { $nbpooled > 0 } {
495 tpool::cancel $worker [array names job_def]
496 }
497 catch {tpool::resume $worker}
40093367 498 tpool::release $worker
499 }
500
501 uplevel dchrono _timer stop
502 set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
503
8a262fa1 504 if { $userbreak } {
9753e6de 505 _log_and_puts log "*********** Stopped by user break ***********"
8a262fa1 506 set time "${time} \nNote: the process is not finished, stopped by user break!"
507 }
508
40093367 509 ######################################################
510 # output summary logs and exit
511 ######################################################
512
513 _log_summarize $logdir $log $time
514 if { $logdir != "" } {
515 puts "Detailed logs are saved in $logdir"
516 }
517 if { $logdir != "" && $xmlfile != "" } {
518 # XML output file is assumed relative to log dir unless it is absolute
519 if { [ file pathtype $xmlfile] == "relative" } {
520 set xmlfile [file normalize $logdir/$xmlfile]
521 }
522 _log_xml_summary $logdir $xmlfile $log 0
523 puts "XML summary is saved to $xmlfile"
524 }
433673e0 525 # play sound signal at the end of test
526 if {$signal} {
527 puts "\7\7\7\7"
528 }
40093367 529 return
530}
531
22db40eb 532# Procedure to regenerate summary log from logs of test cases
533help testsummarize {
534 Regenerate summary log in the test directory from logs of test cases.
535 This can be necessary if test grids are executed separately (e.g. on
536 different stations) or some grids have been re-executed.
537 Use: testsummarize dir
538}
539proc testsummarize {dir} {
540 global _test_case_regexp
541
542 if { ! [file isdirectory $dir] } {
543 error "Error: \"$dir\" is not a directory"
544 }
545
546 # get summary statements from all test cases in one log
9753e6de 547 set log {}
22db40eb 548
549 # to avoid huge listing of logs, first find all subdirectories and iterate
550 # by them, parsing log files in each subdirectory independently
551 foreach grid [glob -directory $dir -types d -tails */*] {
552 foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
553 set file [file join $dir $grid $caselog]
554 set nbfound 0
555 set fd [open $file r]
556 while { [gets $fd line] >= 0 } {
557 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
558 if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } {
559 puts "Error: $file contains status line for another test case ($line)"
560 }
9753e6de 561 lappend log $line
22db40eb 562 incr nbfound
563 }
564 }
565 close $fd
566
567 if { $nbfound != 1 } {
568 puts "Error: $file contains $nbfound status lines, expected 1"
569 }
570 }
571 }
572
573 _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
574 return
575}
576
cc6a292d 577# Procedure to compare results of two runs of test cases
b725d7c5 578help testdiff {
579 Compare results of two executions of tests (CPU times, ...)
22db40eb 580 Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
b725d7c5 581 Where dir1 and dir2 are directories containing logs of two test runs.
582 Allowed options are:
22db40eb 583 -save filename: save resulting log in specified file (default name is
60874ff8 584 <dir1>/diff-<dir2>.log); HTML log is saved with same name
22db40eb 585 and extension .html
b725d7c5 586 -status {same|ok|all}: filter cases for comparing by their status:
587 same - only cases with same status are compared (default)
588 ok - only cases with OK status in both logs are compared
589 all - results are compared regardless of status
590 -verbose level:
591 1 - output only differences
22db40eb 592 2 - output also list of logs and directories present in one of dirs only
593 3 - (default) output also progress messages
d5f061b6 594
595 -highlight_percent value: highlight considerable (>value in %) deviations
596 of CPU and memory (default value is 5%)
cc6a292d 597}
598proc testdiff {dir1 dir2 args} {
599 if { "$dir1" == "$dir2" } {
600 error "Input directories are the same"
601 }
602
603 ######################################################
604 # check arguments
605 ######################################################
606
607 # treat options
22db40eb 608 set logfile [file join $dir1 "diff-[file tail $dir2].log"]
cc6a292d 609 set basename ""
610 set status "same"
611 set verbose 3
d5f061b6 612 set highlight_percent 5
cc6a292d 613 for {set narg 0} {$narg < [llength $args]} {incr narg} {
614 set arg [lindex $args $narg]
615
616 # log file name
617 if { $arg == "-save" } {
618 incr narg
22db40eb 619 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
cc6a292d 620 set logfile [lindex $args $narg]
621 } else {
622 error "Error: Option -save must be followed by log file name"
623 }
624 continue
625 }
626
cc6a292d 627 # status filter
628 if { $arg == "-status" } {
629 incr narg
22db40eb 630 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
cc6a292d 631 set status [lindex $args $narg]
632 } else { set status "" }
633 if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
634 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
635 }
636 continue
637 }
638
639 # verbose level
640 if { $arg == "-verbose" } {
641 incr narg
22db40eb 642 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
cc6a292d 643 set verbose [expr [lindex $args $narg]]
22db40eb 644 } else {
645 error "Error: Option -verbose must be followed by integer verbose level"
cc6a292d 646 }
647 continue
648 }
d5f061b6 649
650 # highlight_percent
651 if { $arg == "-highlight_percent" } {
652 incr narg
653 if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
654 set highlight_percent [expr [lindex $args $narg]]
655 } else {
656 error "Error: Option -highlight_percent must be followed by integer value"
657 }
658 continue
659 }
660
22db40eb 661 if { [regexp {^-} $arg] } {
cc6a292d 662 error "Error: unsupported option \"$arg\""
22db40eb 663 }
664
665 # non-option arguments form a subdirectory path
666 set basename [file join $basename $arg]
cc6a292d 667 }
668
669 # run diff procedure (recursive)
670 _test_diff $dir1 $dir2 $basename $status $verbose log
671
672 # save result to log file
673 if { "$logfile" != "" } {
9753e6de 674 _log_save $logfile [join $log "\n"]
d5f061b6 675 _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2 ${highlight_percent}
22db40eb 676 puts "Log is saved to $logfile (and .html)"
cc6a292d 677 }
678
679 return
680}
681
351bbcba 682# Procedure to check data file before adding it to repository
683help testfile {
684 Check data file and prepare it for putting to test data files repository.
685 Use: testfile [filelist]
686
687 Will report if:
688 - data file (non-binary) is in DOS encoding (CR/LF)
689 - same data file (with same or another name) already exists in the repository
690 - another file with the same name already exists
691 Note that names are assumed to be case-insensitive (for Windows).
692
693 Unless the file is already in the repository, tries to load it, reports
694 the recognized file format, file size, number of faces and edges in the
60874ff8 695 loaded shape (if any), and makes snapshot (in the temporary directory).
351bbcba 696 Finally it advises whether the file should be put to public section of the
697 repository.
698}
699proc testfile {filelist} {
700 global env
701
702 # check that CSF_TestDataPath is defined
703 if { ! [info exists env(CSF_TestDataPath)] } {
704 error "Environment variable CSF_TestDataPath must be defined!"
705 }
706
707 # build registry of existing data files (name -> path) and (size -> path)
708 puts "Checking available test data files..."
709 foreach dir [_split_path $env(CSF_TestDataPath)] {
710 while {[llength $dir] != 0} {
711 set curr [lindex $dir 0]
712 set dir [lrange $dir 1 end]
713 eval lappend dir [glob -nocomplain -directory $curr -type d *]
714 foreach file [glob -nocomplain -directory $curr -type f *] {
715 set name [file tail $file]
716 set name_lower [string tolower $name]
717
718 # check that the file is not in DOS encoding
719 if { [_check_dos_encoding $file] } {
720 puts "Warning: file $file is in DOS encoding; was this intended?"
721 }
722 _check_file_format $file
723
724 # check if file with the same name is present twice or more
725 if { [info exists names($name_lower)] } {
726 puts "Error: more than one file with name $name is present in the repository:"
727 if { [_diff_files $file $names($name_lower)] } {
728 puts "(files are different by content)"
729 } else {
730 puts "(files are same by content)"
731 }
732 puts "--> $file"
733 puts "--> $names($name_lower)"
734 continue
735 }
736
737 # check if file with the same content exists
738 set size [file size $file]
739 if { [info exists sizes($size)] } {
740 foreach other $sizes($size) {
741 if { ! [_diff_files $file $other] } {
742 puts "Warning: two files with the same content found:"
743 puts "--> $file"
744 puts "--> $other"
745 }
746 }
747 }
748
749 # add the file to the registry
750 set names($name_lower) $file
751 lappend sizes($size) $file
752 }
753 }
754 }
755 if { [llength $filelist] <= 0 } { return }
756
757 # check the new files
758 set has_images f
759 puts "Checking new file(s)..."
760 foreach file $filelist {
761 # check for DOS encoding
762 if { [_check_dos_encoding $file] } {
763 puts "$file: Warning: DOS encoding detected"
764 }
765
766 set name [file tail $file]
767 set name_lower [string tolower $name]
768
769 # check for presence of the file with same name
770 if { [info exists names($name_lower)] } {
771 if { [_diff_files $file $names($name_lower)] } {
772 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
773 } else {
774 puts "$file: OK: already in the repository \n--> $names($name_lower)"
775 continue
776 }
777 }
778
779 # check if file with the same content exists
780 set size [file size $file]
781 if { [info exists sizes($size)] } {
782 set found f
783 foreach other $sizes($size) {
784 if { ! [_diff_files $file $other] } {
785 puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
786 set found t
787 break
788 }
789 }
790 if { $found } { continue }
791 }
792
793 # try to read the file
794 set format [_check_file_format $file]
795 if { [catch {uplevel load_data_file $file $format a}] } {
796 puts "$file: Error: Cannot read as $format file"
797 continue
798 }
799
800 # get number of faces and edges
801 set edges 0
802 set faces 0
803 set nbs [uplevel nbshapes a]
804 regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
805 regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
806
807 # classify; first check file size and number of faces and edges
808 if { $size < 95000 && $faces < 20 && $edges < 100 } {
809 set dir public
810 } else {
811 set dir private
812 # check if one of names of that file corresponds to typical name for
813 # MDTV bugs or has extension .rle, this should be old model
814 if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
815 [regexp -nocase {[.]rle\y} $name] } {
816 set dir old
817 }
818 }
819
820 # add stats
821 puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
822
60874ff8 823 set tmpdir [_get_temp_dir]
824 file mkdir $tmpdir/$dir
351bbcba 825
826 # make snapshot
827 pload AISV
828 uplevel vdisplay a
829 uplevel vfit
830 uplevel vzfit
60874ff8 831 uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
351bbcba 832 set has_images t
833 }
834 if { $has_images } {
60874ff8 835 puts "Snapshots are saved in subdirectory [_get_temp_dir]"
351bbcba 836 }
837}
838
22db40eb 839# Procedure to locate data file for test given its name.
840# The search is performed assuming that the function is called
841# from the test case script; the search order is:
842# - subdirectory "data" of the test script (grid) folder
843# - subdirectories in environment variable CSF_TestDataPath
844# - subdirectory set by datadir command
845# If file is not found, raises Tcl error.
846proc locate_data_file {filename} {
847 global env groupname gridname casename
848
849 # check if the file is located in the subdirectory data of the script dir
850 set scriptfile [info script]
851 if { $scriptfile != "" } {
852 set path [file join [file dirname $scriptfile] data $filename]
853 if { [file exists $path] } {
854 return [file normalize $path]
855 }
856 }
857
858 # check sub-directories in paths indicated by CSF_TestDataPath
859 if { [info exists env(CSF_TestDataPath)] } {
860 foreach dir [_split_path $env(CSF_TestDataPath)] {
861 while {[llength $dir] != 0} {
862 set name [lindex $dir 0]
863 set dir [lrange $dir 1 end]
80482e01 864 # skip directories starting with dot
865 if { [regexp {^[.]} $name] } { continue }
22db40eb 866 if { [file exists $name/$filename] } {
867 return [file normalize $name/$filename]
868 }
80482e01 869 eval lappend dir [glob -nocomplain -directory $name -type d *]
22db40eb 870 }
871 }
872 }
873
874 # check current datadir
875 if { [file exists [uplevel datadir]/$filename] } {
876 return [file normalize [uplevel datadir]/$filename]
877 }
878
879 # raise error
c97067ad 880 error [join [list "File $filename could not be found" \
22db40eb 881 "(should be in paths indicated by CSF_TestDataPath environment variable, " \
882 "or in subfolder data in the script directory)"] "\n"]
883}
884
40093367 885# Internal procedure to find test case indicated by group, grid, and test case names;
886# returns:
887# - dir: path to the base directory of the tests group
888# - gridname: actual name of the grid
889# - casefile: path to the test case script
890# if no such test is found, raises error with appropriate message
891proc _get_test {group grid casename _dir _gridname _casefile} {
892 upvar $_dir dir
893 upvar $_gridname gridname
894 upvar $_casefile casefile
895
896 global env
897
898 # check that environment variable defining paths to test scripts is defined
899 if { ! [info exists env(CSF_TestScriptsPath)] ||
900 [llength $env(CSF_TestScriptsPath)] <= 0 } {
901 error "Error: Environment variable CSF_TestScriptsPath is not defined"
902 }
903
904 # iterate by all script paths
905 foreach dir [_split_path $env(CSF_TestScriptsPath)] {
906 # protection against empty paths
907 set dir [string trim $dir]
908 if { $dir == "" } { continue }
909
910 # check that directory exists
911 if { ! [file isdirectory $dir] } {
912 puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
913 continue
914 }
915
916 # check if test group with given name exists in this dir
917 # if not, continue to the next test dir
918 if { ! [file isdirectory $dir/$group] } { continue }
919
920 # check that grid with given name (possibly alias) exists; stop otherwise
921 set gridname $grid
922 if { ! [file isdirectory $dir/$group/$gridname] } {
923 # check if grid is named by alias rather than by actual name
924 if { [file exists $dir/$group/grids.list] } {
925 set fd [open $dir/$group/grids.list]
926 while { [gets $fd line] >= 0 } {
927 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
928 if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
929 break
930 }
931 }
932 close $fd
933 }
934 }
935 if { ! [file isdirectory $dir/$group/$gridname] } { continue }
936
937 # get actual file name of the script; stop if it cannot be found
938 set casefile $dir/$group/$gridname/$casename
939 if { ! [file exists $casefile] } {
940 # check if this grid is aliased to another one
941 if { [file exists $dir/$group/$gridname/cases.list] } {
942 set fd [open $dir/$group/$gridname/cases.list]
943 if { [gets $fd line] >= 0 } {
944 set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
945 }
946 close $fd
947 }
948 }
949 if { [file exists $casefile] } {
950 # normal return
951 return
952 }
953 }
954
955 # coming here means specified test is not found; report error
956 error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
957 "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
958}
959
960# Internal procedure to run test case indicated by base directory,
961# grid and grid names, and test case file path.
962# The log can be obtained by command "dlog get".
5df3a117 963proc _run_test {scriptsdir group gridname casefile echo} {
40093367 964 global env
965
966 # start timer
967 uplevel dchrono _timer reset
968 uplevel dchrono _timer start
433673e0 969 catch {uplevel meminfo h} membase
40093367 970
971 # enable commands logging; switch to old-style mode if dlog command is not present
972 set dlog_exists 1
973 if { [catch {dlog reset}] } {
974 set dlog_exists 0
5df3a117 975 } elseif { $echo } {
976 decho on
40093367 977 } else {
978 dlog reset
979 dlog on
980 rename puts puts-saved
981 proc puts args {
982 global _tests_verbose
983
984 # log only output to stdout and stderr, not to file!
985 if {[llength $args] > 1} {
d33dea30
PK
986 set optarg [lindex $args end-1]
987 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
40093367 988 dlog add [lindex $args end]
c97067ad 989 } else {
990 eval puts-saved $args
40093367 991 }
992 } else {
993 dlog add [lindex $args end]
994 }
40093367 995 }
996 }
997
40093367 998 # evaluate test case
936f43da 999 set tmp_imagedir 0
40093367 1000 if [catch {
60874ff8 1001 # set variables identifying test case
40093367 1002 uplevel set casename [file tail $casefile]
8418c617 1003 uplevel set groupname $group
1004 uplevel set gridname $gridname
c97067ad 1005 uplevel set dirname $scriptsdir
40093367 1006
a3ef6605 1007 # set path for saving of log and images (if not yet set) to temp dir
60874ff8 1008 if { ! [uplevel info exists imagedir] } {
60874ff8 1009 uplevel set test_image \$casename
a3ef6605 1010
1011 # create subdirectory in temp named after group and grid with timestamp
1012 set rootlogdir [_get_temp_dir]
1013
1014 set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
1015 set imagedir [file normalize ${rootlogdir}/$imagedir]
1016
1017 if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1018 ! [catch {glob -directory $imagedir *}] } {
1019# puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
1020 set imagedir $rootlogdir
1021 }
1022
d16b64f1 1023 uplevel set imagedir \"$imagedir\"
936f43da 1024 set tmp_imagedir 1
60874ff8 1025 }
1026
1027 # execute test scripts
40093367 1028 if { [file exists $scriptsdir/$group/begin] } {
1029 puts "Executing $scriptsdir/$group/begin..."; flush stdout
1030 uplevel source $scriptsdir/$group/begin
1031 }
1032 if { [file exists $scriptsdir/$group/$gridname/begin] } {
1033 puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1034 uplevel source $scriptsdir/$group/$gridname/begin
1035 }
1036
1037 puts "Executing $casefile..."; flush stdout
1038 uplevel source $casefile
1039
1040 if { [file exists $scriptsdir/$group/$gridname/end] } {
1041 puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1042 uplevel source $scriptsdir/$group/$gridname/end
1043 }
1044 if { [file exists $scriptsdir/$group/end] } {
1045 puts "Executing $scriptsdir/$group/end..."; flush stdout
1046 uplevel source $scriptsdir/$group/end
1047 }
1048 } res] {
1049 puts "Tcl Exception: $res"
1050 }
1051
40093367 1052 # stop logging
1053 if { $dlog_exists } {
5df3a117 1054 if { $echo } {
1055 decho off
1056 } else {
1057 rename puts {}
1058 rename puts-saved puts
1059 dlog off
1060 }
40093367 1061 }
1062
8418c617 1063 # stop cpulimit killer if armed by the test
1064 cpulimit
1065
22db40eb 1066 # add memory and timing info
1067 set stats ""
433673e0 1068 if { ! [catch {uplevel meminfo h} memuse] } {
936f43da 1069 append stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
22db40eb 1070 }
40093367 1071 uplevel dchrono _timer stop
1072 set time [uplevel dchrono _timer show]
936f43da 1073 if { [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu_usr] } {
1074 append stats "TOTAL CPU TIME: $cpu_usr sec\n"
22db40eb 1075 }
1076 if { $dlog_exists && ! $echo } {
1077 dlog add $stats
1078 } else {
1079 puts $stats
40093367 1080 }
936f43da 1081
1082 # unset global vars
1083 uplevel unset casename groupname gridname dirname
1084 if { $tmp_imagedir } { uplevel unset imagedir test_image }
40093367 1085}
1086
1087# Internal procedure to check log of test execution and decide if it passed or failed
5fd3308a 1088proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
40093367 1089 global env
1090 if { $_summary != "" } { upvar $_summary summary }
1091 if { $_html_log != "" } { upvar $_html_log html_log }
9753e6de 1092 set summary {}
1093 set html_log {}
5fd3308a 1094 set errors_log {}
40093367 1095
1096if [catch {
1097
1098 # load definition of 'bad words' indicating test failure
1099 # note that rules are loaded in the order of decreasing priority (grid - group - common),
1100 # thus grid rules will override group ones
1101 set badwords {}
1102 foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
1103 if [catch {set fd [open $rulesfile r]}] { continue }
1104 while { [gets $fd line] >= 0 } {
1105 # skip comments and empty lines
1106 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
1107 if { [string trim $line] == "" } { continue }
1108 # extract regexp
1109 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } {
1110 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1111 continue
1112 }
1113 set status [string trim $status]
936f43da 1114 if { $comment != "" } { append status " ([string trim $comment])" }
40093367 1115 set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1116 lappend badwords [list $status $rexp]
1117 }
1118 close $fd
1119 }
1120 if { [llength $badwords] <= 0 } {
1121 puts "Warning: no definition of error indicators found (check files parse.rules)"
1122 }
1123
1124 # analyse log line-by-line
1125 set todos {}
1126 set status ""
1127 foreach line [split $log "\n"] {
1128 # check if line defines specific treatment of some messages
b58dfc5e 1129 set deb_info [dversion]
1130 if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1131 if { [regexp {DEBUG_} $platforms] != 1 } {
1132 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1133 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1134 lappend html_log $line
1135 continue ;# TODO statement is for another platform
1136 }
1137
1138 # record TODOs that mark unstable cases
1139 if { [regexp {[\?]} $platforms] } {
1140 set todos_unstable([llength $todos]) 1
1141 }
1142
1143 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1144 lappend html_log [_html_highlight BAD $line]
1145 continue
1146 }
1147
1148 if { [regexp "Debug mode" $deb_info] != 1 && [regexp {DEBUG_} $platforms] == 1 } {
1149 continue
40093367 1150 }
1151
b58dfc5e 1152 if { [regexp "Debug mode" $deb_info] == 1 && [regexp {DEBUG_} $platforms] == 1 } {
1153 if { ! [regexp -nocase {\mAll\M} $platforms] &&
1154 ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1155 lappend html_log $line
1156 continue ;# TODO statement is for another platform
1157 }
40093367 1158
b58dfc5e 1159 # record TODOs that mark unstable cases
1160 if { [regexp {[\?]} $platforms] } {
1161 set todos_unstable([llength $todos]) 1
1162 }
1163
1164 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1165 lappend html_log [_html_highlight BAD $line]
1166 continue
1167 }
40093367 1168 }
b58dfc5e 1169
40093367 1170 # check for presence of messages indicating test result
1171 set ismarked 0
1172 foreach bw $badwords {
1173 if { [regexp [lindex $bw 1] $line] } {
1174 # check if this is known bad case
1175 set is_known 0
1176 for {set i 0} {$i < [llength $todos]} {incr i} {
1177 if { [regexp [lindex $todos $i] $line] } {
1178 set is_known 1
1179 incr todo_count($i)
9753e6de 1180 lappend html_log [_html_highlight BAD $line]
40093367 1181 break
1182 }
1183 }
1184
1185 # if it is not in todo, define status
1186 if { ! $is_known } {
1187 set stat [lindex $bw 0 0]
5fd3308a 1188 if {$errors} {
1189 lappend errors_log $line
1190 }
9753e6de 1191 lappend html_log [_html_highlight $stat $line]
40093367 1192 if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1193 set status [lindex $bw 0]
1194 }
1195 }
1196 set ismarked 1
1197 break
1198 }
1199 }
1200 if { ! $ismarked } {
9753e6de 1201 lappend html_log $line
40093367 1202 }
1203 }
1204
1205 # check for presence of TEST COMPLETED statement
1206 if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1207 # check whether absence of TEST COMPLETED is known problem
1208 set i [lsearch $todos "TEST INCOMPLETE"]
1209 if { $i >= 0 } {
1210 incr todo_count($i)
1211 } else {
1212 set status "FAILED (no final message is found)"
1213 }
1214 }
1215
1216 # check declared bad cases and diagnose possible improvement
1217 # (bad case declared but not detected).
1218 # Note that absence of the problem marked by TODO with question mark
1219 # (unstable) is not reported as improvement.
1220 if { $status == "" } {
1221 for {set i 0} {$i < [llength $todos]} {incr i} {
1222 if { ! [info exists todos_unstable($i)] &&
1223 (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1224 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1225 break;
1226 }
1227 }
1228 }
1229
1230 # report test as known bad if at least one of expected problems is found
1231 if { $status == "" && [llength [array names todo_count]] > 0 } {
1232 set status "BAD (known problem)"
1233 }
1234
1235 # report normal OK
1236 if { $status == "" } {set status "OK" }
1237
1238} res] {
1239 set status "FAILED ($res)"
1240}
1241
1242 # put final message
1243 _log_and_puts summary "CASE $group $gridname $casename: $status"
9753e6de 1244 set summary [join $summary "\n"]
5fd3308a 1245 if {$errors} {
1246 foreach error $errors_log {
1247 _log_and_puts summary " $error"
1248 }
1249 }
9753e6de 1250 set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
40093367 1251}
1252
1253# Auxiliary procedure putting message to both cout and log variable (list)
1254proc _log_and_puts {logvar message} {
1255 if { $logvar != "" } {
1256 upvar $logvar log
9753e6de 1257 lappend log $message
40093367 1258 }
1259 puts $message
1260}
1261
1262# Auxiliary procedure to log result on single test case
1263proc _log_test_case {output logdir dir group grid casename logvar} {
1264 upvar $logvar log
5fd3308a 1265 set show_errors 0
40093367 1266 # check result and make HTML log
5fd3308a 1267 _check_log $dir $group $grid $casename $show_errors $output summary html_log
9753e6de 1268 lappend log $summary
40093367 1269
1270 # save log to file
1271 if { $logdir != "" } {
1272 _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1273 _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1274 }
1275}
1276
1277# Auxiliary procedure to save log to file
1278proc _log_save {file log {title {}}} {
1279 # create missing directories as needed
1280 catch {file mkdir [file dirname $file]}
1281
1282 # try to open a file
1283 if [catch {set fd [open $file w]} res] {
1284 error "Error saving log file $file: $res"
1285 }
1286
1287 # dump log and close
1288 puts $fd "$title\n"
1289 puts $fd $log
1290 close $fd
1291 return
1292}
1293
22db40eb 1294# Auxiliary procedure to make a (relative if possible) URL to a file for
1295# inclusion a reference in HTML log
1296proc _make_url {htmldir file} {
1297 set htmlpath [file split [file normalize $htmldir]]
1298 set filepath [file split [file normalize $file]]
1299 for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1300 if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1301 if { $i == 0 } { break }
1302 return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1303 }
1304 }
1305
1306 # if relative path could not be made, return full file URL
1307 return "file://[file normalize $file]"
1308}
1309
40093367 1310# Auxiliary procedure to save log to file
1311proc _log_html {file log {title {}}} {
1312 # create missing directories as needed
1313 catch {file mkdir [file dirname $file]}
1314
1315 # try to open a file
1316 if [catch {set fd [open $file w]} res] {
1317 error "Error saving log file $file: $res"
1318 }
1319
1320 # print header
22db40eb 1321 puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
40093367 1322
ffc26091 1323 # add images if present; these should have either PNG, GIF, or JPG extension,
1324 # and start with name of the test script, with optional suffix separated
1325 # by underscore or dash
40093367 1326 set imgbasename [file rootname [file tail $file]]
ffc26091 1327 foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails \
1328 ${imgbasename}.gif ${imgbasename}.png ${imgbasename}.jpg \
1329 ${imgbasename}_*.gif ${imgbasename}_*.png ${imgbasename}_*.jpg \
1330 ${imgbasename}-*.gif ${imgbasename}-*.png ${imgbasename}-*.jpg]] {
3b21f8ae 1331 puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
40093367 1332 }
1333
b725d7c5 1334 # print log body, trying to add HTML links to script files on lines like
1335 # "Executing <filename>..."
40093367 1336 puts $fd "<pre>"
b725d7c5 1337 foreach line [split $log "\n"] {
1338 if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1339 [file exists $script] } {
22db40eb 1340 set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
b725d7c5 1341 }
1342 puts $fd $line
1343 }
40093367 1344 puts $fd "</pre></body></html>"
1345
1346 close $fd
1347 return
1348}
1349
1350# Auxiliary method to make text with HTML highlighting according to status
1351proc _html_color {status} {
1352 # choose a color for the cell according to result
1353 if { $status == "OK" } {
1354 return lightgreen
1355 } elseif { [regexp -nocase {^FAIL} $status] } {
1356 return red
1357 } elseif { [regexp -nocase {^BAD} $status] } {
1358 return yellow
1359 } elseif { [regexp -nocase {^IMP} $status] } {
1360 return orange
1361 } elseif { [regexp -nocase {^SKIP} $status] } {
1362 return gray
1363 } elseif { [regexp -nocase {^IGNOR} $status] } {
1364 return gray
1365 } else {
1366 puts "Warning: no color defined for status $status, using red as if FAILED"
1367 return red
1368 }
1369}
1370
1371# Format text line in HTML to be colored according to the status
1372proc _html_highlight {status line} {
1373 return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1374}
1375
1376# Internal procedure to generate HTML page presenting log of the tests
1377# execution in tabular form, with links to reports on individual cases
1378proc _log_html_summary {logdir log totals regressions improvements total_time} {
1379 global _test_case_regexp
1380
9753e6de 1381 # create missing directories as needed
1382 file mkdir $logdir
40093367 1383
1384 # try to open a file and start HTML
1385 if [catch {set fd [open $logdir/summary.html w]} res] {
1386 error "Error creating log file: $res"
1387 }
1388
1389 # write HRML header, including command to refresh log if still in progress
1390 puts $fd "<html><head>"
1391 puts $fd "<title>Tests summary</title>"
1392 if { $total_time == "" } {
1393 puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1394 }
1395 puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1396 puts $fd "</head><body>"
1397
1398 # put summary
1399 set legend(OK) "Test passed OK"
1400 set legend(FAILED) "Test failed (regression)"
1401 set legend(BAD) "Known problem"
1402 set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1403 set legend(SKIPPED) "Test skipped due to lack of data file"
1404 puts $fd "<h1>Summary</h1><table>"
1405 foreach nbstat $totals {
1406 set status [lindex $nbstat 1]
1407 if { [info exists legend($status)] } {
1408 set comment $legend($status)
1409 } else {
1410 set comment "User-defined status"
1411 }
1412 puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1413 }
1414 puts $fd "</table>"
1415
1416 # time stamp and elapsed time info
1417 if { $total_time != "" } {
8a262fa1 1418 puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1419 puts $fd [join [split $total_time "\n"] "<p>"]
40093367 1420 } else {
1421 puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1422 }
1423
1424 # print regressions and improvements
1425 foreach featured [list $regressions $improvements] {
1426 if { [llength $featured] <= 1 } { continue }
1427 set status [string trim [lindex $featured 0] { :}]
1428 puts $fd "<h2>$status</h2>"
1429 puts $fd "<table>"
1430 set groupgrid ""
1431 foreach test [lrange $featured 1 end] {
1432 if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1433 set gg UNKNOWN
1434 set name "Error building short list; check details"
1435 }
1436 if { $gg != $groupgrid } {
1437 if { $groupgrid != "" } { puts $fd "</tr>" }
1438 set groupgrid $gg
1439 puts $fd "<tr><td>$gg</td>"
1440 }
1441 puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1442 }
1443 if { $groupgrid != "" } { puts $fd "</tr>" }
1444 puts $fd "</table>"
1445 }
1446
9753e6de 1447 # put detailed log with TOC
1448 puts $fd "<hr><h1>Details</h1>"
1449 puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
40093367 1450
1451 # process log line-by-line
1452 set group {}
1453 set letter {}
9753e6de 1454 set body {}
1455 foreach line [lsort -dictionary $log] {
40093367 1456 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1457 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1458 continue
1459 }
1460
1461 # start new group
1462 if { $grp != $group } {
9753e6de 1463 if { $letter != "" } { lappend body "</tr></table>" }
40093367 1464 set letter {}
1465 set group $grp
1466 set grid {}
9753e6de 1467 puts $fd "<a href=\"#$group\">$group</a><br>"
1468 lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
40093367 1469 }
1470
1471 # start new grid
1472 if { $grd != $grid } {
9753e6de 1473 if { $letter != "" } { lappend body "</tr></table>" }
40093367 1474 set letter {}
1475 set grid $grd
9753e6de 1476 puts $fd "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#$group-$grid\">$grid</a><br>"
1477 lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
40093367 1478 }
1479
1480 # check if test case name is <letter><digit>;
1481 # if not, set alnum to period "." to recognize non-standard test name
9753e6de 1482 if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1483 ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1484 set alnum $casename
40093367 1485 }
1486
1487 # start new row when letter changes or for non-standard names
1488 if { $alnum != $letter || $alnum == "." } {
1489 if { $letter != "" } {
9753e6de 1490 lappend body "</tr><tr>"
40093367 1491 } else {
9753e6de 1492 lappend body "<table><tr>"
40093367 1493 }
1494 set letter $alnum
1495 }
1496
9753e6de 1497 lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
40093367 1498 }
9753e6de 1499 puts $fd "</div>\n[join $body "\n"]</tr></table>"
40093367 1500
1501 # add remaining lines of log as plain text
1502 puts $fd "<h2>Plain text messages</h2>\n<pre>"
9753e6de 1503 foreach line $log {
40093367 1504 if { ! [regexp $_test_case_regexp $line] } {
1505 puts $fd "$line"
1506 }
1507 }
1508 puts $fd "</pre>"
1509
1510 # close file and exit
1511 puts $fd "</body>"
1512 close $fd
1513 return
1514}
1515
1516# Procedure to dump summary logs of tests
1517proc _log_summarize {logdir log {total_time {}}} {
1518
1519 # sort log records alphabetically to have the same behavior on Linux and Windows
1520 # (also needed if tests are run in parallel)
9753e6de 1521 set loglist [lsort -dictionary $log]
40093367 1522
1523 # classify test cases by status
1524 foreach line $loglist {
1525 if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1526 lappend stat($status) $caseid
1527 }
1528 }
1529 set totals {}
1530 set improvements {Improvements:}
1531 set regressions {Failed:}
1532 if { [info exists stat] } {
1533 foreach status [lsort [array names stat]] {
1534 lappend totals [list [llength $stat($status)] $status]
1535
1536 # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1537 if { [regexp -nocase {^IMP} $status] } {
1538 eval lappend improvements $stat($status)
1539 } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1540 eval lappend regressions $stat($status)
1541 }
1542 }
1543 }
1544
1545 # if time is specified, add totals
1546 if { $total_time != "" } {
1547 if { [llength $improvements] > 1 } {
1548 _log_and_puts log [join $improvements "\n "]
1549 }
1550 if { [llength $regressions] > 1 } {
1551 _log_and_puts log [join $regressions "\n "]
1552 }
1553 if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1554 _log_and_puts log "No regressions"
1555 }
1556 _log_and_puts log "Total cases: [join $totals {, }]"
1557 _log_and_puts log $total_time
1558 }
1559
1560 # save log to files
1561 if { $logdir != "" } {
1562 _log_html_summary $logdir $log $totals $regressions $improvements $total_time
9753e6de 1563 _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
40093367 1564 }
1565
1566 return
1567}
1568
1569# Internal procedure to generate XML log in JUnit style, for further
1570# consumption by Jenkins or similar systems.
1571#
1572# The output is intended to conform to XML schema supported by Jenkins found at
1573# 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
1574#
1575# The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1576# http://windyroad.org/dl/Open%20Source/JUnit.xsd
1577proc _log_xml_summary {logdir filename log include_cout} {
1578 global _test_case_regexp
1579
1580 catch {file mkdir [file dirname $filename]}
1581
1582 # try to open a file and start XML
1583 if [catch {set fd [open $filename w]} res] {
1584 error "Error creating XML summary file $filename: $res"
1585 }
1586 puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1587 puts $fd "<testsuites>"
1588
1589 # prototype for command to generate test suite tag
1590 set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1591 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"}
1592
1593 # sort log and process it line-by-line
1594 set group {}
9753e6de 1595 foreach line [lsort -dictionary $log] {
40093367 1596 # check that the line is case report in the form "CASE group grid name: result (explanation)"
1597 if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1598 continue
1599 }
1600 set message [string trim $message " \t\r\n()"]
1601
1602 # start new testsuite for each grid
1603 if { $grp != $group || $grd != $grid } {
1604
1605 # write previous test suite
1606 if [info exists testcases] { eval $cmd_testsuite }
1607
1608 set testcases {}
1609 set nbtests 0
1610 set nberr 0
1611 set nbfail 0
1612 set nbskip 0
1613 set time 0.
1614
1615 set group $grp
1616 set grid $grd
1617 }
1618
1619 incr nbtests
1620
1621 # parse test log and get its CPU time
1622 set testout {}
1623 set add_cpu {}
1624 if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } {
1625 puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1626 } else {
1627 while { [gets $fdlog logline] >= 0 } {
1628 if { $include_cout } {
936f43da 1629 append testout "$logline\n"
40093367 1630 }
1631 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1632 set add_cpu " time=\"$cpu\""
1633 set time [expr $time + $cpu]
1634 }
1635 }
1636 close $fdlog
1637 }
1638 if { ! $include_cout } {
1639 set testout "$line\n"
1640 }
1641
1642 # record test case with its output and status
1643 # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
936f43da 1644 append testcases "\n <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1645 append testcases "\n <system-out>\n$testout </system-out>"
40093367 1646 if { $result != "OK" } {
1647 if { [regexp -nocase {^SKIP} $result] } {
1648 incr nberr
936f43da 1649 append testcases "\n <error name=\"$result\" message=\"$message\"/>"
40093367 1650 } elseif { [regexp -nocase {^BAD} $result] } {
1651 incr nbskip
936f43da 1652 append testcases "\n <skipped>$message</skipped>"
40093367 1653 } else {
1654 incr nbfail
936f43da 1655 append testcases "\n <failure name=\"$result\" message=\"$message\"/>"
40093367 1656 }
1657 }
936f43da 1658 append testcases "\n </testcase>"
40093367 1659 }
1660
1661 # write last test suite
1662 if [info exists testcases] { eval $cmd_testsuite }
1663
1664 # the end
1665 puts $fd "</testsuites>"
1666 close $fd
1667 return
1668}
1669
1670# define custom platform name
1671proc _tests_platform_def {} {
1672 global env tcl_platform
1673
1674 if [info exists env(os_type)] { return }
40093367 1675 set env(os_type) $tcl_platform(platform)
37d6975c 1676 if { $tcl_platform(os) == "Linux" } {
1677 set env(os_type) Linux
40093367 1678 }
37d6975c 1679 if { $tcl_platform(os) == "Darwin" } {
1680 set env(os_type) MacOS
1681 }
40093367 1682}
1683_tests_platform_def
1684
1685# Auxiliary procedure to split path specification (usually defined by
1686# environment variable) into list of directories or files
1687proc _split_path {pathspec} {
1688 global tcl_platform
1689
1690 # first replace all \ (which might occur on Windows) by /
1691 regsub -all "\\\\" $pathspec "/" pathspec
1692
1693 # split path by platform-specific separator
1694 return [split $pathspec [_path_separator]]
1695}
1696
1697# Auxiliary procedure to define platform-specific separator for directories in
1698# path specification
1699proc _path_separator {} {
1700 global tcl_platform
1701
1702 # split path by platform-specific separator
1703 if { $tcl_platform(platform) == "windows" } {
1704 return ";"
1705 } else {
1706 return ":"
1707 }
1708}
1709
cc6a292d 1710# Procedure to make a diff and common of two lists
1711proc _list_diff {list1 list2 _in1 _in2 _common} {
1712 upvar $_in1 in1
1713 upvar $_in2 in2
1714 upvar $_common common
1715
1716 set in1 {}
1717 set in2 {}
1718 set common {}
1719 foreach item $list1 {
1720 if { [lsearch -exact $list2 $item] >= 0 } {
1721 lappend common $item
1722 } else {
1723 lappend in1 $item
1724 }
1725 }
1726 foreach item $list2 {
1727 if { [lsearch -exact $common $item] < 0 } {
1728 lappend in2 $item
1729 }
1730 }
1731 return
1732}
1733
1734# procedure to load a file to Tcl string
1735proc _read_file {filename} {
1736 set fd [open $filename r]
1737 set result [read -nonewline $fd]
1738 close $fd
1739 return $result
1740}
1741
22db40eb 1742# procedure to construct name for the mage diff file
1743proc _diff_img_name {dir1 dir2 casepath imgfile} {
1744 return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1745}
1746
936f43da 1747# auxiliary procedure to produce string comparing two values
1748proc _diff_show_ratio {value1 value2} {
1749 return "$value1 / $value2 \[[format "%+5.2f%%" [expr 100 * ($value1 - $value2) / double($value2)]]\]"
1750}
1751
cc6a292d 1752# Procedure to compare results of two runs of test cases
1753proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1754 upvar $_logvar log
1755
22db40eb 1756 # make sure to load diffimage command
1757 uplevel pload VISUALIZATION
1758
cc6a292d 1759 # prepare variable (array) for collecting statistics
1760 if { "$_statvar" != "" } {
1761 upvar $_statvar stat
1762 } else {
1763 set stat(cpu1) 0
1764 set stat(cpu2) 0
22db40eb 1765 set stat(mem1) 0
1766 set stat(mem2) 0
cc6a292d 1767 set log {}
1768 }
1769
1770 # first check subdirectories
1771 set path1 [file join $dir1 $basename]
1772 set path2 [file join $dir2 $basename]
1773 set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1774 set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1775 if { [llength $list1] >0 || [llength $list2] > 0 } {
1776 _list_diff $list1 $list2 in1 in2 common
1777 if { "$verbose" > 1 } {
1778 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1779 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1780 }
1781 foreach subdir $common {
1782 if { "$verbose" > 2 } {
1783 _log_and_puts log "Checking [file join $basename $subdir]"
1784 }
1785 _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1786 }
1787 } else {
1788 # check log files (only if directory has no subdirs)
1789 set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1790 set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1791 _list_diff $list1 $list2 in1 in2 common
1792 if { "$verbose" > 1 } {
1793 if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1794 if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1795 }
936f43da 1796 set gcpu1 0
1797 set gcpu2 0
1798 set gmem1 0
1799 set gmem2 0
cc6a292d 1800 foreach logfile $common {
1801 # load two logs
1802 set log1 [_read_file [file join $dir1 $basename $logfile]]
1803 set log2 [_read_file [file join $dir2 $basename $logfile]]
22db40eb 1804 set casename [file rootname $logfile]
cc6a292d 1805
1806 # check execution statuses
1807 set status1 UNDEFINED
1808 set status2 UNDEFINED
1809 if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1810 ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1811 "$status1" != "$status2" } {
22db40eb 1812 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
cc6a292d 1813
1814 # if test statuses are different, further comparison makes
1815 # no sense unless explicitly requested
1816 if { "$status" != "all" } {
1817 continue
1818 }
1819 }
1820 if { "$status" == "ok" && "$status1" != "OK" } {
1821 continue
1822 }
1823
1824 # check CPU times
1825 set cpu1 UNDEFINED
1826 set cpu2 UNDEFINED
1827 if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1828 [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1829 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1830 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
936f43da 1831 set gcpu1 [expr $gcpu1 + $cpu1]
1832 set gcpu2 [expr $gcpu2 + $cpu2]
cc6a292d 1833
1834 # compare CPU times with 10% precision (but not less 0.5 sec)
1835 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
936f43da 1836 _log_and_puts log "CPU [split $basename /] $casename: [_diff_show_ratio $cpu1 $cpu2]"
cc6a292d 1837 }
1838 }
22db40eb 1839
1840 # check memory delta
1841 set mem1 UNDEFINED
1842 set mem2 UNDEFINED
1843 if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1844 [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1845 set stat(mem1) [expr $stat(mem1) + $mem1]
1846 set stat(mem2) [expr $stat(mem2) + $mem2]
936f43da 1847 set gmem1 [expr $gmem1 + $mem1]
1848 set gmem2 [expr $gmem2 + $mem2]
22db40eb 1849
1850 # compare memory usage with 10% precision (but not less 16 KiB)
1851 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
936f43da 1852 _log_and_puts log "MEMORY [split $basename /] $casename: [_diff_show_ratio $mem1 $mem2]"
22db40eb 1853 }
1854 }
1855
1856 # check images
936f43da 1857 set imglist1 [glob -directory $path1 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1858 set imglist2 [glob -directory $path2 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
22db40eb 1859 _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1860 if { "$verbose" > 1 } {
1861 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1862 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1863 }
1864 foreach imgfile $imgcommon {
1865# if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1866 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1867 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1868 [file join $dir2 $basename $imgfile] \
1869 0 0 0 $diffile} diff] } {
1870 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1871 file delete -force $diffile ;# clean possible previous result of diffimage
1872 } elseif { $diff != 0 } {
1873 _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1874 } else {
1875 file delete -force $diffile ;# clean useless artifact of diffimage
1876 }
1877 }
cc6a292d 1878 }
936f43da 1879
1880 # report CPU and memory difference in group if it is greater than 10%
1881 if { [expr abs ($gcpu1 - $gcpu2) > 0.5 + 0.005 * abs ($gcpu1 + $gcpu2)] } {
1882 _log_and_puts log "CPU [split $basename /]: [_diff_show_ratio $gcpu1 $gcpu2]"
1883 }
1884 if { [expr abs ($gmem1 - $gmem2) > 16 + 0.005 * abs ($gmem1 + $gmem2)] } {
1885 _log_and_puts log "MEMORY [split $basename /]: [_diff_show_ratio $gmem1 $gmem2]"
1886 }
cc6a292d 1887 }
1888
1889 if { "$_statvar" == "" } {
936f43da 1890 _log_and_puts log "Total MEMORY difference: [_diff_show_ratio $stat(mem1) $stat(mem2)]"
1891 _log_and_puts log "Total CPU difference: [_diff_show_ratio $stat(cpu1) $stat(cpu2)]"
cc6a292d 1892 }
1893}
b725d7c5 1894
22db40eb 1895# Auxiliary procedure to save log of results comparison to file
d5f061b6 1896proc _log_html_diff {file log dir1 dir2 highlight_percent} {
22db40eb 1897 # create missing directories as needed
1898 catch {file mkdir [file dirname $file]}
1899
1900 # try to open a file
1901 if [catch {set fd [open $file w]} res] {
1902 error "Error saving log file $file: $res"
1903 }
1904
1905 # print header
1906 puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
433673e0 1907 puts $fd "<h1>Comparison of test results:</h1>"
1908 puts $fd "<h2>Version A - $dir1</h2>"
1909 puts $fd "<h2>Version B - $dir2</h2>"
22db40eb 1910
1911 # print log body, trying to add HTML links to script files on lines like
1912 # "Executing <filename>..."
1913 puts $fd "<pre>"
1914 set logpath [file split [file normalize $file]]
9753e6de 1915 foreach line $log {
d5f061b6 1916 # put a line; highlight considerable (> ${highlight_percent}%) deviations of CPU and memory
936f43da 1917 if { [regexp "\[\\\[](\[0-9.e+-]+)%\[\]]" $line res value] &&
d5f061b6 1918 [expr abs($value)] > ${highlight_percent} } {
936f43da 1919 puts $fd "<table><tr><td bgcolor=\"[expr $value > 0 ? \"red\" : \"lightgreen\"]\">$line</td></tr></table>"
1920 } else {
1921 puts $fd $line
1922 }
22db40eb 1923
936f43da 1924 # add images
22db40eb 1925 if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1926 if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1927 # note: special handler for the case if test grid directoried are compared directly
1928 set gridpath ""
1929 }
1930 set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1931 set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1932
1933 set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1934 if { [file exists $difffile] } {
1935 set imgd "<img src=\"[_make_url $file $difffile]\">"
1936 } else {
1937 set imgd "N/A"
1938 }
1939
433673e0 1940 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 1941 puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1942 }
1943 }
1944 puts $fd "</pre></body></html>"
1945
1946 close $fd
1947 return
1948}
1949
b725d7c5 1950# get number of CPUs on the system
1951proc _get_nb_cpus {} {
1952 global tcl_platform env
1953
1954 if { "$tcl_platform(platform)" == "windows" } {
1955 # on Windows, take the value of the environment variable
1956 if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1957 ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1958 return $env(NUMBER_OF_PROCESSORS)
1959 }
1960 } elseif { "$tcl_platform(os)" == "Linux" } {
1961 # on Linux, take number of logical processors listed in /proc/cpuinfo
1962 if { [catch {open "/proc/cpuinfo" r} fd] } {
1963 return 0 ;# should never happen, but...
1964 }
1965 set nb 0
1966 while { [gets $fd line] >= 0 } {
1967 if { [regexp {^processor[ \t]*:} $line] } {
1968 incr nb
1969 }
1970 }
1971 close $fd
1972 return $nb
1973 } elseif { "$tcl_platform(os)" == "Darwin" } {
1974 # on MacOS X, call sysctl command
1975 if { ! [catch {exec sysctl hw.ncpu} ret] &&
1976 [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
1977 return $nb
1978 }
1979 }
1980
1981 # if cannot get good value, return 0 as default
1982 return 0
1983}
351bbcba 1984
1985# check two files for difference
1986proc _diff_files {file1 file2} {
1987 set fd1 [open $file1 "r"]
1988 set fd2 [open $file2 "r"]
1989
1990 set differ f
1991 while {! $differ} {
1992 set nb1 [gets $fd1 line1]
1993 set nb2 [gets $fd2 line2]
1994 if { $nb1 != $nb2 } { set differ t; break }
1995 if { $nb1 < 0 } { break }
1996 if { [string compare $line1 $line2] } {
1997 set differ t
1998 }
1999 }
2000
2001 close $fd1
2002 close $fd2
2003
2004 return $differ
2005}
2006
2007# Check if file is in DOS encoding.
2008# This check is done by presence of \r\n combination at the end of the first
2009# line (i.e. prior to any other \n symbol).
2010# Note that presence of non-ascii symbols typically used for recognition
2011# of binary files is not suitable since some IGES and STEP files contain
2012# non-ascii symbols.
2013# Special check is added for PNG files which contain \r\n in the beginning.
2014proc _check_dos_encoding {file} {
2015 set fd [open $file rb]
2016 set isdos f
2017 if { [gets $fd line] && [regexp {.*\r$} $line] &&
2018 ! [regexp {^.PNG} $line] } {
2019 set isdos t
2020 }
2021 close $fd
2022 return $isdos
2023}
2024
2025# procedure to recognize format of a data file by its first symbols (for OCCT
2026# BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
2027proc _check_file_format {file} {
2028 set fd [open $file rb]
2029 set line [read $fd 1024]
2030 close $fd
2031
2032 set warn f
2033 set ext [file extension $file]
2034 set format unknown
2035 if { [regexp {^DBRep_DrawableShape} $line] } {
2036 set format BREP
2037 if { "$ext" != ".brep" && "$ext" != ".rle" &&
2038 "$ext" != ".draw" && "$ext" != "" } {
2039 set warn t
2040 }
2041 } elseif { [regexp {^DrawTrSurf_} $line] } {
2042 set format DRAW
2043 if { "$ext" != ".rle" &&
2044 "$ext" != ".draw" && "$ext" != "" } {
2045 set warn t
2046 }
2047 } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2048 set format STEP
2049 if { "$ext" != ".step" && "$ext" != ".stp" } {
2050 set warn t
2051 }
2052 } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2053 set format IGES
2054 if { "$ext" != ".iges" && "$ext" != ".igs" } {
2055 set warn t
2056 }
2057 } elseif { "$ext" == ".igs" } {
2058 set format IGES
2059 } elseif { "$ext" == ".stp" } {
2060 set format STEP
2061 } else {
2062 set format [string toupper [string range $ext 1 end]]
2063 }
2064
2065 if { $warn } {
2066 puts "$file: Warning: extension ($ext) does not match format ($format)"
2067 }
2068
2069 return $format
2070}
2071
2072# procedure to load file knowing its format
2073proc load_data_file {file format shape} {
2074 switch $format {
2075 BREP { uplevel restore $file $shape }
808b3f9f 2076 DRAW { uplevel restore $file $shape }
351bbcba 2077 IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
2078 STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
2079 STL { pload XSDRAW; uplevel readstl $shape $file }
2080 default { error "Cannot read $format file $file" }
2081 }
2082}
60874ff8 2083
2084# procedure to get name of temporary directory,
2085# ensuring it is existing and writeable
2086proc _get_temp_dir {} {
723754e2 2087 global env tcl_platform
60874ff8 2088
2089 # check typical environment variables
2090 foreach var {TempDir Temp Tmp} {
2091 # check different case
2092 foreach name [list [string toupper $var] $var [string tolower $var]] {
2093 if { [info exists env($name)] && [file isdirectory $env($name)] &&
2094 [file writable $env($name)] } {
2095 return [regsub -all {\\} $env($name) /]
2096 }
2097 }
2098 }
2099
2100 # check platform-specific locations
2101 set fallback tmp
2102 if { "$tcl_platform(platform)" == "windows" } {
2103 set paths "c:/TEMP c:/TMP /TEMP /TMP"
2104 if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
2105 set fallback [regsub -all {\\} "$env(HOMEDRIVE)$(HOMEPATH)/tmp" /]
2106 }
2107 } else {
2108 set paths "/tmp /var/tmp /usr/tmp"
2109 if { [info exists env(HOME)] } {
2110 set fallback "$env(HOME)/tmp"
2111 }
2112 }
2113 foreach dir $paths {
723754e2 2114 if { [file isdirectory $dir] && [file writable $dir] } {
60874ff8 2115 return $dir
2116 }
2117 }
2118
2119 # fallback case: use subdir /tmp of home or current dir
2120 file mkdir $fallback
2121 return $fallback
2122}
9753e6de 2123
2124# extract of code from testgrid command used to process jobs running in
2125# parallel until number of jobs in the queue becomes equal or less than
2126# specified value
2127proc _testgrid_process_jobs {worker {nb_ok 0}} {
2128 # bind local vars to variables of the caller procedure
2129 upvar log log
2130 upvar logdir logdir
2131 upvar job_def job_def
2132 upvar nbpooled nbpooled
2133 upvar userbreak userbreak
2134 upvar refresh refresh
2135 upvar refresh_timer refresh_timer
2136
2137 catch {tpool::resume $worker}
2138 while { ! $userbreak && $nbpooled > $nb_ok } {
2139 foreach job [tpool::wait $worker [array names job_def]] {
2140 eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2141 unset job_def($job)
2142 incr nbpooled -1
2143 }
2144
2145 # check for user break
2146 if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2147 set userbreak 1
2148 }
2149
2150 # update summary log with requested period
2151 if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2152 _log_summarize $logdir $log
2153 set refresh_timer [clock seconds]
2154 }
2155 }
2156 catch {tpool::suspend $worker}
2157}
ccadc126 2158
2159help checkcolor {
2160 Check pixel color.
2161 Use: checkcolor x y red green blue
2162 x y - pixel coordinates
2163 red green blue - expected pixel color (values from 0 to 1)
2164 Function check color with tolerance (5x5 area)
2165}
2166# Procedure to check color using command vreadpixel with tolerance
2167proc checkcolor { coord_x coord_y rd_get gr_get bl_get } {
2168 puts "Coordinate x = $coord_x"
2169 puts "Coordinate y = $coord_y"
2170 puts "RED color of RGB is $rd_get"
2171 puts "GREEN color of RGB is $gr_get"
2172 puts "BLUE color of RGB is $bl_get"
2173
2174 if { $coord_x <= 1 || $coord_y <= 1 } {
2175 puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2176 return -1
2177 }
2178
2179 set color ""
2180 catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2181 if {"$color" == ""} {
2182 puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2183 }
2184 set rd [lindex $color 0]
2185 set gr [lindex $color 1]
2186 set bl [lindex $color 2]
2187 set rd_int [expr int($rd * 1.e+05)]
2188 set gr_int [expr int($gr * 1.e+05)]
2189 set bl_int [expr int($bl * 1.e+05)]
2190 set rd_ch [expr int($rd_get * 1.e+05)]
2191 set gr_ch [expr int($gr_get * 1.e+05)]
2192 set bl_ch [expr int($bl_get * 1.e+05)]
2193
2194 if { $rd_ch != 0 } {
2195 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2196 } else {
2197 set tol_rd $rd_int
2198 }
2199 if { $gr_ch != 0 } {
2200 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2201 } else {
2202 set tol_gr $gr_int
2203 }
2204 if { $bl_ch != 0 } {
2205 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2206 } else {
2207 set tol_bl $bl_int
2208 }
2209
2210 set status 0
2211 if { $tol_rd > 0.2 } {
2212 puts "Warning : RED light of additive color model RGB is invalid"
2213 set status 1
2214 }
2215 if { $tol_gr > 0.2 } {
2216 puts "Warning : GREEN light of additive color model RGB is invalid"
2217 set status 1
2218 }
2219 if { $tol_bl > 0.2 } {
2220 puts "Warning : BLUE light of additive color model RGB is invalid"
2221 set status 1
2222 }
2223
2224 if { $status != 0 } {
2225 puts "Warning : Colors of default coordinate are not equal"
2226 }
2227
2228 global stat
2229 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2230 set info [_checkpoint $coord_x $coord_y $rd_ch $gr_ch $bl_ch]
2231 set stat [lindex $info end]
2232 if { ${stat} != 1 } {
2233 puts "Error : Colors are not equal in default coordinate and in the near coordinates too"
2234 return $stat
2235 } else {
2236 puts "Point with valid color was found"
2237 return $stat
2238 }
2239 } else {
2240 set stat 1
2241 }
2242}
2243
2244# Procedure to check color in the point near default coordinate
2245proc _checkpoint {coord_x coord_y rd_ch gr_ch bl_ch} {
2246 set x_start [expr ${coord_x} - 2]
2247 set y_start [expr ${coord_y} - 2]
2248 set mistake 0
2249 set i 0
2250 while { $mistake != 1 && $i <= 5 } {
2251 set j 0
2252 while { $mistake != 1 && $j <= 5 } {
2253 set position_x [expr ${x_start} + $j]
2254 set position_y [expr ${y_start} + $i]
2255 puts $position_x
2256 puts $position_y
2257
2258 set color ""
2259 catch { [set color "[vreadpixel ${position_x} ${position_y} rgb]"] }
2260 if {"$color" == ""} {
2261 puts "Warning : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2262 incr j
2263 continue
2264 }
2265 set rd [lindex $color 0]
2266 set gr [lindex $color 1]
2267 set bl [lindex $color 2]
2268 set rd_int [expr int($rd * 1.e+05)]
2269 set gr_int [expr int($gr * 1.e+05)]
2270 set bl_int [expr int($bl * 1.e+05)]
2271
2272 if { $rd_ch != 0 } {
2273 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2274 } else {
2275 set tol_rd $rd_int
2276 }
2277 if { $gr_ch != 0 } {
2278 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2279 } else {
2280 set tol_gr $gr_int
2281 }
2282 if { $bl_ch != 0 } {
2283 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2284 } else {
2285 set tol_bl $bl_int
2286 }
2287
2288 if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2289 puts "Warning : Point with true color was not found near default coordinates"
2290 set mistake 0
2291 } else {
2292 set mistake 1
2293 }
2294 incr j
2295 }
2296 incr i
2297 }
2298 return $mistake
2299}