include test for failure mode
[catagits/Catalyst-Runtime.git] / t / optional_http-server.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 BEGIN {
6     plan skip_all => 'set TEST_HTTP to enable this test' unless $ENV{TEST_HTTP};
7 }
8
9 use File::Path;
10 use FindBin;
11 use IPC::Open3;
12 use IO::Socket;
13
14 eval "use Catalyst::Devel 1.0";
15 plan skip_all => 'Catalyst::Devel required' if $@;
16 eval "use File::Copy::Recursive";
17 plan skip_all => 'File::Copy::Recursive required' if $@;
18 plan tests => 1;
19
20 # Run a single test by providing it as the first arg
21 my $single_test = shift;
22
23 my $tmpdir = "$FindBin::Bin/../t/tmp";
24
25 # clean up
26 rmtree $tmpdir if -d $tmpdir;
27
28 # create a TestApp and copy the test libs into it
29 mkdir $tmpdir;
30 chdir $tmpdir;
31 system( $^X, "-I$FindBin::Bin/../lib", "$FindBin::Bin/../script/catalyst.pl", 'TestApp' );
32 chdir "$FindBin::Bin/..";
33 File::Copy::Recursive::dircopy( 't/lib', 't/tmp/TestApp/lib' );
34
35 # remove TestApp's tests
36 rmtree 't/tmp/TestApp/t';
37
38 # spawn the standalone HTTP server
39 my $port = 30000 + int rand(1 + 10000);
40 my $pid = open3( undef, my $server, undef,
41   $^X, "-I$FindBin::Bin/../lib",
42   "$FindBin::Bin/../t/tmp/TestApp/script/testapp_server.pl", '-port', $port )
43     or die "Unable to spawn standalone HTTP server: $!";
44
45 # wait for it to start
46 print "Waiting for server to start...\n";
47 while ( check_port( 'localhost', $port ) != 1 ) {
48     sleep 1;
49 }
50
51 # run the testsuite against the HTTP server
52 $ENV{CATALYST_SERVER} = "http://localhost:$port";
53
54 my $return;
55 if ( $single_test ) {
56     $return = system( "$^X -Ilib/ $single_test" );
57 }
58 else {
59     $return = prove( '-r', '-Ilib/', glob('t/aggregate/live_*.t') );
60 }
61
62 # shut it down
63 kill 'INT', $pid;
64 close $server;
65
66 # clean up
67 rmtree "$FindBin::Bin/../t/tmp" if -d "$FindBin::Bin/../t/tmp";
68
69 is( $return, 0, 'live tests' );
70
71 sub check_port {
72     my ( $host, $port ) = @_;
73
74     my $remote = IO::Socket::INET->new(
75         Proto    => "tcp",
76         PeerAddr => $host,
77         PeerPort => $port
78     );
79     if ($remote) {
80         close $remote;
81         return 1;
82     }
83     else {
84         return 0;
85     }
86 }
87
88 sub prove {
89     if (!(my $pid = fork)) {
90         require App::Prove;
91         my $prove = App::Prove->new;
92         $prove->process_args(@_);
93         exit( $prove->run ? 0 : 1 );
94     } else {
95         waitpid $pid, 0;
96         return $?;
97     }
98 }