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" );

In reply to Re: Examples of Perl testing other languages by eyepopslikeamosquito
in thread Examples of Perl testing other languages by jkeenan1

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.