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