When parsing multipart bodies, temporary files are created to store any
uploaded files. You must delete these temporary files yourself after
-processing them.
+processing them, or set $body->cleanup(1) to automatically delete them
+at DESTROY-time.
=head1 METHODS
my $body = $TYPES->{ $type || 'application/octet-stream' };
my $self = {
+ cleanup => 0,
buffer => '',
chunk_buffer => '',
body => undef,
return $self->init;
}
+sub DESTROY {
+ my $self = shift;
+
+ if ( $self->{cleanup} ) {
+ my @temps = ();
+ for my $upload ( values %{ $self->{upload} } ) {
+ push @temps, map { $_->{tempname} || () }
+ ( ref $upload eq 'ARRAY' ? @{$upload} : $upload );
+ }
+
+ unlink map { $_ } grep { -e $_ } @temps;
+ }
+}
+
=item add
Add string to internal buffer. Will call spin unless done. returns
return shift->{chunked};
}
+=item cleanup
+
+Set to 1 to enable automatic deletion of temporary files at DESTROY-time.
+
+=cut
+
+sub cleanup {
+ my $self = shift;
+ $self->{cleanup} = shift if @_;
+ return $self->{cleanup};
+}
+
=item content_length
Returns the content-length for the body data if known.
use strict;
use warnings;
-use Test::More tests => 102;
+use Test::More tests => 140;
+use Test::Deep;
use Cwd;
use HTTP::Body;
$body->add($buffer);
}
+ # Tests >= 10 use auto-cleanup
+ if ( $i >= 10 ) {
+ $body->cleanup(1);
+ }
+
# Save tempnames for later deletion
my @temps;
for ( ( ref($value) eq 'ARRAY' ) ? @{$value} : $value ) {
like($_->{tempname}, qr{$regex_tempdir}, "has tmpdir $tempdir");
- push @temps, delete $_->{tempname};
+ push @temps, $_->{tempname};
+ }
+
+ # Tell Test::Deep to ignore tempname values
+ if ( ref $value eq 'ARRAY' ) {
+ for ( @{ $results->{upload}->{$field} } ) {
+ $_->{tempname} = ignore();
+ }
+ }
+ else {
+ $results->{upload}->{$field}->{tempname} = ignore();
}
}
- is_deeply( $body->body, $results->{body}, "$test MultiPart body" );
- is_deeply( $body->param, $results->{param}, "$test MultiPart param" );
- is_deeply( $body->upload, $results->{upload}, "$test MultiPart upload" )
+ cmp_deeply( $body->body, $results->{body}, "$test MultiPart body" );
+ cmp_deeply( $body->param, $results->{param}, "$test MultiPart param" );
+ cmp_deeply( $body->upload, $results->{upload}, "$test MultiPart upload" )
if $results->{upload};
cmp_ok( $body->state, 'eq', 'done', "$test MultiPart state" );
cmp_ok( $body->length, '==', $body->content_length, "$test MultiPart length" );
- # Clean up temp files created
- unlink map { $_ } grep { -e $_ } @temps;
-}
+ if ( $i < 10 ) {
+ # Clean up temp files created
+ unlink map { $_ } grep { -e $_ } @temps;
+ }
+
+ undef $body;
+
+ # Ensure temp files were deleted
+ for my $temp ( @temps ) {
+ ok( !-e $temp, "Temp file $temp was deleted" );
+ }
+}