Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update tesh.pl.
[simgrid.git] / buildtools / Cmake / Scripts / tesh.pl
1 #! /usr/bin/perl
2
3 # Copyright (c) 2012-2014. The SimGrid Team.
4 # All rights reserved.
5
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the license (GNU LGPL) which comes with this package.
8
9 eval 'exec perl -S $0 ${1+"$@"}'
10   if $running_under_some_shell;
11
12 =encoding UTF-8
13
14 =head1 NAME
15
16 tesh -- testing shell
17
18 =head1 SYNOPSIS
19
20 B<tesh> [I<options>] I<tesh_file>
21
22 =cut
23 my($bindir)=".";
24 my($srcdir)=".";
25 my($timeout)=0;
26 my($time_to_wait)=0;
27 my $path = $0;
28 my $OS;
29 my $enable_coverage=0;
30 my $sort_prefix = 19;
31 my $tesh_file;
32 my $tesh_name;
33 my $error=0;
34 my $exitcode=0;
35 my @bg_cmds;
36 my (%environ);
37
38 $path =~ s|[^/]*$||;
39 push @INC,$path;
40
41 use Getopt::Long qw(GetOptions);
42 use strict;
43 use Term::ANSIColor;
44 use Text::ParseWords;
45 use IPC::Open3;
46 use IO::File;
47
48 if($^O eq "linux"){
49     $OS = "UNIX";
50 }
51 else{
52     $OS = "WIN";
53     $ENV{"PRINTF_EXPONENT_DIGITS"} = "2"; 
54 }
55
56 ##
57 ## Command line option handling
58 ##
59
60 sub var_subst {
61     my ($text, $name, $value) = @_;
62     if ($value) {
63         $text =~ s/\${$name(?::[=-][^}]*)?}/$value/g;
64         $text =~ s/\$$name(\W|$)/$value$1/g;
65     }
66     else {
67         $text =~ s/\${$name:=([^}]*)}/$1/g;
68         $text =~ s/\${$name}//g;
69         $text =~ s/\$$name(\W|$)/$1/g;
70     }
71     return $text;
72 }
73
74 # option handling helper subs
75 sub cd_cmd {
76   my $directory=$_[1];
77   my $failure=1;
78   if (-e $directory && -d $directory) {
79     chdir("$directory");
80     print "[Tesh/INFO] change directory to $directory\n";
81   $failure=0;
82   } elsif (-e $directory) {
83     print "Cannot change directory to '$directory': it is not a directory\n";
84   } else {
85     print "Chdir to $directory failed: No such file or directory\n";
86   }
87   if($failure==1){
88   $error=1;
89   $exitcode=4;
90   print "Test suite `$tesh_file': NOK (system error)\n";
91   exit 4;
92   }
93 }
94
95 sub setenv_cmd {
96   my($var,$ctn);
97   if ($_[0] =~ /^(.*)=(.*)$/) {
98     ($var,$ctn)=($1,$2);
99   }elsif ($_[1] =~ /^(.*)=(.*)$/) {
100     ($var,$ctn)=($1,$2);
101   } else { 
102       die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$_[1]'\n";
103   }
104     
105   print "[Tesh/INFO] setenv $var=$ctn\n";
106   $environ{$var} = $ctn;
107 }
108
109 # Main option parsing sub
110
111 sub get_options {
112   # remove the tesh file from the ARGV used
113   my @ARGV = @_;
114   $tesh_file = pop @ARGV;
115
116   # temporary arrays for GetOption
117   my @verbose = ();
118   my @cfg;
119   my $log; # ignored
120
121
122   my %opt = (
123     "help"  => 0,
124     "debug"   => 0,
125     "verbose" => 0
126     );
127
128   Getopt::Long::config('bundling', 'no_getopt_compat', 'no_auto_abbrev');
129   
130   GetOptions(
131     'help|h'   => \$opt{'help'},
132
133     'verbose|v'  => \@verbose,
134     'debug|d'  => \$opt{"debug"},
135
136     'cd=s'     => \&cd_cmd,
137     'timeout=s'  => \$opt{'timeout'},    
138     'setenv=s'   => \&setenv_cmd,
139     'cfg=s'    => \@cfg,
140     'log=s'    => \$log,
141     'enable-coverage+'  => \$enable_coverage,    
142     );
143
144   if($enable_coverage){
145     print "Enable coverage\n";
146   }
147
148   unless($tesh_file=~/(.*)\.tesh/){
149     $tesh_file="(stdin)";
150     $tesh_name="(stdin)";
151     print "Test suite from stdin\n";
152   }else{
153     $tesh_name=$1;
154     print "Test suite `$tesh_name'\n";
155   }
156
157   $opt{'verbose'} = scalar @verbose;
158   foreach (@cfg) {
159     $opt{'cfg'} .= " --cfg=$_";
160   }
161   return %opt;
162 }
163
164 my %opts = get_options(@ARGV);
165
166 ##
167 ## File parsing
168 ##
169 my($nb_arg)=0;
170 my($old_buffer);
171 my($linebis);
172 my($SIGABRT)=0;
173 my($verbose)=0;
174 my($return)=-1;
175 my($pid);
176 my($result);
177 my($result_err);
178 my($forked);
179 my($config)="";
180 my($tesh_command)=0;
181 my(@buffer_tesh)=();
182
183 #eval {
184   use POSIX;
185
186   sub exit_status {
187     my $status = shift;
188     if (POSIX::WIFEXITED($status)) {
189       $exitcode=POSIX::WEXITSTATUS($status)+40;
190       return "returned code ".POSIX::WEXITSTATUS($status);
191     } elsif (POSIX::WIFSIGNALED($status)) {
192       my $code;
193       if (POSIX::WTERMSIG($status) == SIGINT){$code="SIGINT"; }
194       elsif  (POSIX::WTERMSIG($status) == SIGTERM) {$code="SIGTERM"; }
195       elsif  (POSIX::WTERMSIG($status) == SIGKILL) {$code= "SIGKILL"; }
196       elsif  (POSIX::WTERMSIG($status) == SIGABRT) {$code="SIGABRT"; }
197       elsif  (POSIX::WTERMSIG($status) == SIGSEGV) {$code="SIGSEGV" ;}
198       $exitcode=POSIX::WTERMSIG($status)+4;
199       return "got signal $code";
200     }
201     return "Unparsable status. Is the process stopped?";
202   }
203 #};
204 #if ($@) { # no POSIX available?
205 #  warn "POSIX not usable to parse the return value of forked child: $@\n";
206 #  sub exit_status {
207 #    return "returned code -1 $@ ";
208 #  }
209 #}
210
211 sub exec_cmd { 
212   my %cmd = %{$_[0]};
213   if ($opts{'debug'}) {
214     print "IN BEGIN\n";
215     map {print "  $_"} @{$cmd{'in'}};
216     print "IN END\n";
217     print "OUT BEGIN\n";
218     map {print "  $_"} @{$cmd{'out'}};
219     print "OUT END\n";
220     print "CMD: $cmd{'cmd'}\n";
221   }
222
223   # cleanup the command line
224   if($OS eq "WIN") {
225       var_subst($cmd{'cmd'}, "EXEEXT", ".exe");
226   } else {
227       var_subst($cmd{'cmd'}, "EXEEXT", "");
228   }
229
230   # substitute environ variables
231   foreach my $key (keys %environ) {
232       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $key, $environ{$key});
233   }
234   # substitute remaining variables, if any
235   while ($cmd{'cmd'} =~ /\${(\w+)(?::[=-][^}]*)?}/) {
236       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
237   }
238   while ($cmd{'cmd'} =~ /\$(\w+)/) {
239       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
240   }
241
242   # add cfg options
243   $cmd{'cmd'} .= " $opts{'cfg'}" if (defined($opts{'cfg'}) && length($opts{'cfg'}));
244
245   # final cleanup
246   $cmd{'cmd'} =~ s/^\s+//;
247   $cmd{'cmd'} =~ s/\s+$//;
248
249   print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n" ;
250
251   ###
252   # exec the command line
253   ###  $line =~ s/\r//g;
254
255   $cmd{'got'} = IO::File->new_tmpfile;
256   $cmd{'got'}->autoflush(1);
257   local *E = $cmd{'got'}; 
258   $cmd{'pid'} = open3(\*CHILD_IN,  ">&E",  ">&E",
259                       quotewords('\s+', 0, $cmd{'cmd'}));
260
261   # push all provided input to executing child
262   map { print CHILD_IN "$_\n"; }  @{$cmd{'in'}};
263   close CHILD_IN;
264
265   # if timeout specified, fork and kill executing child at the end of timeout
266   if (defined($cmd{'timeout'}) or defined($opts{'timeout'})){
267     $time_to_wait= defined($cmd{'timeout'}) ? $cmd{'timeout'} : $opts{'timeout'};
268     $forked = fork();
269     $timeout=-1;
270     die "fork() failed: $!" unless defined $forked;
271     if ( $forked == 0 ) { # child
272       sleep $time_to_wait;
273       kill(SIGKILL, $cmd{'pid'});
274       exit $time_to_wait;
275     }
276   }
277
278   
279   # Cleanup the executing child, and kill the timeouter brother on need
280   $cmd{'return'} = 0 unless defined($cmd{'return'});
281   if($cmd{'background'} != 1){
282     waitpid ($cmd{'pid'}, 0);
283     $cmd{'gotret'} = exit_status($?);
284     parse_out(\%cmd);
285   }else{
286     # & commands, which will be handled at the end
287     push @bg_cmds, \%cmd;
288     # no timeout for background commands
289     if($forked){
290        kill(SIGKILL, $forked);
291        $timeout=0;
292        $forked=0;
293     }
294   }
295 }
296
297
298 sub parse_out { 
299   my %cmd = %{$_[0]};
300   my $gotret=$cmd{'gotret'};
301
302   my $wantret;
303
304   if(defined($cmd{'expect'}) and ($cmd{'expect'} ne "")){
305     $wantret = "got signal $cmd{'expect'}";
306   }else{
307     $wantret = "returned code ".(defined($cmd{'return'})? $cmd{'return'} : 0);
308   }
309
310   local *got = $cmd{'got'};
311   seek(got,0,0);
312   # pop all output from executing child
313   my @got;
314   while(defined(my $got=<got>)) {
315     $got =~ s/\r//g;
316     chomp $got;
317     if (!($enable_coverage and $got=~ /^profiling:/)){
318       push @got, $got;
319     }
320   }    
321
322   if ($cmd{'sort'}){   
323     sub mysort{
324         substr($a, 0, $sort_prefix) cmp substr($b, 0, $sort_prefix)
325     }
326     use sort 'stable';
327     @got = sort mysort @got;
328     while (@got and $got[0] eq "") {
329       shift @got;
330     }
331
332     #also resort the other one, as perl sort is not the same as the C one used to generate teshes
333     if(defined($cmd{'out'})){
334       @{$cmd{'out'}}=sort mysort @{$cmd{'out'}};
335       while (@{$cmd{'out'}} and ${$cmd{'out'}}[0] eq "") {
336         shift @{$cmd{'out'}};
337       }
338     }
339   }
340
341   #Did we timeout ? If yes, handle it. If not, kill the forked process.
342
343   if($timeout==-1 and $gotret eq "got signal SIGKILL"){
344     $gotret="return code 0";
345     $timeout=1;
346     $gotret= "timeout after $time_to_wait sec";
347     $error=1;
348     $exitcode=3;
349     print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
350   }else{
351     $timeout=0;  
352   }
353   if($gotret ne $wantret) {
354     $error=1;
355     my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
356     if ($timeout!=1) {
357         $msg=$msg."Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";    
358     }
359     map {$msg .=  "|| $_\n"} @got;
360     if(!@got) {
361         if($timeout==1){
362         print STDERR "<$cmd{'file'}:$cmd{'line'}> No output before timeout\n";
363         }else{
364         $msg .= "||\n";
365         }
366     }
367     $timeout = 0;
368     print STDERR "$msg";
369   }
370
371       
372   ###
373   # Check the result of execution 
374   ###
375   my $diff;
376   if (!defined($cmd{'output ignore'})){
377     $diff = build_diff(\@{$cmd{'out'}}, \@got);
378   }else{
379   print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n"
380   }
381   if (length $diff) {
382     print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch:\n";
383     map { print "$_\n" } split(/\n/,$diff);
384
385     print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
386     $error=1;
387     $exitcode=2;
388   }
389 }
390
391 sub mkfile_cmd {
392   my %cmd = %{$_[0]};
393   my $file = $cmd{'arg'};
394   print "[Tesh/INFO] mkfile $file\n";
395
396   unlink($file);
397   open(FILE,">$file") or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
398   print FILE join("\n", @{$cmd{'in'}});
399   print FILE "\n" if (scalar @{$cmd{'in'}} > 0);
400   close(FILE);
401 }
402
403 # parse tesh file
404 #my $teshfile=$tesh_file;
405 #$teshfile=~ s{\.[^.]+$}{};
406
407 unless($tesh_file eq "(stdin)"){
408   open TESH_FILE, $tesh_file or die "[Tesh/CRITICAL] Unable to open $tesh_file $!\n";
409 }
410
411 my %cmd; # everything about the next command to run
412 my $line_num=0;
413 my $finished =0;
414 LINE: while (not $finished and not $error) {
415   my $line;
416
417
418   if ($tesh_file ne "(stdin)" and !defined($line=<TESH_FILE>)){
419     $finished=1;
420     next LINE;
421   }elsif ($tesh_file eq "(stdin)" and !defined($line=<>)){
422     $finished=1;
423     next LINE;
424   }
425
426
427   $line_num++;
428   chomp $line;
429   $line =~ s/\r//g;
430   print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
431   my $next;
432   # deal with line continuations
433   while ($line =~ /^(.*?)\\$/) {
434     $next=<TESH_FILE>;
435     die "[TESH/CRITICAL] Continued line at end of file\n"
436       unless defined($next);
437     $line_num++;
438     chomp $next;
439     print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
440     $line = $1.$next;
441   }
442
443   # Push delayed commands on empty lines
444   unless ($line =~ m/^(.)(.*)$/) {
445     if (defined($cmd{'cmd'}))  {
446       exec_cmd(\%cmd);
447       %cmd = ();
448     }
449     next LINE;
450   }     
451  
452   my ($cmd,$arg) = ($1,$2);
453   $arg =~ s/^ //g;
454   $arg =~ s/\r//g;
455   $arg =~ s/\\\\/\\/g;
456   # handle the commands
457   if ($cmd =~ /^#/) {    #comment
458   } elsif ($cmd eq '>'){    #expected result line
459     print "[TESH/debug] push expected result\n" if $opts{'debug'};
460     push @{$cmd{'out'}}, $arg;
461
462   } elsif ($cmd eq '<') {    # provided input
463     print "[TESH/debug] push provided input\n" if $opts{'debug'};
464     push @{$cmd{'in'}}, $arg;
465
466   } elsif ($cmd eq 'p') {    # comment
467     print "[$tesh_name:$line_num] $arg\n";
468
469   } elsif ($cmd eq '$') {  # Command
470     # if we have something buffered, run it now
471     if (defined($cmd{'cmd'})) {
472       exec_cmd(\%cmd);
473       %cmd = ();
474     }
475     if ($arg =~ /^\s*mkfile /){      # "mkfile" command line
476       die "[TESH/CRITICAL] Output expected from mkfile command!\n" if scalar @{cmd{'out'}};
477
478       $cmd{'arg'} = $arg;
479       $cmd{'arg'} =~ s/\s*mkfile //;
480       mkfile_cmd(\%cmd);
481       %cmd = ();
482
483     } elsif ($arg =~ /^\s*cd /) {
484       die "[TESH/CRITICAL] Input provided to cd command!\n" if scalar @{cmd{'in'}};
485       die "[TESH/CRITICAL] Output expected from cd command!\n" if scalar @{cmd{'out'}};
486
487       $arg =~ s/^ *cd //;
488       cd_cmd("",$arg);
489       %cmd = ();
490
491     } else { # regular command
492       $cmd{'cmd'} = $arg;
493       $cmd{'file'} = $tesh_file;
494       $cmd{'line'} = $line_num;
495     }
496   }
497   elsif($cmd eq '&'){      # parallel command line
498
499     if (defined($cmd{'cmd'})) {
500       exec_cmd(\%cmd);
501       %cmd = ();
502     }
503     $cmd{'background'} = 1;
504     $cmd{'cmd'} = $arg;
505     $cmd{'file'} = $tesh_file;
506     $cmd{'line'} = $line_num;
507   }    
508   elsif($line =~ /^!\s*output sort/){    #output sort
509     if (defined($cmd{'cmd'})) {
510       exec_cmd(\%cmd);
511       %cmd = ();
512     }
513     $cmd{'sort'} = 1;
514     if ($line =~ /^!\s*output sort\s+(\d+)/) {
515         $sort_prefix = $1;
516     }
517   }
518   elsif($line =~ /^!\s*output ignore/){    #output ignore
519     if (defined($cmd{'cmd'})) {
520       exec_cmd(\%cmd);
521       %cmd = ();
522     }
523     $cmd{'output ignore'} = 1;
524   }
525   elsif($line =~ /^!\s*expect signal (\w*)/) {#expect signal SIGABRT
526     if (defined($cmd{'cmd'})) {
527       exec_cmd(\%cmd);
528       %cmd = ();
529     }
530 print "hey\n";
531     $cmd{'expect'} = "$1";
532   }
533   elsif($line =~ /^!\s*expect return/){    #expect return
534     if (defined($cmd{'cmd'})) {
535       exec_cmd(\%cmd);
536       %cmd = ();
537     }
538     $line =~ s/^! expect return //g;
539     $line =~ s/\r//g;
540     $cmd{'return'} = $line;
541   }
542   elsif($line =~ /^!\s*setenv/){    #setenv
543     if (defined($cmd{'cmd'})) {
544       exec_cmd(\%cmd);
545       %cmd = ();
546     }
547     $line =~ s/^! setenv //g;
548     $line =~ s/\r//g;
549     setenv_cmd($line);
550   }
551   elsif($line =~ /^!\s*include/){    #include
552     if (defined($cmd{'cmd'})) {
553       exec_cmd(\%cmd);
554       %cmd = ();
555     }
556     print color("red"), "[Tesh/CRITICAL] need include";
557     print color("reset"), "\n";
558     die;
559   }
560   elsif($line =~ /^!\s*timeout/){    #timeout
561     if (defined($cmd{'cmd'})) {
562       exec_cmd(\%cmd);
563       %cmd = ();
564     }
565     $line =~ s/^! timeout //;
566     $line =~ s/\r//g;
567     $cmd{'timeout'} = $line;
568   } else {
569     die "[TESH/CRITICAL] parse error: $line\n";
570   }
571   if($forked){
572    kill(SIGKILL, $forked);
573    $timeout=0;
574   }
575
576 }
577
578
579
580 # Deal with last command
581 if (defined($cmd{'cmd'})) {
582   exec_cmd(\%cmd);
583   %cmd = ();
584 }
585
586
587 if($forked){
588    kill(SIGKILL, $forked);
589    $timeout=0;
590 }
591
592 foreach(@bg_cmds){
593   my %test=%{$_};
594   waitpid ($test{'pid'}, 0);
595   $test{'gotret'} = exit_status($?);
596   parse_out(\%test);
597 }
598
599 @bg_cmds=();
600
601
602 if($error !=0){
603     exit $exitcode;
604 }elsif($tesh_file eq "(stdin)"){
605     print "Test suite from stdin OK\n";
606 }else{
607     print "Test suite `$tesh_name' OK\n";
608 }
609
610 #my (@a,@b);
611 #push @a,"bl1";   push @b,"bl1";
612 #push @a,"bl2";   push @b,"bl2";
613 #push @a,"bl3";   push @b,"bl3";
614 #push @a,"bl4";   push @b,"bl4";
615 #push @a,"bl5";   push @b,"bl5";
616 #push @a,"bl6";   push @b,"bl6";
617 #push @a,"bl7";   push @b,"bl7";
618 ##push @a,"Perl";  push @b,"ruby";
619 #push @a,"END1";   push @b,"END1";
620 #push @a,"END2";   push @b,"END2";
621 #push @a,"END3";   push @b,"END3";
622 #push @a,"END4";   push @b,"END4";
623 #push @a,"END5";   push @b,"END5";
624 #push @a,"END6";   push @b,"END6";
625 #push @a,"END7";   push @b,"END7";
626 #print "Identical:\n". build_diff(\@a,\@b);
627
628 #@a = (); @b =();
629 #push @a,"AZE"; push @b,"EZA";
630 #print "Different:\n".build_diff(\@a,\@b);
631
632 use lib "@CMAKE_BINARY_DIR@/bin" ;
633
634 use Diff qw(diff); # postpone a bit to have time to change INC
635
636 sub build_diff {
637   my $res;
638   my $diff = Diff->new(@_);
639   
640   $diff->Base( 1 );   # Return line numbers, not indices
641   my $chunk_count = $diff->Next(-1); # Compute the amount of chuncks
642   return ""   if ($chunk_count == 1 && $diff->Same());
643   $diff->Reset();
644   while(  $diff->Next()  ) {
645     my @same = $diff->Same();
646     if ($diff->Same() ) {
647       if ($diff->Next(0) > 1) { # not first chunk: print 2 first lines
648         $res .= '  '.$same[0]."\n" ;
649         $res .= '  '.$same[1]."\n" if (scalar @same>1);
650       }     
651       $res .= "...\n"  if (scalar @same>2);
652 #    $res .= $diff->Next(0)."/$chunk_count\n";
653       if ($diff->Next(0) < $chunk_count) { # not last chunk: print 2 last lines
654         $res .= '  '.$same[scalar @same -2]."\n" if (scalar @same>1);
655         $res .= '  '.$same[scalar @same -1]."\n";
656       } 
657     } 
658     next if  $diff->Same();
659     map { $res .= "- $_\n" } $diff->Items(1);
660     map { $res .= "+ $_\n" } $diff->Items(2);
661   }
662   return $res;
663 }
664
665