如何在Perl中伪造STDIN?

时间:2009-07-31 18:01:36

标签: perl unit-testing

我正在测试需要用户输入的组件。如何告诉Test::More使用我预定义的输入,以便我不需要手动输入?

这就是我现在所拥有的:

use strict;
use warnings;
use Test::More;
use TestClass;

    *STDIN = "1\n";
    foreach my $file (@files)
    {

#this constructor asks for user input if it cannot find the file (1 is ignore);
    my $test = TestClass->new( file=> @files );

    isa_ok( $test, 'TestClass');
    }


done_testing;

此代码按Enter键但函数检索0而不是1;

2 个答案:

答案 0 :(得分:17)

如果程序从STDIN读取,则只需将STDIN设置为您希望它的打开文件句柄:

#!perl

use strict;
use warnings;

use Test::More;

*STDIN = *DATA;

my @a = <STDIN>;

is_deeply \@a, ["foo\n", "bar\n", "baz\n"], "can read from the DATA section";

my $fakefile = "1\n2\n3\n";

open my $fh, "<", \$fakefile
    or die "could not open fake file: $!";

*STDIN = $fh;

my @b = <STDIN>;

is_deeply \@b, ["1\n", "2\n", "3\n"], "can read from a fake file";

done_testing; 

__DATA__;
foo
bar
baz

您可能希望详细了解typeglobs中有关perldoc perldata的更多内容以及有关在open文档中将字符串转换为虚假文件的更多信息(查找“自v5.8开始,perl已构建默认使用PerlIO。“)在perldoc perlfunc

答案 1 :(得分:7)

以下最小脚本似乎有效:

#!/usr/bin/perl

package TestClass;
use strict;
use warnings;

sub new {
    my $class = shift;
    return unless <STDIN> eq "1\n";
    bless {} => $class;
}

package main;

use strict;
use warnings;

use Test::More tests => 1;

{
    open my $stdin, '<', \ "1\n"
        or die "Cannot open STDIN to read from string: $!";
    local *STDIN = $stdin;
    my $test = TestClass->new;
    isa_ok( $test, 'TestClass');
}

输出:

C:\Temp> t
1..1
ok 1 - The object isa TestClass