36d25ce51fc07b139c4673e5303f9b6753ef62f0
[gitmo/MooseX-Daemonize.git] / t / 20.core.t
1 use strict;
2 use warnings;
3
4 use Test::More 'no_plan';
5 use Test::Fatal;
6 use Test::Moose;
7 use File::Temp qw(tempdir);
8 use File::Spec::Functions;
9
10 my $dir = tempdir( CLEANUP => 1 );
11
12 BEGIN {
13     use_ok('MooseX::Daemonize::Core');
14     use_ok('MooseX::Daemonize::Pid');
15 }
16
17 use constant DEBUG => 0;
18
19 $ENV{MX_DAEMON_STDOUT} = catfile($dir, 'Out.txt');
20 $ENV{MX_DAEMON_STDERR} = catfile($dir, 'Err.txt');
21
22 {
23     package MyFooDaemon;
24     use Moose;
25
26     with 'MooseX::Daemonize::Core';
27
28     has 'daemon_pid' => (is => 'rw', isa => 'MooseX::Daemonize::Pid');
29
30     # capture the PID from the fork
31     around 'daemon_fork' => sub {
32         my $next = shift;
33         my $self = shift;
34         if (my $pid = $self->$next(@_)) {
35             $self->daemon_pid(
36                 MooseX::Daemonize::Pid->new(pid => $pid)
37             );
38         }
39     };
40
41     sub start {
42         my $self = shift;
43         # tell it to ignore zombies ...
44         $self->ignore_zombies( 1 );
45         $self->no_double_fork( 1 );
46         $self->daemonize;
47         return unless $self->is_daemon;
48         # change to our local dir
49         # so that we can debug easier
50         chdir $dir;
51         # make it easy to find with ps
52         $0 = 'test-app';
53         $SIG{INT} = sub {
54             print "Got INT! Oh Noes!";
55             exit;
56         };
57         while (1) {
58             print "Hello from $$\n";
59             sleep(10);
60         }
61         exit;
62     }
63 }
64
65 my $d = MyFooDaemon->new;
66 isa_ok($d, 'MyFooDaemon');
67 does_ok($d, 'MooseX::Daemonize::Core');
68
69 is(
70     exception { $d->start },
71     undef,
72     '... successfully daemonized from (' . $$ . ')',
73 );
74
75 my $p = $d->daemon_pid;
76 isa_ok($p, 'MooseX::Daemonize::Pid');
77
78 ok($p->is_running, '... the daemon process is running (' . $p->pid . ')');
79
80 my $pid = $p->pid;
81 if (DEBUG) {
82     diag `ps $pid`;
83     diag "-------";
84     diag `ps -x | grep test-app`;
85     diag "-------";
86     diag "killing $pid";
87 }
88 kill INT => $p->pid;
89 diag "killed $pid" if DEBUG;
90 sleep(2);
91 if (DEBUG) {
92     diag `ps $pid`;
93     diag "-------";
94     diag `ps -x | grep test-app`;
95 }
96
97 ok(!$p->is_running, '... the daemon process is no longer running (' . $p->pid . ')');
98
99 unlink $ENV{MX_DAEMON_STDOUT};
100 unlink $ENV{MX_DAEMON_STDERR};
101
102