Perl: Testing an input reader?

末鹿安然 提交于 2019-12-10 20:44:35

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/17432518/perl-testing-an-input-reader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!