代码之家  ›  专栏  ›  技术社区  ›  kthakore

如何在Perl中伪造STDIN?

  •  21
  • kthakore  · 技术社区  · 16 年前

    我正在单元测试一个需要用户输入的组件。我怎么说 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 回复  |  直到 16 年前
        1
  •  17
  •   Chas. Owens    16 年前

    如果程序从 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.0以来,perl默认使用PerlIO构建。”) perldoc perlfunc .

        2
  •  7
  •   Sinan Ünür    16 年前

    #!/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