Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test STDERR with Test::More?

Tags:

file-io

perl

dup

I am writing some tests using Test::More, and one of the functions I'm testing prints to STDERR. I'd like to test the output to STDERR, but am a little unsure how to do this. I know I'm close. This works:

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");

This prints out:

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

However, I don't want to close STDERR. I merely want to dup it.

I've tried this:

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");

But, $error_string is blank.

What am I doing wrong?

like image 247
David W. Avatar asked Aug 20 '13 18:08

David W.


3 Answers

For me, open STDERR, ">&", $error_fh (along with open STDERR, ">&" . fileno($error_fh)) does not return a true value. I think the >& mode might be a pretty direct syntactic sugar for a dup system call, which wouldn't work on a pseudo-filehandle like $error_fh.

How about localizing STDERR?

{
    local *STDERR = *$error_fh;
    say STDERR "something";
}
# STDERR restored
like image 158
mob Avatar answered Nov 11 '22 09:11

mob


Test::Output can do it, and it now uses Capture::Tiny to catch the edge cases.

like image 6
brian d foy Avatar answered Nov 11 '22 09:11

brian d foy


#  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.
"
like image 2
Oesor Avatar answered Nov 11 '22 08:11

Oesor