in reply to Examples of Perl testing other languages
I often run commands, then verify the return code, stdout and stderr. Generally, I like to put as much logic as I can in support functions (such as run_cmd_capture below), so the test script itself is short and reads easily. Here is a simple example.
use strict; use warnings; use Test::More tests => 6; sub read_file_contents { my $fname = shift; local $/; open(my $fh, '<', $fname) or die "error: open '$fname': $!\n"; <$fh>; } sub run_cmd_capture { my $cmd = shift; my $tmpfile = "klink-$$.tmp"; my $outstr = `$cmd 2>$tmpfile`; my $rc = $? >> 8; my $errstr = read_file_contents($tmpfile); unlink($tmpfile) or die "error: unlink '$tmpfile': $!\n"; return ($rc, $outstr, $errstr); } my $outcmd = qq|$^X -le "print 'Klink'"|; my ($rc, $outstr, $errstr) = run_cmd_capture($outcmd); cmp_ok( $rc, '==', 0, "command '$outcmd' rc is zero" ); is( $outstr, "Klink\n", "command '$outcmd' stdout is Klink" ); is( $errstr, "", "command '$outcmd' stderr is empty" ); my $errcmd = qq|$^X -le "print STDERR 'Klink'"|; ($rc, $outstr, $errstr) = run_cmd_capture($errcmd); cmp_ok( $rc, '==', 0, "command '$errcmd' rc is zero" ); is( $outstr, "", "command '$errcmd' stdout is empty" ); is( $errstr, "Klink\n", "command '$errcmd' stderr is Klink" );
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Examples of Perl testing other languages
by jkeenan1 (Deacon) on Nov 20, 2004 at 00:07 UTC |