3 # Copyright (c) 2012-2015. The SimGrid Team.
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;
11 # If you change this file, please stick to the formatting you got with:
12 # perltidy --backup-and-modify-in-place --maximum-line-length=180 --output-line-ending=unix --cuddled-else
22 B<tesh> [I<options>] I<tesh_file>
27 # Disabling IPC::Run::Debug saves tons of useless calls.
28 $ENV{'IPCRUNDEBUG'} = 'none'
29 unless exists $ENV{'IPCRUNDEBUG'};
33 my ($time_to_wait) = 0;
35 my $enable_coverage = 0;
37 my $diff_tool_tmp_fh = 0;
38 my $diff_tool_tmp_filename = 0;
46 $SIG{'PIPE'} = 'IGNORE';
50 use lib "@CMAKE_BINARY_DIR@/bin";
52 use Diff qw(diff); # postpone a bit to have time to change INC
54 use Getopt::Long qw(GetOptions);
57 use IPC::Run qw(start run timeout finish);
62 #### Portability bits for windows
65 use constant RUNNING_ON_WINDOWS => ( $OSNAME =~ /^(?:mswin|dos|os2)/oi );
66 use POSIX qw(:sys_wait_h WIFEXITED WIFSIGNALED WIFSTOPPED WEXITSTATUS WTERMSIG WSTOPSIG
67 :signal_h SIGINT SIGTERM SIGKILL SIGABRT SIGSEGV);
70 if (RUNNING_ON_WINDOWS) { # Missing on windows
71 *WIFEXITED = sub { not $_[0] & 127 };
72 *WEXITSTATUS = sub { $_[0] >> 8 };
73 *WIFSIGNALED = sub { ( $_[0] & 127 ) && ( $_[0] & 127 != 127 ) };
74 *WTERMSIG = sub { $_[0] & 127 };
80 #### Command line option handling
83 if ( $ARGV[0] eq "--internal-killer-process" ) {
85 # We fork+exec a waiter process in charge of killing the command after timeout
86 # If the command stops earlier, that's fine: the killer sends a signal to an already stopped process, fails, and quits.
87 # Nobody cares about the killer issues.
88 # The only problem could arise if another process is given the same PID than cmd. We bet it won't happen :)
89 my $time_to_wait = $ARGV[1];
98 my %opts = ( "debug" => 0,
99 "timeout" => 120, # No command should run any longer than 2 minutes by default
102 Getopt::Long::config( 'bundling', 'no_getopt_compat', 'no_auto_abbrev' );
104 'debug|d' => \$opts{"debug"},
106 'difftool=s' => \$diff_tool,
108 'cd=s' => sub { cd_cmd( $_[1] ) },
109 'timeout=s' => \$opts{'timeout'},
110 'setenv=s' => sub { setenv_cmd( $_[1] ) },
111 'cfg=s' => sub { $opts{'cfg'} .= " --cfg=$_[1]" },
112 'enable-coverage+' => \$enable_coverage,
115 $tesh_file = pop @ARGV;
117 if ($enable_coverage) {
118 print "Enable coverage\n";
122 use File::Temp qw/ tempfile /;
123 ( $diff_tool_tmp_fh, $diff_tool_tmp_filename ) = tempfile();
124 print "New tesh: $diff_tool_tmp_filename\n";
127 if ( $tesh_file =~ m/(.*)\.tesh/ ) {
129 print "Test suite `$tesh_name'\n";
131 $tesh_file = "(stdin)";
132 $tesh_name = "(stdin)";
133 print "Test suite from stdin\n";
142 my (@buffer_tesh) = ();
144 ###########################################################################
148 if ( WIFEXITED($status) ) {
149 $exitcode = WEXITSTATUS($status) + 40;
150 return "returned code " . WEXITSTATUS($status);
151 } elsif ( WIFSIGNALED($status) ) {
153 if ( WTERMSIG($status) == SIGINT ) { $code = "SIGINT"; }
154 elsif ( WTERMSIG($status) == SIGTERM ) { $code = "SIGTERM"; }
155 elsif ( WTERMSIG($status) == SIGKILL ) { $code = "SIGKILL"; }
156 elsif ( WTERMSIG($status) == SIGABRT ) { $code = "SIGABRT"; }
157 elsif ( WTERMSIG($status) == SIGSEGV ) { $code = "SIGSEGV"; }
158 $exitcode = WTERMSIG($status) + 4;
159 return "got signal $code";
161 return "Unparsable status. Is the process stopped?";
165 my %cmd = %{ $_[0] };
166 if ( $opts{'debug'} ) {
167 map { print "IN: $_\n" } @{ $cmd{'in'} };
168 map { print "OUT: $_\n" } @{ $cmd{'out'} };
169 print "CMD: $cmd{'cmd'}\n";
172 # cleanup the command line
173 if (RUNNING_ON_WINDOWS) {
174 var_subst( $cmd{'cmd'}, "EXEEXT", ".exe" );
176 var_subst( $cmd{'cmd'}, "EXEEXT", "" );
179 # substitute environ variables
180 foreach my $key ( keys %environ ) {
181 $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $key, $environ{$key} );
184 # substitute remaining variables, if any
185 while ( $cmd{'cmd'} =~ /\${(\w+)(?::[=-][^}]*)?}/ ) {
186 $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $1, "" );
188 while ( $cmd{'cmd'} =~ /\$(\w+)/ ) {
189 $cmd{'cmd'} = var_subst( $cmd{'cmd'}, $1, "" );
193 $cmd{'cmd'} .= " $opts{'cfg'}"
194 if ( defined( $opts{'cfg'} ) && length( $opts{'cfg'} ) );
196 # finally trim any remaining space chars
197 $cmd{'cmd'} =~ s/^\s+//;
198 $cmd{'cmd'} =~ s/\s+$//;
200 print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n";
202 $cmd{'return'} ||= 0;
203 $cmd{'timeout'} ||= $opts{'timeout'};
207 # exec the command line
209 my @cmdline = quotewords( '\s+', 0, $cmd{'cmd'} );
210 my $input = defined($cmd{'in'})? join("\n",@{$cmd{'in'}}) : "";
211 my $output = " " x 10240; $output = ""; # Preallocate 10kB, and reset length to 0
212 $cmd{'got'} = \$output;
213 $cmd{'job'} = start \@cmdline, '<', \$input, '>&', \$output, timeout($cmd{'timeout'});
215 if ( $cmd{'background'} ) {
216 # Just enqueue the job. It will be dealed with at the end
217 push @bg_cmds, \%cmd;
219 # Deal with its ending conditions right away
220 analyze_result( \%cmd );
225 my %cmd = %{ $_[0] };
228 finish( $cmd{'job'} );
231 if ($@ =~ /timeout/) {
232 $cmd{'job'}->kill_kill;
233 $cmd{'timeouted'} = 1;
234 } elsif ($@ =~ /^ack / and $@ =~ /pipe/) {
235 print STDERR "Tesh: Broken pipe (ignored).\n";
237 die $@; # Don't know what it is, so let it go.
240 $cmd{'timeouted'} ||= 0;
242 my $gotret = $cmd{'gotret'} = exit_status($?);
246 if ( defined( $cmd{'expect'} ) and ( $cmd{'expect'} ne "" ) ) {
247 $wantret = "got signal $cmd{'expect'}";
249 $wantret = "returned code " . ( defined( $cmd{'return'} ) ? $cmd{'return'} : 0 );
252 # pop all output from executing child
254 map { print "GOT: $_\n" } ${$cmd{'got'}} if $opts{'debug'};
255 foreach my $got ( split("\n", ${$cmd{'got'}}) ) {
258 print $diff_tool_tmp_fh "> $got\n" if ($diff_tool);
260 unless ( $enable_coverage and $got =~ /^profiling:/ ) {
265 if ( $cmd{'sort'} ) {
267 # Save the unsorted observed output to report it on error.
268 map { push @{ $cmd{'unsorted got'} }, $_ } @got;
271 substr( $a, 0, $sort_prefix ) cmp substr( $b, 0, $sort_prefix );
274 if ( $sort_prefix > 0 ) {
275 @got = sort mysort @got;
279 while ( @got and $got[0] eq "" ) {
283 # Sort the expected output to make it easier to write for humans
284 if ( defined( $cmd{'out'} ) ) {
285 if ( $sort_prefix > 0 ) {
286 @{ $cmd{'out'} } = sort mysort @{ $cmd{'out'} };
288 @{ $cmd{'out'} } = sort @{ $cmd{'out'} };
290 while ( @{ $cmd{'out'} } and ${ $cmd{'out'} }[0] eq "" ) {
291 shift @{ $cmd{'out'} };
296 # Did we timeout ? If yes, handle it. If not, kill the forked process.
298 if ( $cmd{'timeouted'} ) {
299 $gotret = "timeout after $cmd{'timeout'} sec";
302 print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
304 if ( $gotret ne $wantret ) {
306 my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
308 $msg = $msg . "Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";
309 map { $msg .= "|| $_\n" } @got;
311 $msg .= "<$cmd{'file'}:$cmd{'line'}> No output so far.\n";
317 # Check the result of execution
320 if ( defined( $cmd{'output display'} ) ) {
321 print "[Tesh/INFO] Here is the (ignored) command output:\n";
322 map { print "||$_\n" } @got;
323 } elsif ( defined( $cmd{'output ignore'} ) ) {
324 print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n";
326 $diff = build_diff( \@{ $cmd{'out'} }, \@got );
328 if ( length $diff ) {
329 print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch" . ( $cmd{'sort'} ? " (even after sorting)" : "" ) . ":\n";
330 map { print "$_\n" } split( /\n/, $diff );
331 if ( $cmd{'sort'} ) {
332 print "WARNING: Both the observed output and expected output were sorted as requested.\n";
333 print "WARNING: Output were only sorted using the $sort_prefix first chars.\n"
334 if ( $sort_prefix > 0 );
335 print "WARNING: Use <! output sort 19> to sort by simulated date and process ID only.\n";
337 # print "----8<--------------- Begin of unprocessed observed output (as it should appear in file):\n";
338 # map {print "> $_\n"} @{$cmd{'unsorted got'}};
339 # print "--------------->8---- End of the unprocessed observed output.\n";
342 print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
348 my $infh; # The file descriptor from which we should read the teshfile
349 if ( $tesh_file eq "(stdin)" ) {
352 open $infh, $tesh_file
353 or die "[Tesh/CRITICAL] Unable to open $tesh_file: $!\n";
356 my %cmd; # everything about the next command to run
358 LINE: while ( defined( my $line = <$infh> ) and not $error ) {
363 print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
366 # deal with line continuations
367 while ( $line =~ /^(.*?)\\$/ ) {
369 die "[TESH/CRITICAL] Continued line at end of file\n"
370 unless defined($next);
373 print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
377 # Push delayed commands on empty lines
378 unless ( $line =~ m/^(.)(.*)$/ ) {
379 if ( defined( $cmd{'cmd'} ) ) {
383 print $diff_tool_tmp_fh "$line\n" if ($diff_tool);
387 my ( $cmd, $arg ) = ( $1, $2 );
388 print $diff_tool_tmp_fh "$line\n" if ( $diff_tool and $cmd ne '>' );
393 # handle the commands
394 if ( $cmd =~ /^#/ ) { # comment
395 } elsif ( $cmd eq '>' ) { # expected result line
396 print "[TESH/debug] push expected result\n" if $opts{'debug'};
397 push @{ $cmd{'out'} }, $arg;
399 } elsif ( $cmd eq '<' ) { # provided input
400 print "[TESH/debug] push provided input\n" if $opts{'debug'};
401 push @{ $cmd{'in'} }, $arg;
403 } elsif ( $cmd eq 'p' ) { # comment
404 print "[$tesh_name:$line_num] $arg\n";
406 } elsif ( $cmd eq '$' ) { # Command
407 # if we have something buffered, run it now
408 if ( defined( $cmd{'cmd'} ) ) {
412 if ( $arg =~ /^\s*mkfile / ) { # "mkfile" command line
413 die "[TESH/CRITICAL] Output expected from mkfile command!\n"
414 if scalar @{ cmd { 'out' } };
417 $cmd{'arg'} =~ s/\s*mkfile //;
421 } elsif ( $arg =~ /^\s*cd / ) {
422 die "[TESH/CRITICAL] Input provided to cd command!\n"
423 if scalar @{ cmd { 'in' } };
424 die "[TESH/CRITICAL] Output expected from cd command!\n"
425 if scalar @{ cmd { 'out' } };
431 } else { # regular command
433 $cmd{'file'} = $tesh_file;
434 $cmd{'line'} = $line_num;
436 } elsif ( $cmd eq '&' ) { # background command line
438 if ( defined( $cmd{'cmd'} ) ) {
442 $cmd{'background'} = 1;
444 $cmd{'file'} = $tesh_file;
445 $cmd{'line'} = $line_num;
447 } elsif ( $line =~ /^!\s*output sort/ ) { #output sort
448 if ( defined( $cmd{'cmd'} ) ) {
453 if ( $line =~ /^!\s*output sort\s+(\d+)/ ) {
456 } elsif ( $line =~ /^!\s*output ignore/ ) { #output ignore
457 if ( defined( $cmd{'cmd'} ) ) {
461 $cmd{'output ignore'} = 1;
462 } elsif ( $line =~ /^!\s*output display/ ) { #output display
463 if ( defined( $cmd{'cmd'} ) ) {
467 $cmd{'output display'} = 1;
468 } elsif ( $line =~ /^!\s*expect signal (\w*)/ ) { #expect signal SIGABRT
469 if ( defined( $cmd{'cmd'} ) ) {
473 $cmd{'expect'} = "$1";
474 } elsif ( $line =~ /^!\s*expect return/ ) { #expect return
475 if ( defined( $cmd{'cmd'} ) ) {
479 $line =~ s/^! expect return //g;
481 $cmd{'return'} = $line;
482 } elsif ( $line =~ /^!\s*setenv/ ) { #setenv
483 if ( defined( $cmd{'cmd'} ) ) {
487 $line =~ s/^! setenv //g;
490 } elsif ( $line =~ /^!\s*timeout/ ) { #timeout
491 if ( defined( $cmd{'cmd'} ) ) {
495 $line =~ s/^! timeout //;
497 $cmd{'timeout'} = $line;
499 die "[TESH/CRITICAL] parse error: $line\n";
502 kill( 'KILL', $forked );
507 # We're done reading the input file
508 close $infh unless ( $tesh_file eq "(stdin)" );
510 # Deal with last command
511 if ( defined( $cmd{'cmd'} ) ) {
517 kill( 'KILL', $forked );
523 analyze_result( \%test );
527 close $diff_tool_tmp_fh;
528 system("$diff_tool $diff_tool_tmp_filename $tesh_file");
529 unlink $diff_tool_tmp_filename;
534 } elsif ( $tesh_file eq "(stdin)" ) {
535 print "Test suite from stdin OK\n";
537 print "Test suite `$tesh_name' OK\n";
541 #### Helper functions
546 my $diff = Diff->new(@_);
548 $diff->Base(1); # Return line numbers, not indices
549 my $chunk_count = $diff->Next(-1); # Compute the amount of chuncks
550 return "" if ( $chunk_count == 1 && $diff->Same() );
552 while ( $diff->Next() ) {
553 my @same = $diff->Same();
554 if ( $diff->Same() ) {
555 if ( $diff->Next(0) > 1 ) { # not first chunk: print 2 first lines
556 $res .= ' ' . $same[0] . "\n";
557 $res .= ' ' . $same[1] . "\n" if ( scalar @same > 1 );
559 $res .= "...\n" if ( scalar @same > 2 );
561 # $res .= $diff->Next(0)."/$chunk_count\n";
562 if ( $diff->Next(0) < $chunk_count ) { # not last chunk: print 2 last lines
563 $res .= ' ' . $same[ scalar @same - 2 ] . "\n"
564 if ( scalar @same > 1 );
565 $res .= ' ' . $same[ scalar @same - 1 ] . "\n";
568 next if $diff->Same();
569 map { $res .= "- $_\n" } $diff->Items(1);
570 map { $res .= "+ $_\n" } $diff->Items(2);
575 # Helper function replacing any occurence of variable '$name' by its '$value'
576 # As in Bash, ${$value:=BLABLA} is rewritten to $value if set or to BLABLA if $value is not set
578 my ( $text, $name, $value ) = @_;
580 $text =~ s/\${$name(?::[=-][^}]*)?}/$value/g;
581 $text =~ s/\$$name(\W|$)/$value$1/g;
583 $text =~ s/\${$name:=([^}]*)}/$1/g;
584 $text =~ s/\${$name}//g;
585 $text =~ s/\$$name(\W|$)/$1/g;
590 ################################ The possible commands ################################
593 my %cmd = %{ $_[0] };
594 my $file = $cmd{'arg'};
595 print STDERR "[Tesh/INFO] mkfile $file. Ctn: >>".join( '\n', @{ $cmd{'in'} })."<<\n"
599 open( FILE, ">$file" )
600 or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
601 print FILE join( "\n", @{ $cmd{'in'} } );
602 print FILE "\n" if ( scalar @{ $cmd{'in'} } > 0 );
606 # Command CD. Just change to the provided directory
608 my $directory = shift;
610 if ( -e $directory && -d $directory ) {
612 print "[Tesh/INFO] change directory to $directory\n";
614 } elsif ( -e $directory ) {
615 print "Cannot change directory to '$directory': it is not a directory\n";
617 print "Chdir to $directory failed: No such file or directory\n";
619 if ( $failure == 1 ) {
620 print "Test suite `$tesh_file': NOK (system error)\n";
625 # Command setenv. Gets "variable=content", and update the environment accordingly
628 if ( $arg =~ /^(.*)=(.*)$/ ) {
629 my ( $var, $ctn ) = ( $1, $2 );
630 print "[Tesh/INFO] setenv $var=$ctn\n";
631 $environ{$var} = $ctn;
634 die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$arg'\n";