6d3c53fdf4885f763c5bae84ce7ea51de55e319e
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
1 # work around brain damage in PPerl (yes, it has to be a global)
2 $SIG{__WARN__} = sub {
3   warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
4 } if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
5
6 # the persistent environments run with this flag first to see if
7 # we will run at all (e.g. it will fail if $^X doesn't match)
8 exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
9
10 # Do the override as early as possible so that CORE::bless doesn't get compiled away
11 # We will replace $bless_override only if we are in author mode
12 my $bless_override;
13 BEGIN {
14   $bless_override = sub {
15     CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
16   };
17   *CORE::GLOBAL::bless = sub { goto $bless_override };
18 }
19
20 use strict;
21 use warnings;
22 use Test::More;
23
24 my $TB = Test::More->builder;
25 if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
26   # without this explicit close ->reset below warns
27   close ($TB->$_) for qw/output failure_output/;
28
29   # so done_testing can work
30   $TB->reset;
31
32   # this simulates a subtest
33   $TB->_indent(' ' x 4);
34 }
35
36 use lib qw(t/lib);
37 use DBICTest::RunMode;
38 BEGIN {
39   plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
40     if DBICTest::RunMode->peepeeness;
41 }
42
43 use Scalar::Util qw/refaddr reftype weaken/;
44 use Carp qw/longmess/;
45 use Try::Tiny;
46
47 my $have_test_cycle;
48 BEGIN {
49   require DBIx::Class::Optional::Dependencies;
50   $have_test_cycle = DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks')
51     and import Test::Memory::Cycle;
52 }
53
54 # this is what holds all weakened refs to be checked for leakage
55 my $weak_registry = {};
56
57 # Skip the heavy-duty leak tracing when just doing an install
58 unless (DBICTest::RunMode->is_plain) {
59   # Some modules are known to install singletons on-load
60   # Load them before we swap out $bless_override
61   require DBI;
62   require DBD::SQLite;
63   require Errno;
64   require Class::Struct;
65   require FileHandle;
66   require Hash::Merge;
67   require Storable;
68
69   no warnings qw/redefine once/;
70   no strict qw/refs/;
71
72   # redefine the bless override so that we can catch each and every object created
73   $bless_override = sub {
74
75     my $obj = CORE::bless(
76       $_[0], (@_ > 1) ? $_[1] : do {
77         my ($class, $fn, $line) = caller();
78         fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
79           if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
80         $class;
81       }
82     );
83
84     my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
85       ref $obj,
86       reftype $obj,
87       refaddr $obj,
88     );
89
90     # weaken immediately to avoid weird side effects
91     $weak_registry->{$slot} = { weakref => $obj, strace => longmess() };
92     weaken $weak_registry->{$slot}{weakref};
93
94     return $obj;
95   };
96
97   for my $func (qw/try catch finally/) {
98     my $orig = \&{"Try::Tiny::$func"};
99     *{"Try::Tiny::$func"} = sub (&;@) {
100
101       my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
102
103       $weak_registry->{$slot} = { weakref => $_[0], strace => longmess() };
104       weaken $weak_registry->{$slot}{weakref};
105
106       goto $orig;
107     }
108   }
109 }
110
111 {
112   use_ok ('DBICTest');
113
114   my $schema = DBICTest->init_schema;
115   my $rs = $schema->resultset ('Artist');
116   my $storage = $schema->storage;
117
118   ok ($storage->connected, 'we are connected');
119
120   my $row_obj = $rs->search({}, { rows => 1})->next;  # so that commits/rollbacks work
121   ok ($row_obj, 'row from db');
122
123   # txn_do to invoke more codepaths
124   my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
125
126     my $artist = $rs->create ({
127       name => 'foo artist',
128       cds => [{
129         title => 'foo cd',
130         year => 1984,
131       }],
132     });
133
134     my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
135
136     my $pg_wcount = $rs->page(4)->pager->total_entries (66);
137
138     return ($artist, $pg, $pg_wcount);
139   });
140
141   is ($pager->next_page, 3, 'There is one more page available');
142
143   # based on 66 per 10 pages
144   is ($pager_explicit_count->last_page, 7, 'Correct last page');
145
146   # do some population (invokes some extra codepaths)
147   # also exercise the guard code and the manual txn control
148   {
149     my $guard = $schema->txn_scope_guard;
150     # populate with bindvars
151     $rs->populate([{ name => 'James Bound' }]);
152     $guard->commit;
153
154     $schema->txn_begin;
155     # populate mixed
156     $rs->populate([{ name => 'James Rebound', rank => \ '11'  }]);
157     $schema->txn_commit;
158
159     $schema->txn_begin;
160     # and without bindvars
161     $rs->populate([{ name => \ '"James Unbound"' }]);
162     $schema->txn_rollback;
163   }
164
165   my $base_collection = {
166     resultset => $rs,
167
168     # twice so that we make sure only one H::M object spawned
169     chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
170     chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
171
172     row_object => $row_obj,
173
174     result_source => $rs->result_source,
175
176     result_source_handle => $rs->result_source->handle,
177
178     fresh_pager => $rs->page(5)->pager,
179     pager => $pager,
180     pager_explicit_count => $pager_explicit_count,
181
182   };
183
184   %$base_collection = (
185     %$base_collection,
186     refrozen => Storable::dclone( $base_collection ),
187     rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
188     schema => $schema,
189     storage => $storage,
190     sql_maker => $storage->sql_maker,
191     dbh => $storage->_dbh,
192   );
193
194   memory_cycle_ok ($base_collection, 'No cycles in the object collection')
195     if $have_test_cycle;
196
197   for (keys %$base_collection) {
198     $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
199     weaken $weak_registry->{"basic $_"}{weakref};
200   }
201 }
202
203 # check that "phantom-chaining" works - we never lose track of the original $schema
204 # and have access to the entire tree without leaking anything
205 {
206   my $phantom;
207   for (
208     sub { DBICTest->init_schema },
209     sub { shift->source('Artist') },
210     sub { shift->resultset },
211     sub { shift->result_source },
212     sub { shift->schema },
213     sub { shift->resultset('Artist') },
214     sub { shift->find_or_create({ name => 'detachable' }) },
215     sub { shift->result_source },
216     sub { shift->schema },
217     sub { shift->clone },
218     sub { shift->resultset('Artist') },
219     sub { shift->next },
220     sub { shift->result_source },
221     sub { shift->resultset },
222     sub { shift->create({ name => 'detached' }) },
223     sub { shift->update({ name => 'reattached' }) },
224     sub { shift->discard_changes },
225     sub { shift->delete },
226     sub { shift->insert },
227   ) {
228     $phantom = $_->($phantom);
229
230     my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
231       ref $phantom,
232       reftype $phantom,
233       refaddr $phantom,
234     );
235     $weak_registry->{$slot} = $phantom;
236     weaken $weak_registry->{$slot};
237   }
238
239   ok( $phantom->in_storage, 'Properly deleted/reinserted' );
240   is( $phantom->name, 'reattached', 'Still correct name' );
241 }
242
243 # Naturally we have some exceptions
244 my $cleared;
245 for my $slot (keys %$weak_registry) {
246   if ($slot =~ /^\QTest::Builder/) {
247     # T::B 2.0 has result objects and other fancyness
248     delete $weak_registry->{$slot};
249   }
250   elsif ($slot =~ /^\QSQL::Translator/) {
251     # SQLT is a piece of shit, leaks all over
252     delete $weak_registry->{$slot};
253   }
254   elsif ($slot =~ /^\QHash::Merge/) {
255     # only clear one object of a specific behavior - more would indicate trouble
256     delete $weak_registry->{$slot}
257       unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
258   }
259   elsif ($slot =~ /^__TxnScopeGuard__FIXUP__/) {
260     delete $weak_registry->{$slot}
261       if $] > 5.013001 and $] < 5.013008;
262   }
263 }
264
265
266 # FIXME
267 # For reasons I can not yet fully understand the table() god-method (located in
268 # ::ResultSourceProxy::Table) attaches an actual source instance to each class
269 # as virtually *immortal* class-data. 
270 # For now just ignore these instances manually but there got to be a saner way
271 for ( map { $_->result_source_instance } (
272   'DBICTest::BaseResult',
273   map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
274 )) {
275   delete $weak_registry->{$_};
276 }
277
278 # FIXME
279 # same problem goes for the schema - its classdata contains live result source
280 # objects, which to add insult to the injury are *different* instances from the
281 # ones we ignored above
282 for ( values %{DBICTest::Schema->source_registrations || {}} ) {
283   delete $weak_registry->{$_};
284 }
285
286 for my $slot (sort keys %$weak_registry) {
287
288   ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
289     my $diag = '';
290
291     $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
292       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
293
294     if (my $stack = $weak_registry->{$slot}{strace}) {
295       $diag .= "    Reference first seen$stack";
296     }
297
298     diag $diag if $diag;
299   };
300 }
301
302
303 # we got so far without a failure - this is a good thing
304 # now let's try to rerun this script under a "persistent" environment
305 # this is ugly and dirty but we do not yet have a Test::Embedded or
306 # similar
307
308 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
309 my @pperl_term_cmd = @pperl_cmd;
310 splice @pperl_term_cmd, 1, 0, '--kill';
311
312 # scgi is smart and will auto-reap after -t amount of seconds
313 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
314
315 SKIP: {
316   skip 'Test already in a persistent loop', 1
317     if $ENV{DBICTEST_IN_PERSISTENT_ENV};
318
319   skip 'Persistence test disabled on regular installs', 1
320     if DBICTest::RunMode->is_plain;
321
322   skip 'Main test failed - skipping persistent env tests', 1
323     unless $TB->is_passing;
324
325   # set up -I
326   require Config;
327   local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
328
329   local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
330
331   # try with pperl
332   SKIP: {
333     skip 'PPerl persistent environment tests require PPerl', 1
334       unless eval { require PPerl };
335
336     # since PPerl is racy and sucks - just prime the "server"
337     {
338       local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
339       system(@pperl_cmd);
340       sleep 1;
341
342       # see if it actually runs - if not might as well bail now
343       skip "Something is wrong with pperl ($!)", 1
344         if system(@pperl_cmd);
345     }
346
347     for (1,2,3) {
348       system(@pperl_cmd);
349       ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
350     }
351
352     ok (! system (@pperl_term_cmd), 'killed pperl instance');
353   }
354
355   # try with speedy-cgi
356   SKIP: {
357     skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
358       unless eval { require CGI::SpeedyCGI };
359
360     {
361       local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
362       skip "Something is wrong with speedy ($!)", 1
363         if system(@scgi_cmd);
364       sleep 1;
365     }
366
367     for (1,2,3) {
368       system(@scgi_cmd);
369       ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
370     }
371   }
372 }
373
374 done_testing;
375
376 # just an extra precaution in case we blew away from the SKIP - since there are no
377 # PID files to go by (man does pperl really suck :(
378 END {
379   unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
380     close STDOUT;
381     close STDERR;
382     local $?; # otherwise test will inherit $? of the system()
383     system (@pperl_term_cmd);
384   }
385 }