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