On Mon, 09 Feb 2004 14:00, Andy Lester wrote;
> > While writing tests for some of my code, I was faced with the issue
> > of capturing what the code sends to STDOUT and STDERR. As I have not
> > found a module to make it easy, I wrote a trivial code to do it. It
> > is used like this:
> I'm not sure what you're actually trying to test. If you're testing
> test modules, look at Test::Builder::Tester.
No, something that ties STDOUT so that code can print to it, and you
can test that the right thing was printed; I've had to do this before,
and ended up not going through the CPAN ropes for this module:
{
package Capture;
sub new {
my $class = shift;
my $self = { stdout => "" };
bless $self, $class;
return $self;
}
sub capture_print {
my $self = shift;
$self->{so} = tie(*STDOUT, __PACKAGE__, \$self->{stdout})
or die "failed to tie STDOUT; $!";
}
sub release_stdout {
my $self = shift;
delete $self->{so};
untie(*STDOUT);
return $self->{stdout};
}
sub TIEHANDLE {
my $class = shift;
my $ref = shift;
return bless({ stdout => $ref }, $class);
}
sub PRINT {
my $self = shift;
${$self->{stdout}} .= join('', map { defined $_?$_:""} @_);
}
sub PRINTF {
my ($self) = shift;
print STDERR "OUCH @_\n";
my ($fmt) = shift;
${$self->{stdout}} .= sprintf($fmt, @_)
if (@_);
}
sub glob {
return \*STDOUT;
}
}
Though, I must say that I prefer his API. The above was really just a
quick hack based on what I'd extracted out of the ePerl code base.
I'd call it something like IO::Capture if I were to CPAN it.
IO::Seize isn't quite right, but "seize" is definitely a good Perlish
name for the function.
Note that php has a built-in function to do just this.
--
Sam Vilain, sam /\T vilain |><>T net, PGP key ID: 0x05B52F13
(include my PGP key ID in personal replies to avoid spam filtering)
Time is an illusion perpetrated by the manufacturers of space.
GRAFFITI