Fix embarrassing leak triggered on calling new_related on an uninserted object
[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 use DBIx::Class;
39 use B 'svref_2object';
40 BEGIN {
41   plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
42     if DBIx::Class::_ENV_::PEEPEENESS;
43 }
44
45 use Scalar::Util qw/refaddr reftype weaken/;
46
47 # this is what holds all weakened refs to be checked for leakage
48 my $weak_registry = {};
49
50 # whether or to invoke IC::DT
51 my $has_dt;
52
53 # Skip the heavy-duty leak tracing when just doing an install
54 unless (DBICTest::RunMode->is_plain) {
55
56   # have our own little stack maker - Carp infloops due to the bless override
57   my $trace = sub {
58     my $depth = 1;
59     my (@stack, @frame);
60
61     while (@frame = caller($depth++)) {
62       push @stack, [@frame[3,1,2]];
63     }
64
65     $stack[0][0] = '';
66     return join "\tinvoked as ", map { sprintf ("%s at %s line %d\n", @$_ ) } @stack;
67   };
68
69   # redefine the bless override so that we can catch each and every object created
70   no warnings qw/redefine once/;
71   no strict qw/refs/;
72
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 => $trace->() };
92     weaken $weak_registry->{$slot}{weakref};
93
94     return $obj;
95   };
96
97   require Try::Tiny;
98   for my $func (qw/try catch finally/) {
99     my $orig = \&{"Try::Tiny::$func"};
100     *{"Try::Tiny::$func"} = sub (&;@) {
101
102       my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
103
104       $weak_registry->{$slot} = { weakref => $_[0], strace => $trace->() };
105       weaken $weak_registry->{$slot}{weakref};
106
107       goto $orig;
108     }
109   }
110
111   # Some modules are known to install singletons on-load
112   # Load them and empty the registry
113
114   # this loads the DT armada
115   $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
116
117   require Errno;
118   require DBI;
119   require DBD::SQLite;
120   require FileHandle;
121
122   %$weak_registry = ();
123 }
124
125 my @compose_ns_classes;
126 {
127   use_ok ('DBICTest');
128
129   my $schema = DBICTest->init_schema;
130   my $rs = $schema->resultset ('Artist');
131   my $storage = $schema->storage;
132
133   @compose_ns_classes = map { "DBICTest::${_}" } keys %{$schema->source_registrations};
134
135   ok ($storage->connected, 'we are connected');
136
137   my $row_obj = $rs->search({}, { rows => 1})->next;  # so that commits/rollbacks work
138   ok ($row_obj, 'row from db');
139
140   # txn_do to invoke more codepaths
141   my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
142
143     my $artist = $rs->create ({
144       name => 'foo artist',
145       cds => [{
146         title => 'foo cd',
147         year => 1984,
148       }],
149     });
150
151     my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
152
153     my $pg_wcount = $rs->page(4)->pager->total_entries (66);
154
155     return ($artist, $pg, $pg_wcount);
156   });
157
158   is ($pager->next_page, 3, 'There is one more page available');
159
160   # based on 66 per 10 pages
161   is ($pager_explicit_count->last_page, 7, 'Correct last page');
162
163   # do some population (invokes some extra codepaths)
164   # also exercise the guard code and the manual txn control
165   {
166     my $guard = $schema->txn_scope_guard;
167     # populate with bindvars
168     $rs->populate([{ name => 'James Bound' }]);
169     $guard->commit;
170
171     $schema->txn_begin;
172     # populate mixed
173     $rs->populate([{ name => 'James Rebound', rank => \ '11'  }]);
174     $schema->txn_commit;
175
176     $schema->txn_begin;
177     # and without bindvars
178     $rs->populate([{ name => \ '"James Unbound"' }]);
179     $schema->txn_rollback;
180   }
181
182   # prefetching
183   my $cds_rs = $schema->resultset('CD');
184   my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
185   my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
186   my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
187
188   # implicit pref
189   my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
190
191   # get_column
192   my $getcol_rs = $cds_rs->get_column('me.cdid');
193   my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
194
195   # fire the column getters
196   my @throwaway = $pref_getcol_rs->all;
197
198   my $base_collection = {
199     resultset => $rs,
200
201     pref_precursor => $cds_rs,
202
203     pref_rs_single => $cds_with_artist,
204     pref_rs_multi => $cds_with_tracks,
205     pref_rs_nested => $cds_with_stuff,
206
207     pref_rs_implicit => $cds_with_impl_artist,
208
209     pref_row_single => $cds_with_artist->next,
210     pref_row_multi => $cds_with_tracks->next,
211     pref_row_nested => $cds_with_stuff->next,
212
213     # even though this does not leak Storable croaks on it :(((
214     #pref_row_implicit => $cds_with_impl_artist->next,
215
216     get_column_rs_plain => $getcol_rs,
217     get_column_rs_pref => $pref_getcol_rs,
218
219     # twice so that we make sure only one H::M object spawned
220     chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
221     chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
222
223     row_object => $row_obj,
224
225     result_source => $rs->result_source,
226
227     result_source_handle => $rs->result_source->handle,
228
229     pager_explicit_count => $pager_explicit_count,
230   };
231
232   require Storable;
233   %$base_collection = (
234     %$base_collection,
235     refrozen => Storable::dclone( $base_collection ),
236     rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
237     pref_row_implicit => $cds_with_impl_artist->next,
238     schema => $schema,
239     storage => $storage,
240     sql_maker => $storage->sql_maker,
241     dbh => $storage->_dbh,
242     fresh_pager => $rs->page(5)->pager,
243     pager => $pager,
244   );
245
246   if ($has_dt) {
247     my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
248
249     my $now = DateTime->now;
250     for (1..5) {
251       $base_collection->{"icdt_row_$_"} = $rs->create({
252         created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
253         starts_at => $now->clone->add(days => $_),
254       });
255     }
256
257     # re-search
258     my @dummy = $rs->all;
259   }
260
261   # dbh's are created in XS space, so pull them separately
262   for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
263     $base_collection->{"DBI handle $_"} = $_;
264   }
265
266   if ( DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks') ) {
267     Test::Memory::Cycle::memory_cycle_ok ($base_collection, 'No cycles in the object collection')
268   }
269
270   for (keys %$base_collection) {
271     $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
272     weaken $weak_registry->{"basic $_"}{weakref};
273   }
274 }
275
276 # check that "phantom-chaining" works - we never lose track of the original $schema
277 # and have access to the entire tree without leaking anything
278 {
279   my $phantom;
280   for (
281     sub { DBICTest->init_schema },
282     sub { shift->source('Artist') },
283     sub { shift->resultset },
284     sub { shift->result_source },
285     sub { shift->schema },
286     sub { shift->resultset('Artist') },
287     sub { shift->find_or_create({ name => 'detachable' }) },
288     sub { shift->result_source },
289     sub { shift->schema },
290     sub { shift->clone },
291     sub { shift->resultset('Artist') },
292     sub { shift->next },
293     sub { shift->result_source },
294     sub { shift->resultset },
295     sub { shift->create({ name => 'detached' }) },
296     sub { shift->update({ name => 'reattached' }) },
297     sub { shift->discard_changes },
298     sub { shift->delete },
299     sub { shift->insert },
300   ) {
301     $phantom = $_->($phantom);
302
303     my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
304       ref $phantom,
305       reftype $phantom,
306       refaddr $phantom,
307     );
308
309     $weak_registry->{$slot} = $phantom;
310     weaken $weak_registry->{$slot};
311   }
312
313   ok( $phantom->in_storage, 'Properly deleted/reinserted' );
314   is( $phantom->name, 'reattached', 'Still correct name' );
315 }
316
317 # Naturally we have some exceptions
318 my $cleared;
319 for my $slot (keys %$weak_registry) {
320   if ($slot =~ /^Test::Builder/) {
321     # T::B 2.0 has result objects and other fancyness
322     delete $weak_registry->{$slot};
323   }
324   elsif ($slot =~ /^SQL::Translator/) {
325     # SQLT is a piece of shit, leaks all over
326     delete $weak_registry->{$slot};
327   }
328   elsif ($slot =~ /^Hash::Merge/) {
329     # only clear one object of a specific behavior - more would indicate trouble
330     delete $weak_registry->{$slot}
331       unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
332   }
333   elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
334     delete $weak_registry->{$slot}
335   }
336   elsif ($slot =~ /^DateTime::TimeZone/) {
337     # DT is going through a refactor it seems - let it leak zones for now
338     delete $weak_registry->{$slot};
339   }
340 }
341
342 # every result class has a result source instance as classdata
343 # make sure these are all present and distinct before ignoring
344 # (distinct means only 1 reference)
345 for my $rs_class (
346   'DBICTest::BaseResult',
347   @compose_ns_classes,
348   map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
349 ) {
350   # need to store the SVref and examine it separately, to push the rsrc instance off the pad
351   my $SV = svref_2object($rs_class->result_source_instance);
352   is( $SV->REFCNT, 1, "Source instance of $rs_class referenced exactly once" );
353
354   # ignore it
355   delete $weak_registry->{$rs_class->result_source_instance};
356 }
357
358 # Schema classes also hold sources, but these are clones, since
359 # each source contains the schema (or schema class name in this case)
360 # Hence the clone so that the same source can be registered with
361 # multiple schemas
362 for my $moniker ( keys %{DBICTest::Schema->source_registrations || {}} ) {
363
364   my $SV = svref_2object(DBICTest::Schema->source($moniker));
365   is( $SV->REFCNT, 1, "Source instance registered under DBICTest::Schema as $moniker referenced exactly once" );
366
367   delete $weak_registry->{DBICTest::Schema->source($moniker)};
368 }
369
370 for my $slot (sort keys %$weak_registry) {
371
372   ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
373     my $diag = '';
374
375     $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
376       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
377
378     if (my $stack = $weak_registry->{$slot}{strace}) {
379       $diag .= "    Reference first seen$stack";
380     }
381
382     diag $diag if $diag;
383   };
384 }
385
386 # we got so far without a failure - this is a good thing
387 # now let's try to rerun this script under a "persistent" environment
388 # this is ugly and dirty but we do not yet have a Test::Embedded or
389 # similar
390
391 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
392 my @pperl_term_cmd = @pperl_cmd;
393 splice @pperl_term_cmd, 1, 0, '--kill';
394
395 # scgi is smart and will auto-reap after -t amount of seconds
396 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
397
398 SKIP: {
399   skip 'Test already in a persistent loop', 1
400     if $ENV{DBICTEST_IN_PERSISTENT_ENV};
401
402   skip 'Persistence test disabled on regular installs', 1
403     if DBICTest::RunMode->is_plain;
404
405   skip 'Main test failed - skipping persistent env tests', 1
406     unless $TB->is_passing;
407
408   # set up -I
409   require Config;
410   local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
411
412   local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
413
414   # try with pperl
415   SKIP: {
416     skip 'PPerl persistent environment tests require PPerl', 1
417       unless eval { require PPerl };
418
419     # since PPerl is racy and sucks - just prime the "server"
420     {
421       local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
422       system(@pperl_cmd);
423       sleep 1;
424
425       # see if it actually runs - if not might as well bail now
426       skip "Something is wrong with pperl ($!)", 1
427         if system(@pperl_cmd);
428     }
429
430     for (1,2,3) {
431       system(@pperl_cmd);
432       ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
433     }
434
435     ok (! system (@pperl_term_cmd), 'killed pperl instance');
436   }
437
438   # try with speedy-cgi
439   SKIP: {
440     skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
441       unless eval { require CGI::SpeedyCGI };
442
443     {
444       local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
445       skip "Something is wrong with speedy ($!)", 1
446         if system(@scgi_cmd);
447       sleep 1;
448     }
449
450     for (1,2,3) {
451       system(@scgi_cmd);
452       ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
453     }
454   }
455 }
456
457 done_testing;
458
459 # just an extra precaution in case we blew away from the SKIP - since there are no
460 # PID files to go by (man does pperl really suck :(
461 END {
462   unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
463     close STDOUT;
464     close STDERR;
465     local $?; # otherwise test will inherit $? of the system()
466     system (@pperl_term_cmd);
467   }
468 }