bce0f8530dd438b2def151b4288f20096b396e24
[catagits/HTTP-Body.git] / t / 04multipart.t
1 #!perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 140;
7 use Test::Deep;
8
9 use Cwd;
10 use HTTP::Body;
11 use File::Spec::Functions;
12 use IO::File;
13 use YAML;
14 use File::Temp qw/ tempdir /;
15
16 my $path = catdir( getcwd(), 't', 'data', 'multipart' );
17
18 for ( my $i = 1; $i <= 13; $i++ ) {
19
20     my $test    = sprintf( "%.3d", $i );
21     my $headers = YAML::LoadFile( catfile( $path, "$test-headers.yml" ) );
22     my $results = YAML::LoadFile( catfile( $path, "$test-results.yml" ) );
23     my $content = IO::File->new( catfile( $path, "$test-content.dat" ) );
24     my $body    = HTTP::Body->new( $headers->{'Content-Type'}, $headers->{'Content-Length'} );
25     my $tempdir = tempdir( 'XXXXXXX', CLEANUP => 1, DIR => File::Spec->tmpdir() );
26     $body->tmpdir($tempdir);
27
28     my $regex_tempdir = quotemeta($tempdir);
29
30     binmode $content, ':raw';
31
32     while ( $content->read( my $buffer, 1024 ) ) {
33         $body->add($buffer);
34     }
35     
36     # Tests >= 10 use auto-cleanup
37     if ( $i >= 10 ) {
38         $body->cleanup(1);
39     }
40     
41     # Save tempnames for later deletion
42     my @temps;
43     
44     for my $field ( keys %{ $body->upload } ) {
45
46         my $value = $body->upload->{$field};
47
48         for ( ( ref($value) eq 'ARRAY' ) ? @{$value} : $value ) {
49             like($_->{tempname}, qr{$regex_tempdir}, "has tmpdir $tempdir");
50             push @temps, $_->{tempname};
51         }
52         
53         # Tell Test::Deep to ignore tempname values
54         if ( ref $value eq 'ARRAY' ) {
55             for ( @{ $results->{upload}->{$field} } ) {
56                 $_->{tempname} = ignore();
57             }
58         }
59         else {
60             $results->{upload}->{$field}->{tempname} = ignore();
61         }
62     }
63
64     cmp_deeply( $body->body, $results->{body}, "$test MultiPart body" );
65     cmp_deeply( $body->param, $results->{param}, "$test MultiPart param" );
66     cmp_deeply( $body->upload, $results->{upload}, "$test MultiPart upload" )
67         if $results->{upload};
68     cmp_ok( $body->state, 'eq', 'done', "$test MultiPart state" );
69     cmp_ok( $body->length, '==', $body->content_length, "$test MultiPart length" );
70     
71     if ( $i < 10 ) {
72         # Clean up temp files created
73         unlink map { $_ } grep { -e $_ } @temps;
74     }
75     
76     undef $body;
77     
78     # Ensure temp files were deleted
79     for my $temp ( @temps ) {
80         ok( !-e $temp, "Temp file $temp was deleted" );
81     }
82