Some stylistic test changes in preparation for next commits
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
CommitLineData
66917da3 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)
8exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
9
f05edfd1 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
12my $bless_override;
13BEGIN {
14 $bless_override = sub {
15 CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
16 };
17 *CORE::GLOBAL::bless = sub { goto $bless_override };
18}
19
50261284 20use strict;
21use warnings;
a917fb06 22use Test::More;
d5e5fb4b 23
30c81ba9 24use lib qw(t/lib);
25use DBICTest::RunMode;
cd771d5c 26use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry visit_refs);
27use Scalar::Util qw(weaken blessed reftype);
28use DBIx::Class::_Util qw(hrefaddr sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt);
29BEGIN {
30 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
31 if DBIx::Class::_ENV_::PEEPEENESS;
32}
30c81ba9 33
30c81ba9 34
66917da3 35my $TB = Test::More->builder;
36if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
cd771d5c 37 # without this explicit close TB warns in END after a ->reset
38 close ($TB->$_) for qw(output failure_output todo_output);
66917da3 39
cd771d5c 40 # newer TB does not auto-reopen handles
41 if ( modver_gt_or_eq( 'Test::More', '1.200' ) ) {
42 open ($TB->$_, '>&', *STDERR)
43 for qw( failure_output todo_output );
7be5717e 44 open ($TB->output, '>&', *STDOUT);
45 }
46
47 # so done_testing can work on every persistent pass
48 $TB->reset;
66917da3 49}
50
a8c2c746 51# this is what holds all weakened refs to be checked for leakage
52my $weak_registry = {};
53
6a43bc0c 54# whether or to invoke IC::DT
55my $has_dt;
56
a8c2c746 57# Skip the heavy-duty leak tracing when just doing an install
58unless (DBICTest::RunMode->is_plain) {
f05edfd1 59
eb7aa960 60 # redefine the bless override so that we can catch each and every object created
a8c2c746 61 no warnings qw/redefine once/;
62 no strict qw/refs/;
63
f05edfd1 64 $bless_override = sub {
65
a8c2c746 66 my $obj = CORE::bless(
67 $_[0], (@_ > 1) ? $_[1] : do {
68 my ($class, $fn, $line) = caller();
69 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
70 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
71 $class;
72 }
73 );
74
8d6b1478 75 # unicode is tricky, and now we happen to invoke it early via a
76 # regex in connection()
77 return $obj if (ref $obj) =~ /^utf8/;
78
7be5717e 79 # Test Builder is now making a new object for every pass/fail (que bloat?)
80 # and as such we can't really store any of its objects (since it will
81 # re-populate the registry while checking it, ewwww!)
cd771d5c 82 return $obj if (ref $obj) =~ /^TB2::|^Test::Stream/;
7be5717e 83
5dc4301c 84 # populate immediately to avoid weird side effects
65d35121 85 return populate_weakregistry ($weak_registry, $obj );
a8c2c746 86 };
87
eb7aa960 88 require Try::Tiny;
a8c2c746 89 for my $func (qw/try catch finally/) {
90 my $orig = \&{"Try::Tiny::$func"};
91 *{"Try::Tiny::$func"} = sub (&;@) {
65d35121 92 populate_weakregistry( $weak_registry, $_[0] );
a8c2c746 93 goto $orig;
94 }
95 }
eb7aa960 96
97 # Some modules are known to install singletons on-load
98 # Load them and empty the registry
99
100 # this loads the DT armada
2baba3d9 101 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for([qw( test_rdbms_sqlite icdt )]);
eb7aa960 102
103 require Errno;
104 require DBI;
105 require DBD::SQLite;
106 require FileHandle;
e6ff3658 107 require Moo;
eb7aa960 108
109 %$weak_registry = ();
a8c2c746 110}
111
112{
66917da3 113 use_ok ('DBICTest');
a917fb06 114
a8c2c746 115 my $schema = DBICTest->init_schema;
116 my $rs = $schema->resultset ('Artist');
117 my $storage = $schema->storage;
a917fb06 118
052b8ce2 119 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 120 ok ($row_obj, 'row from db');
121
052b8ce2 122 # txn_do to invoke more codepaths
a8c2c746 123 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
124
9345b14c 125 my $artist = $schema->resultset('Artist')->create ({
a8c2c746 126 name => 'foo artist',
127 cds => [{
128 title => 'foo cd',
129 year => 1984,
187ec69a 130 tracks => [
131 { title => 't1' },
132 { title => 't2' },
133 ],
134 genre => { name => 'mauve' },
a8c2c746 135 }],
136 });
137
138 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
139
140 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
141
142 return ($artist, $pg, $pg_wcount);
143 });
144
9345b14c 145 # more codepaths - error handling in txn_do
146 {
147 eval { $schema->txn_do ( sub {
148 $storage->_dbh->begin_work;
149 fail ('how did we get so far?!');
150 } ) };
151
152 eval { $schema->txn_do ( sub {
153 $schema->txn_do ( sub {
154 die "It's called EXCEPTION";
155 fail ('how did we get so far?!');
156 } );
157 fail ('how did we get so far?!');
158 } ) };
159 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
160 }
161
162 # dbh_do codepath
187ec69a 163 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
164 my $row = $_[0]->schema->resultset('Artist')->new({});
165 my $rs = $_[0]->schema->resultset('Artist')->search({
166 name => $row, # this is deliberately bogus, see FIXME below!
167 });
168 return ($rs, $row);
169 });
170
a8c2c746 171 is ($pager->next_page, 3, 'There is one more page available');
172
173 # based on 66 per 10 pages
174 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 175
052b8ce2 176 # do some population (invokes some extra codepaths)
177 # also exercise the guard code and the manual txn control
178 {
179 my $guard = $schema->txn_scope_guard;
180 # populate with bindvars
181 $rs->populate([{ name => 'James Bound' }]);
182 $guard->commit;
183
184 $schema->txn_begin;
185 # populate mixed
186 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
187 $schema->txn_commit;
188
189 $schema->txn_begin;
190 # and without bindvars
191 $rs->populate([{ name => \ '"James Unbound"' }]);
192 $schema->txn_rollback;
193 }
194
0a03206a 195 # prefetching
196 my $cds_rs = $schema->resultset('CD');
197 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
198 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
199 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
200
201 # implicit pref
202 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
203
204 # get_column
205 my $getcol_rs = $cds_rs->get_column('me.cdid');
206 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
207
a8c2c746 208 my $base_collection = {
a8c2c746 209 resultset => $rs,
307ab4c5 210
0a03206a 211 pref_precursor => $cds_rs,
212
213 pref_rs_single => $cds_with_artist,
214 pref_rs_multi => $cds_with_tracks,
215 pref_rs_nested => $cds_with_stuff,
216
217 pref_rs_implicit => $cds_with_impl_artist,
218
219 pref_row_single => $cds_with_artist->next,
220 pref_row_multi => $cds_with_tracks->next,
221 pref_row_nested => $cds_with_stuff->next,
222
223 # even though this does not leak Storable croaks on it :(((
224 #pref_row_implicit => $cds_with_impl_artist->next,
225
226 get_column_rs_plain => $getcol_rs,
227 get_column_rs_pref => $pref_getcol_rs,
228
37aafa2e 229 # twice so that we make sure only one H::M object spawned
b35500f1 230 chained_resultset => $rs->search_rs ({}, { '+columns' => { foo => 'artistid' } } ),
231 chained_resultset2 => $rs->search_rs ({}, { '+columns' => { bar => 'artistid' } } ),
37aafa2e 232
a8c2c746 233 row_object => $row_obj,
551e711a 234
187ec69a 235 mc_row_object => $mc_row_obj,
236
a8c2c746 237 result_source => $rs->result_source,
551e711a 238
4376a157 239 result_source_handle => $rs->result_source->handle,
240
a8c2c746 241 pager_explicit_count => $pager_explicit_count,
187ec69a 242
243 leaky_resultset => $rs_bind_circref,
244 leaky_resultset_cond => $cond_rowobj,
a8c2c746 245 };
574d9b69 246
6ae62c5c 247 # fire all resultsets multiple times, once here, more below
248 # some of these can't find anything (notably leaky_resultset)
249 my @rsets = grep {
250 blessed $_
251 and
252 (
253 $_->isa('DBIx::Class::ResultSet')
254 or
255 $_->isa('DBIx::Class::ResultSetColumn')
256 )
257 } values %$base_collection;
258
259
260 my $fire_resultsets = sub {
261 local $ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS} = 1;
262 local $SIG{__WARN__} = sigwarn_silencer(
263 qr/Unable to deflate 'filter'-type relationship 'artist'.+related object primary key not retrieved/
264 );
265
266 map
267 { $_, (blessed($_) ? { $_->get_columns } : ()) }
268 map
269 { $_->all }
270 @rsets
271 ;
272 };
b35500f1 273
6ae62c5c 274 push @{$base_collection->{random_results}}, $fire_resultsets->();
b35500f1 275
276 # FIXME - something throws a Storable for a spin if we keep
277 # the results in-collection. The same problem is seen above,
278 # swept under the rug back in 0a03206a, damned lazy ribantainer
279{
280 local $base_collection->{random_results};
218b7c12 281
eb7aa960 282 require Storable;
4376a157 283 %$base_collection = (
284 %$base_collection,
285 refrozen => Storable::dclone( $base_collection ),
286 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
0a03206a 287 pref_row_implicit => $cds_with_impl_artist->next,
4376a157 288 schema => $schema,
289 storage => $storage,
290 sql_maker => $storage->sql_maker,
291 dbh => $storage->_dbh,
cd122820 292 fresh_pager => $rs->page(5)->pager,
293 pager => $pager,
4376a157 294 );
b35500f1 295}
4376a157 296
21aa86aa 297 # FIXME - ideally this kind of collector ought to be global, but attempts
298 # with an invasive debugger-based tracer did not quite work out... yet
299 # Manually scan the innards of everything we have in the base collection
300 # we assembled so far (skip the DT madness below) *recursively*
301 #
302 # Only do this when we do have the bits to look inside CVs properly,
303 # without it we are liable to pick up object defaults that are locked
304 # in method closures
305 if (DBICTest::Util::LeakTracer::CV_TRACING) {
306 visit_refs(
307 refs => [ $base_collection ],
308 action => sub {
309 populate_weakregistry ($weak_registry, $_[0]);
310 1; # true means "keep descending"
311 },
312 );
6ae62c5c 313
314 # do a heavy-duty fire-and-compare loop on all resultsets
315 # this is expensive - not running on install
316 my $typecounts = {};
014846ee 317 if (
318 ! DBICTest::RunMode->is_plain
319 and
320 ! $ENV{DBICTEST_IN_PERSISTENT_ENV}
014846ee 321 ) {
6ae62c5c 322
323 # FIXME - ideally we should be able to just populate an alternative
324 # registry, subtract everything from the main one, and arrive at
325 # an "empty" resulting hash
326 # However due to gross inefficiencies in the ::ResultSet code we
327 # end up recalculating a new set of aliasmaps which could have very
328 # well been cached if it wasn't for... anyhow
329 # What we do here for the time being is similar to the lazy approach
330 # of Devel::LeakTrace - we just make sure we do not end up with more
331 # reftypes than when we started. At least we are not blanket-counting
332 # SVs like D::LT does, but going by reftype... sigh...
333
334 for (values %$weak_registry) {
335 if ( my $r = reftype($_->{weakref}) ) {
336 $typecounts->{$r}--;
337 }
338 }
339
340 # For now we can only reuse the same registry, see FIXME above/below
341 #for my $interim_wr ({}, {}) {
342 for my $interim_wr ( ($weak_registry) x 4 ) {
343
344 visit_refs(
345 refs => [ $fire_resultsets->(), @rsets ],
346 action => sub {
347 populate_weakregistry ($interim_wr, $_[0]);
348 1; # true means "keep descending"
349 },
350 );
351
352 # FIXME - this is what *should* be here
353 #
354 ## anything we have seen so far is cool
355 #delete @{$interim_wr}{keys %$weak_registry};
356 #
6ae62c5c 357 ## moment of truth - the rest ought to be gone
358 #assert_empty_weakregistry($interim_wr);
359 }
360
361 for (values %$weak_registry) {
362 if ( my $r = reftype($_->{weakref}) ) {
363 $typecounts->{$r}++;
364 }
365 }
366 }
367
368 for (keys %$typecounts) {
369 fail ("Amount of $_ refs changed by $typecounts->{$_} during resultset mass-execution")
370 if ( abs ($typecounts->{$_}) > 1 ); # there is a pad caught somewhere, the +1/-1 can be ignored
371 }
21aa86aa 372 }
373
6a43bc0c 374 if ($has_dt) {
375 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
376
377 my $now = DateTime->now;
378 for (1..5) {
379 $base_collection->{"icdt_row_$_"} = $rs->create({
380 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
381 starts_at => $now->clone->add(days => $_),
382 });
383 }
384
385 # re-search
386 my @dummy = $rs->all;
387 }
388
eb7aa960 389 # dbh's are created in XS space, so pull them separately
390 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
391 $base_collection->{"DBI handle $_"} = $_;
392 }
393
65d35121 394 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
395 for keys %$base_collection;
551e711a 396}
397
50261284 398# check that "phantom-chaining" works - we never lose track of the original $schema
399# and have access to the entire tree without leaking anything
400{
401 my $phantom;
402 for (
39b80a73 403 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
50261284 404 sub { shift->source('Artist') },
405 sub { shift->resultset },
406 sub { shift->result_source },
407 sub { shift->schema },
408 sub { shift->resultset('Artist') },
409 sub { shift->find_or_create({ name => 'detachable' }) },
410 sub { shift->result_source },
411 sub { shift->schema },
412 sub { shift->clone },
187ec69a 413 sub { shift->resultset('CD') },
414 sub { shift->next },
415 sub { shift->artist },
416 sub { shift->search_related('cds') },
50261284 417 sub { shift->next },
187ec69a 418 sub { shift->search_related('artist') },
50261284 419 sub { shift->result_source },
420 sub { shift->resultset },
421 sub { shift->create({ name => 'detached' }) },
422 sub { shift->update({ name => 'reattached' }) },
423 sub { shift->discard_changes },
424 sub { shift->delete },
425 sub { shift->insert },
426 ) {
65d35121 427 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
50261284 428 }
429
430 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
431 is( $phantom->name, 'reattached', 'Still correct name' );
432}
a8c2c746 433
307ab4c5 434# Naturally we have some exceptions
435my $cleared;
96577657 436for my $addr (keys %$weak_registry) {
437 my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
438
439 if ($names =~ /^Test::Builder/m) {
c8194884 440 # T::B 2.0 has result objects and other fancyness
96577657 441 delete $weak_registry->{$addr};
c8194884 442 }
96577657 443 elsif ($names =~ /^Hash::Merge/m) {
37aafa2e 444 # only clear one object of a specific behavior - more would indicate trouble
96577657 445 delete $weak_registry->{$addr}
446 unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
307ab4c5 447 }
3619783b 448 elsif ($names =~ /^DateTime::TimeZone::UTC/m) {
449 # DT is going through a refactor it seems - let it leak zones for now
450 delete $weak_registry->{$addr};
451 }
c0fe9332 452 elsif (
75c23ff0 453# # if we can look at closed over pieces - we will register it as a global
454# !DBICTest::Util::LeakTracer::CV_TRACING
455# and
c0fe9332 456 $names =~ /^SQL::Translator::Generator::DDL::SQLite/m
457 ) {
458 # SQLT::Producer::SQLite keeps global generators around for quoted
459 # and non-quoted DDL, allow one for each quoting style
460 delete $weak_registry->{$addr}
461 unless $cleared->{sqlt_ddl_sqlite}->{@{$weak_registry->{$addr}{weakref}->quote_chars}}++;
462 }
307ab4c5 463}
464
187ec69a 465# FIXME !!!
466# There is an actual strong circular reference taking place here, but because
5dc4301c 467# half of it is in XS, so it is a bit harder to track down (it stumps D::FR)
468# (our tracker does not yet do it, but it'd be nice)
469# The problem is:
187ec69a 470#
728f32b5 471# $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
187ec69a 472# ^ /
473# \-------- bound value on prepared/cached STH <-----------/
474#
728f32b5 475{
5dc4301c 476 my @circreffed;
477
478 for my $r (map
479 { $_->{weakref} }
480 grep
481 { $_->{slot_names}{'basic leaky_resultset_cond'} }
482 values %$weak_registry
483 ) {
484 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
728f32b5 485 ok(! defined $r, 'Self-referential RS conditions no longer leak!')
5dc4301c 486 or push @circreffed, $r;
487 }
488
489 if (@circreffed) {
490 is (scalar @circreffed, 1, 'One resultset expected to leak');
491
492 # this is useless on its own, it is to showcase the circref-diag
493 # and eventually test it when it is operational
494 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
495 while (@circreffed) {
496 weaken (my $r = shift @circreffed);
497
498 populate_weakregistry( (my $mini_registry = {}), $r );
499 assert_empty_weakregistry( $mini_registry );
500
501 $r->result_source(undef);
502 }
728f32b5 503 }
187ec69a 504}
505
65d35121 506assert_empty_weakregistry ($weak_registry);
551e711a 507
66917da3 508# we got so far without a failure - this is a good thing
509# now let's try to rerun this script under a "persistent" environment
510# this is ugly and dirty but we do not yet have a Test::Embedded or
511# similar
512
f3ec358e 513# set up -I
514require Config;
515$ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
516($ENV{PATH}) = $ENV{PATH} =~ /(.+)/;
517
518
7617dcc4 519my $persistence_tests;
66917da3 520SKIP: {
521 skip 'Test already in a persistent loop', 1
522 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
523
66917da3 524 skip 'Main test failed - skipping persistent env tests', 1
525 unless $TB->is_passing;
526
cd771d5c 527 skip "Test::Builder\@@{[ Test::Builder->VERSION ]} known to break persistence tests", 1
528 if modver_gt_or_eq_and_lt( 'Test::More', '1.200', '1.301001_099' );
529
66917da3 530 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
531
7617dcc4 532 $persistence_tests = {
533 PPerl => {
534 cmd => [qw/pperl --prefork=1/, __FILE__],
535 },
536 'CGI::SpeedyCGI' => {
537 cmd => [qw/speedy -- -t5/, __FILE__],
538 },
539 };
540
541 # scgi is smart and will auto-reap after -t amount of seconds
542 # pperl needs an actual killer :(
543 $persistence_tests->{PPerl}{termcmd} = [
544 $persistence_tests->{PPerl}{cmd}[0],
545 '--kill',
546 @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
547 ];
548
7be5717e 549 require IPC::Open2;
550
551 for my $type (keys %$persistence_tests) { SKIP: {
53a5200d 552 unless (eval "require $type") {
553 # Don't terminate what we didn't start
554 delete $persistence_tests->{$type}{termcmd};
555 skip "$type module not found", 1;
556 }
7be5717e 557
558 my @cmd = @{$persistence_tests->{$type}{cmd}};
66917da3 559
560 # since PPerl is racy and sucks - just prime the "server"
561 {
562 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
7be5717e 563 system(@cmd);
66917da3 564 sleep 1;
565
7be5717e 566 # see if the thing actually runs, if not - might as well bail now
567 skip "Something is wrong with $type ($!)", 1
568 if system(@cmd);
66917da3 569 }
570
571 for (1,2,3) {
7be5717e 572 note ("Starting run in persistent env ($type pass $_)");
573 IPC::Open2::open2(my $out, undef, @cmd);
574 my @out_lines;
575 while (my $ln = <$out>) {
576 next if $ln =~ /^\s*$/;
577 push @out_lines, " $ln";
578 last if $ln =~ /^\d+\.\.\d+$/; # this is persistence, we need to terminate reading on our end
579 }
580 print $_ for @out_lines;
581 close $out;
582 wait;
583 ok (!$?, "Run in persistent env ($type pass $_): exit $?");
584 ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
66917da3 585 }
586
7be5717e 587 ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
588 if $persistence_tests->{$type}{termcmd};
589 }}
66917da3 590}
591
551e711a 592done_testing;
66917da3 593
594# just an extra precaution in case we blew away from the SKIP - since there are no
595# PID files to go by (man does pperl really suck :(
596END {
7617dcc4 597 if ($persistence_tests->{PPerl}{termcmd}) {
66917da3 598 local $?; # otherwise test will inherit $? of the system()
7617dcc4 599 require IPC::Open3;
600 open my $null, ">", File::Spec->devnull;
601 waitpid(
602 IPC::Open3::open3(undef, $null, $null, @{$persistence_tests->{PPerl}{termcmd}}),
603 0,
604 );
66917da3 605 }
606}