3

Is there a way to automatically test using the standard Test etc. modules whether a Perl program is reading input from e.g. STDIN properly? E.g. testing a program that reads two integers from STDIN and prints their sum.

Sai
  • 461
  • 7
  • 25
draeklae
  • 31
  • 1
  • `use Data::Dumper; print Dumper `? – TLP Jul 02 '13 at 17:58
  • First, redirect STDIN to a file, or even a DATA-segment in your test script. Second, verify that your read produced expected values. – DavidO Jul 02 '13 at 18:11
  • Thanks, that's exactly what I wanted to do! Just saw this, but I've eventually managed to figure it out on my own: have the test open a file with test inputs as STDIN; that way, the inputs are automatically piped into program being tested as if they were coming from the command line. – draeklae Jul 03 '13 at 12:01

2 Answers2

5

It's not 100% clear what you mean, I'll asnswer assuming you want to write a test script that tests your main program, which as part of the test needs to have test input data passed via STDIN.

You can easily do that if your program outputs what it reads. You don't need a special test module - simply:

  1. Call your program your're testing via a system call

    • redirect both STDIN and STDOUT of tested program to your test script, using

      • IPC::Open2 module to open both sides via pipes to filehandles,

      • ... OR, build your command to redirect to/from files and read/write the files in the test script

  2. Check STDOUT from tested program that you collected in the last step to make sure correct values are printed.

DVK
  • 126,886
  • 32
  • 213
  • 327
0

If you want to test if STDIN is connected to a terminal, use -t, as in:

if( -t STDIN ){
    print "Input from a terminal\n";
}else{
    print "Input from a file or pipe\n";
}

See http://perldoc.perl.org/perlfunc.html#Alphabetical-Listing-of-Perl-Functions

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17