update distar url
[catagits/Catalyst-Runtime.git] / xt / author / http-server.t
1 use strict;
2 use warnings;
3
4 use Test::More tests => 1;
5 use Test::TCP;
6
7 use File::Path;
8 use FindBin;
9 use Net::EmptyPort qw(wait_port empty_port);
10 use Try::Tiny;
11 use Plack::Builder;
12 use lib 't/lib';
13 use MakeTestApp;
14
15 # Run a single test by providing it as the first arg
16 my $single_test = shift;
17
18 my $test_app_dir = make_test_app;
19
20 # spawn the standalone HTTP server
21 my $port = empty_port;
22
23 my $pid = fork;
24 if ($pid) {
25     # parent.
26     print "Waiting for server to start...\n";
27     wait_port_timeout($port, 30);
28 } elsif ($pid == 0) {
29     # child process
30     unshift @INC, "$test_app_dir/lib", "$FindBin::Bin/../../lib";
31     require TestApp;
32
33     my $psgi_app = TestApp->apply_default_middlewares(TestApp->psgi_app);
34     Plack::Loader->auto(port => $port)->run(builder {
35         mount '/test_prefix' => $psgi_app;
36         mount '/' => sub {
37             return [501, ['Content-Type' => 'text/plain'], ['broken tests']];
38         };
39     });
40
41     exit 0;
42 } else {
43     die "fork failed: $!";
44 }
45
46 # run the testsuite against the HTTP server
47 $ENV{CATALYST_SERVER} = "http://localhost:$port/test_prefix";
48
49 chdir '..';
50
51 my $return;
52 if ( $single_test ) {
53     $return = system( "$^X -Ilib/ $single_test" );
54 }
55 else {
56     $return = prove(grep { $_ ne '..' } glob('t/aggregate/live_*.t'));
57 }
58
59 # shut it down
60 kill 'INT', $pid;
61
62 # clean up
63 rmtree "$FindBin::Bin/../../t/tmp" if -d "$FindBin::Bin/../../t/tmp";
64
65 is( $return, 0, 'live tests' );
66
67 # kill 'INT' doesn't exist in Windows, so to prevent child hanging,
68 # this process will need to commit seppuku to clean up the children.
69 if ($^O eq 'MSWin32') {
70     # Furthermore, it needs to do it 'politely' so that TAP doesn't
71     # smell anything 'dubious'.
72     require Win32::Process;  # core in all versions of Win32 Perl
73     Win32::Process::KillProcess($$, $return);
74 }
75
76 sub wait_port_timeout {
77     my ($port, $timeout) = @_;
78
79     wait_port($port, $timeout * 10) and return;
80
81     die "Server did not start within $timeout seconds";
82 }
83
84 sub prove {
85     my (@tests) = @_;
86     if (!(my $pid = fork)) {
87         require TAP::Harness;
88
89         my $harness = TAP::Harness->new({
90             lib => ['lib'],
91         });
92
93         my $aggregator = $harness->runtests(@tests);
94
95         exit $aggregator->has_errors ? 1 : 0;
96     } else {
97         waitpid $pid, 0;
98         return $?;
99     }
100 }