I have a program that I need to run a large number of times. This program has a nasty bug in it. When you feed it bad data, it just sits there forever instead of providing a helpful error message. Bad Program!
I can't change the program, but I need to call this program inside a loop in my code. So I am using the perl Expect module to skip over the problem cases and continue with the rest of the runs of the program.
The Expect.pm module is capable of managing this process, so I wrote a few little test programs to help me understand how to accomplish this task.
# unreliable.pl - Simulate a program that sometimes just hangs if (rand(10) > 8){ sleep 1 while 1 > 0; } else{ print "--------------------------------\n", "It worked this time, no problems\n", "--------------------------------\n"; }
Expect.pm Test Program One
The following test program runs the unreliable program twenty times.
If the unreliable program takes longer than five seconds, the attempt
to run it is terminated and the test program continues.
# timeout.pl - Expect Test Program use Expect; my $timeout=5; foreach my $i (1..20) { my $exp = Expect->spawn("./unreliable.pl") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout); }
Expect.pm Test Program Two
The next version of the test program adds the feature that
a message is printed for the cases when a timeout occurs.
use Expect; my $timeout=5; foreach my $i (1..20) { my $exp = Expect->spawn("./unreliable.pl") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout, [ timeout => sub { print "Process timed out.\n"; } ] ); }
Expect.pm Test Program Three
The next version of the test program adds a check to see
if the unreliable program prints "It worked"
somewhere in its output. If the test program detects this string,
it prints "Status: OK" after the unreliable program runs.
use Expect; my $timeout=5; foreach my $i (1..20) { my $spawn_ok="not OK"; my $exp = Expect->spawn("./unreliable.pl") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout, [ 'It worked', sub { $spawn_ok = "OK"; exp_continue; } ], [ timeout => sub { print "Process timed out.\n"; } ] ); print "Status: $spawn_ok\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using Expect.pm to Manage an Unreliable Program
by Anonymous Monk on May 29, 2003 at 14:11 UTC | |
by jcpunk (Friar) on May 29, 2003 at 15:18 UTC | |
by jdporter (Paladin) on Dec 27, 2006 at 17:16 UTC |