How can I test STDERR with Test :: More?

I am writing several tests using Test::More , and one of the functions that I am testing is printing to STDERR . I would like to test the result on STDERR , but a little unsure how to do it. I know that I'm near. It 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 produces:

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

However, I do not want to close STDERR. I just want to trick him.

I 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 empty.

What am I doing wrong?

+6
source share
3 answers

For me, open STDERR, ">&", $error_fh (along with open STDERR, ">&" . fileno($error_fh) ) does not return a true value. I think that the mode >& can be quite a direct syntactic sugar for the dup system call, which will not work with a pseudo file descriptor like $error_fh .

What about the localization of STDERR ?

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

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

+6
source
 # 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. " 
+2
source

Source: https://habr.com/ru/post/952144/


All Articles