Logo AND Algorithmique Numérique Distribuée

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