1#!perl 2 3use strict; 4use warnings; 5 6use File::Basename; 7use Test::More 0.88; 8use t::Util qw[tmpfile rewind slurp monkey_patch dir_list parse_case 9 set_socket_source sort_headers $CRLF $LF]; 10use HTTP::Tiny; 11use File::Temp qw/tempdir/; 12use File::Spec; 13 14BEGIN { monkey_patch() } 15 16my $tempdir = tempdir( TMPDIR => 1, CLEANUP => 1 ); 17my $tempfile = File::Spec->catfile( $tempdir, "tempfile.txt" ); 18 19my $known_epoch = 760233600; 20my $day = 24*3600; 21 22my %timestamp = ( 23 'modified.txt' => $known_epoch - 2 * $day, 24 'not-modified.txt' => $known_epoch - 2 * $day, 25); 26 27for my $file ( dir_list("t/cases", qr/^mirror/ ) ) { 28 1 while unlink $tempfile; 29 my $data = do { local (@ARGV,$/) = $file; <> }; 30 my ($params, $expect_req, $give_res) = split /--+\n/, $data; 31 # cleanup source data 32 my $version = HTTP::Tiny->VERSION || 0; 33 $expect_req =~ s{VERSION}{$version}; 34 s{\n}{$CRLF}g for ($expect_req, $give_res); 35 36 # figure out what request to make 37 my $case = parse_case($params); 38 my $url = $case->{url}->[0]; 39 my %options; 40 41 my %headers; 42 for my $line ( @{ $case->{headers} } ) { 43 my ($k,$v) = ($line =~ m{^([^:]+): (.*)$}g); 44 $headers{$k} = $v; 45 } 46 $options{headers} = \%headers if %headers; 47 48 # maybe create a file 49 (my $url_basename = $url) =~ s{.*/}{}; 50 if ( my $mtime = $timestamp{$url_basename} ) { 51 open my $fh, ">", $tempfile; 52 close $fh; 53 utime $mtime, $mtime, $tempfile; 54 } 55 56 # setup mocking and test 57 my $res_fh = tmpfile($give_res); 58 my $req_fh = tmpfile(); 59 60 my $http = HTTP::Tiny->new( keep_alive => 0 ); 61 set_socket_source($req_fh, $res_fh); 62 63 my @call_args = %options ? ($url, $tempfile, \%options) : ($url, $tempfile); 64 my $response = $http->mirror(@call_args); 65 66 my $got_req = slurp($req_fh); 67 68 my $label = basename($file); 69 70 is( sort_headers($got_req), sort_headers($expect_req), "$label request" ); 71 72 my ($rc) = $give_res =~ m{\S+\s+(\d+)}g; 73 is( $response->{status}, $rc, "$label response code $rc" ) 74 or diag $response->{content}; 75 76 if ( substr($rc,0,1) eq '2' ) { 77 ok( $response->{success}, "$label success flag true" ); 78 ok( -e $tempfile, "$label file created" ); 79 } 80 elsif ( $rc eq '304' ) { 81 ok( $response->{success}, "$label success flag true" ); 82 is( (stat($tempfile))[9], $timestamp{$url_basename}, 83 "$label file not overwritten" ); 84 } 85 else { 86 ok( ! $response->{success}, "$label success flag false" ); 87 ok( ! -e $tempfile, "$label file not created" ); 88 } 89} 90 91done_testing; 92