Make http-server.t use Test::TCP
[catagits/Catalyst-Runtime.git] / t / author / http-server.t
1 use strict;
2 use warnings;
3
4 use Test::More tests => 1;
5
6 use File::Path;
7 use FindBin;
8 use Test::TCP;
9 use Try::Tiny;
10
11 use Catalyst::Devel 1.0;
12 use File::Copy::Recursive;
13
14 # Run a single test by providing it as the first arg
15 my $single_test = shift;
16
17 my $tmpdir = "$FindBin::Bin/../../t/tmp";
18
19 # clean up
20 rmtree $tmpdir if -d $tmpdir;
21
22 # create a TestApp and copy the test libs into it
23 mkdir $tmpdir;
24 chdir $tmpdir;
25 system( $^X, "-I$FindBin::Bin/../../lib", "$FindBin::Bin/../../script/catalyst.pl", 'TestApp' );
26 chdir "$FindBin::Bin/..";
27 File::Copy::Recursive::dircopy( '../t/lib', '../t/tmp/TestApp/lib' ) or die;
28
29 # remove TestApp's tests
30 rmtree '../t/tmp/TestApp/t' or die;
31
32 # spawn the standalone HTTP server
33 my $port = empty_port;
34
35 my $pid = fork;
36 if ($pid) {
37     # parent.
38     print "Waiting for server to start...\n";
39     wait_port_timeout($port, 30);
40 } elsif ($pid == 0) {
41     # child process
42     unshift @INC, "$tmpdir/TestApp/lib", "$FindBin::Bin/../../lib";
43     require TestApp;
44
45     my $psgi_app = TestApp->_wrapped_legacy_psgi_app(TestApp->psgi_app);
46     Plack::Loader->auto(port => $port)->run($psgi_app);
47
48     exit 0;
49 } else {
50     die "fork failed: $!";
51 }
52
53 # run the testsuite against the HTTP server
54 $ENV{CATALYST_SERVER} = "http://localhost:$port";
55
56 chdir '..';
57
58 my $return;
59 if ( $single_test ) {
60     $return = system( "$^X -Ilib/ $single_test" );
61 }
62 else {
63     $return = prove(grep { $_ ne '..' } glob('t/aggregate/live_*.t'));
64 }
65
66 # shut it down
67 kill 'INT', $pid;
68
69 # clean up
70 rmtree "$FindBin::Bin/../../t/tmp" if -d "$FindBin::Bin/../../t/tmp";
71
72 is( $return, 0, 'live tests' );
73
74 sub wait_port_timeout {
75     my ($port, $timeout) = @_;
76
77     # wait_port waits for 10 seconds
78     for (1 .. int($timeout / 10)) { # meh, good enough.
79         try { wait_port $port; 1 } and return;
80     }
81
82     die "Server did not start within $timeout seconds";
83 }
84
85 sub prove {
86     my (@tests) = @_;
87     if (!(my $pid = fork)) {
88         require TAP::Harness;
89
90         my $aggr = -e '.aggregating';
91         my $harness = TAP::Harness->new({
92             ($aggr ? (test_args => \@tests) : ()),
93             lib => ['lib'],
94         });
95
96         my $aggregator = $aggr
97             ? $harness->runtests('t/aggregate.t')
98             : $harness->runtests(@tests);
99
100         exit $aggregator->has_errors ? 1 : 0;
101     } else {
102         waitpid $pid, 0;
103         return $?;
104     }
105 }