【问题标题】:How can I test STDERR with Test::More?如何使用 Test::More 测试 STDERR?
【发布时间】:2013-08-22 22:59:21
【问题描述】:

我正在使用Test::More 编写一些测试,我正在测试的功能之一打印到STDERR。我想测试输出到STDERR,但我有点不确定如何做到这一点。我知道我很接近了。这有效:

use strict;
use warnings;
use feature qw(say);

close STDERR;
open STDERR, ">", \my $error_string;

say STDERR "This is my message";
say qq(The \$error_string is equal to "$error_string");

打印出来:

The $error_string is equal to "This is my message
"

但是,我不想关闭 STDERR。我只是想复制它。

我试过了:

use strict;
use warnings;
use feature qw(say);

open my $error_fh, ">", my $error_string;
open STDERR, ">&", $error_fh;

say STDERR "This is my message";
close $error_fh;
say qq(The \$error_string is equal to "$error_string");

但是,$error_string 是空白的。

我做错了什么?

【问题讨论】:

    标签: perl file-io dup


    【解决方案1】:

    对我来说,open STDERR, ">&", $error_fh(连同open STDERR, ">&" . fileno($error_fh))不会返回真值。我认为>& 模式可能是dup 系统调用的一个非常直接的语法糖,它不适用于像$error_fh 这样的伪文件句柄。

    如何本地化STDERR?

    {
        local *STDERR = *$error_fh;
        say STDERR "something";
    }
    # STDERR restored
    

    【讨论】:

    • 当。我以为我打开了use autodie;。当我添加它时,我得到Can't open 'GLOB(0x7fcb82829808)' with mode '>&': 'Bad file descriptor' at ./test.pl line 11。本地化 STDERR 应该可以解决问题。
    【解决方案2】:

    Test::Output 可以做到,现在它使用Capture::Tiny 来捕捉边缘情况。

    【讨论】:

      【解决方案3】:
      #  perl -MPerlIO::tee -MData::Printer -e 'my $output; STDERR->push_layer(tee=> \$output); warn "Danger, Will Robinson!"; p($output);'
      Danger, Will Robinson! at -e line 1.
      "Danger, Will Robinson! at -e line 1.
      "
      

      【讨论】:

        猜你喜欢
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-05-09
        • 1970-01-01
        • 2015-11-01
        • 2020-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多