use json for serialized data in tests
[catagits/Catalyst-Runtime.git] / t / optional_memleak.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 BEGIN {
6     plan skip_all => 'set TEST_MEMLEAK to enable this test'
7         unless $ENV{TEST_MEMLEAK};
8 }
9
10 use FindBin;
11 use lib "$FindBin::Bin/lib";
12 use Catalyst::Test 'TestApp';
13
14 eval "use Proc::ProcessTable";
15 plan skip_all => 'Proc::ProcessTable required for this test' if $@;
16
17 eval "use HTTP::Body 0.03";
18 plan skip_all => 'HTTP::Body >= 0.03 required for this test' if $@;
19
20 use JSON::MaybeXS qw(decode_json);
21
22 our $t = Proc::ProcessTable->new( cache_ttys => 1 );
23 our ( $initial, $final ) = ( 0, 0 ); 
24 my $test_data = do {
25   open my $fh, '<:raw', "$FindBin::Bin/optional_stress.json" or die "$!";
26   local $/;
27   <$fh>;
28 };
29
30 our $tests = decode_json($test_data);
31
32 my $total_tests = 0;
33
34 # let the user specify a single uri to test
35 my $user_test = shift;
36 if ( $user_test ) {
37     plan tests => 1;
38     run_test( $user_test );
39 }
40 # otherwise, run all tests
41 else {
42     map { $total_tests += scalar @{ $tests->{$_} } } keys %{$tests};
43     plan tests => $total_tests;
44     
45     foreach my $test_group ( keys %{$tests} ) {
46         foreach my $test ( @{ $tests->{$test_group} } ) {
47             run_test( $test );
48         }
49     }
50 }
51
52 sub run_test {
53     my $uri = shift || die 'No URI given for test';
54     
55     print "TESTING $uri\n";
56     
57     # make a few requests to set initial memory size
58     for ( 1 .. 3 ) {
59         request( $uri );
60     }
61     
62     $initial = size_of($$);
63     print "Initial Size: $initial\n";
64     
65     for ( 1 .. 500 ) {
66         request( $uri );
67     }
68     
69     $final = size_of($$);
70     print "Final Size:   $final\n";
71     
72     if ( $final > $initial ) {
73         print "Leaked:       " . ($final - $initial) . "K\n";
74     }
75     
76     is( $final, $initial, "'$uri' memory is not leaking" );
77 }
78
79 sub size_of {
80     my $pid = shift;
81     
82     foreach my $p ( @{ $t->table } ) {
83         if ( $p->pid == $pid ) {
84             return $p->rss;
85         }
86     }
87     
88     die "Pid $pid not found?";
89 }
90